From 200d7a58f3838fce8147807deb69e5d596342273 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:34:21 -0600 Subject: [PATCH] build: regenerate bundles after the comment cleanup --- build/Rosetta.luau | 7304 ++++++++----------------------- build/Rosetta.luau.linemap.json | 1072 ++--- build/rosetta.lua | 6197 +++++--------------------- build/rosetta.lua.linemap.json | 1074 ++--- 4 files changed, 3989 insertions(+), 11658 deletions(-) diff --git a/build/Rosetta.luau b/build/Rosetta.luau index bd6adb0..c77713e 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -26,21 +26,8 @@ end __FILES[""] = function() -- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). --- Every format of a category maps onto one standard type (src/Rosetta/Types.luau): a PNG and a WebP both load as an --- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension. --- --- local F = require(Rosetta) -- Roblox: the ModuleScript; LuaJIT: require("rosetta"); luau: "@rosetta" --- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err --- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...) --- local dec = F.audio.open(src) -- streaming decoders (audio / video) --- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format --- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files --- local s = F.saveString(img, { format = "png" }) --- local buf = F.convert(src, "png", opts?) -- load + save --- F.formats() -- the capability list (also docs/FORMATS.md) --- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector --- --- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). +-- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws +-- on bad data or bad arguments: every function returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") @@ -58,12 +45,11 @@ F.version = "0.1.0" F.Err = Err F.Types = Types F.Bytes = Bytes -F.Rbx = Rbx -- the Roblox instance tree helpers (codecs/model/Rbx: tree, instance, add, set, get, find, descendants) +F.Rbx = Rbx F.null = Types.null F.host = host F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step) --- value.kind -> category local KIND_CATEGORY: { [string]: string } = { image = "image", audio = "audio", @@ -82,7 +68,6 @@ local KIND_CATEGORY: { [string]: string } = { playlist = "playlist", } --- ------------------------------------------------------------------------------------------------ registry access local loaded: { [string]: any } = {} local function module(entry: Registry.Entry): (any, Err.Err?) @@ -102,7 +87,6 @@ local function inCategory(entry: Registry.Entry, category: string?): boolean return category == nil or entry.category == category end --- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches local function find(key: string, category: string?): Registry.Entry? local k = string.lower(key) for _, e in Registry do @@ -118,7 +102,6 @@ local function find(key: string, category: string?): Registry.Entry? return nil end --- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?) if format then local e = find(format, category) @@ -158,9 +141,7 @@ local function detect(buf: buffer, name: string?, category: string?, format: str return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) end --- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that --- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered = --- true: open the format, which renders it, instead of decoding it) +-- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true) local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean) local entry, err = detect(buf, name, o.category, o.format) if not entry and o.category == "audio" then @@ -185,7 +166,6 @@ local function tag(value: any, formatName: string) end end --- full decode through a streaming decoder (audio formats with open but no decode) local function drain(dec: any): any local channels = dec.channels local parts, total = {}, 0 @@ -209,7 +189,7 @@ local function drain(dec: any): any return a end --- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs) +-- siblings resolve relative to path's directory only (no absolute paths, no "..", no URLs) local function siblings(path: string): (uri: string) -> buffer? local dir = string.match(path, "^(.*[/\\])") or "" return function(uri: string): buffer? @@ -229,13 +209,10 @@ local function siblings(path: string): (uri: string) -> buffer? end end --- ------------------------------------------------------------------------------------------------ API type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options local load: (src: any, opts: Options?) -> (any, Err.Err?) --- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer --- | string, else the files next to the descriptor on hosts with a file system local function pageLoader(value: any, name: string?, o: Options) if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then return @@ -256,7 +233,7 @@ local function pageLoader(value: any, name: string?, o: Options) src = (dir :: string) .. file end if type(src) == "table" then - return src -- already an Image + return src end if src == nil then return nil, Err.new(Err.IO, "no data for page " .. file) @@ -265,11 +242,8 @@ local function pageLoader(value: any, name: string?, o: Options) end end --- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a --- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer --- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's --- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the --- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font. +-- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with +-- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer) local function unwrap(value: any, formatName: string, o: Options): any if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then return value @@ -318,18 +292,8 @@ local function unwrap(value: any, formatName: string, o: Options): any return v end --- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format, --- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> --- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for --- the embedded parts) when called directly. --- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. --- --- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded --- as music (sniffed, or as the given format). --- --- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets --- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / --- FLAC / AC-3 as they are), opened through F.open with that format. +-- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule, +-- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are) local function openAudio(demuxer: any, track: any): (any, Err.Err?) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then @@ -371,7 +335,6 @@ local function withHooks(o: Options): Options end end if c.decodeModule == nil then - -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) return F.load(b, { category = "music", format = format }) end @@ -379,7 +342,6 @@ local function withHooks(o: Options): Options return c end --- load(src, opts?) -> value | nil, Err function F.load(src: any, opts: Options?): (any, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -399,7 +361,6 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) return nil, merr end if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then - -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder o = table.clone(o) o.resolve = siblings(name) end @@ -431,7 +392,6 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) end load = F.load --- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err function F.open(src: any, opts: Options?): (any, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -474,10 +434,6 @@ end local encodeTextures: (scene: any) -> Err.Err? --- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil, --- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are --- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap --- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is. local function videoToImage(v: any, o: Options): (any, Err.Err?) if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then return nil, Err.new(Err.ARG, "save: not a VideoDecoder") @@ -536,9 +492,6 @@ local function videoToImage(v: any, o: Options): (any, Err.Err?) return img, nil end --- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method --- for other engines) or a Midi (music/midi render) | --- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } local function renderMusic(value: any, o: Options): (any, Err.Err?) local ok, dec, err @@ -549,8 +502,7 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?) end ok, dec, err = pcall(m.render, value, o) elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then - -- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an - -- empty Decoder carrying .err) + -- AHX / HVL render through the Module's own method (a failed render is an empty Decoder carrying .err) ok, dec = pcall(value.render, value, o) if ok and type(dec) == "table" and dec.err then return nil, dec.err @@ -568,7 +520,6 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?) return dec, nil end --- the writable format for a value: opts.format, the destination's extension, or the source format local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) local category = o.category if category == nil and type(value) == "table" and type(value.kind) == "string" then @@ -628,17 +579,12 @@ function encodeTextures(scene: any): Err.Err? return nil end --- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files --- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the --- caller's opts.files); with a dest they are written next to it. function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local entry, m, err, key = encoderFor(value, dest, o) if not entry then return nil, err end - -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file) - -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin) o = table.clone(o) o.format = o.format or key if dest then @@ -647,7 +593,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s o.files = {} end elseif o.files == nil and entry.caps.extraFiles then - o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages + o.files = {} end if entry.category == "video" and type(value) == "table" and value.kind == "image" then local v, verr = F.video.fromImage(value) @@ -664,7 +610,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s value = img end if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then - local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts + local dec, rerr = renderMusic(value, o) if not dec then return nil, rerr end @@ -705,7 +651,6 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s return buf end --- saveString(value, opts?) -> string | nil, Err function F.saveString(value: any, opts: Options?): (string?, Err.Err?) local buf, err = F.save(value, nil, opts) if not buf then @@ -714,7 +659,6 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?) return buffer.tostring(buf), nil end --- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local value, err = F.load(src, o) @@ -727,7 +671,6 @@ function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { return F.save(value, o.out, so) end --- detect(src, opts?) -> format name | nil, Err function F.detect(src: any, opts: Options?): (string?, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -751,7 +694,6 @@ end type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } --- formats(category?) -> { FormatInfo } (no format module is loaded) function F.formats(category: string?): { FormatInfo } local out = {} for _, e in Registry do @@ -762,7 +704,6 @@ function F.formats(category: string?): { FormatInfo } return out end --- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info) function F.format(name: string): (any, Err.Err?) local e = find(name) if not e then @@ -771,8 +712,6 @@ function F.format(name: string): (any, Err.Err?) return module(e) end --- ------------------------------------------------------------------------------------------------ category facades --- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category local function with(opts: Options?, category: string): Options local o: Options = if opts then table.clone(opts) else {} o.category = category @@ -797,9 +736,6 @@ for category in Types.CATEGORIES do end F.data.null = Types.null --- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; --- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel --- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. for _, fn in { "toBodies", "fromBodies", "tessellate" } do local name: string = fn F.cad[name] = function(value: any, opts: Options?): (any, any) @@ -821,16 +757,12 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do return a, b end end --- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker --- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do local name: string = fn F.music[name] = function(...: any): (any, Err.Err?) return (F.ops.music :: any)[name](...) end end --- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited --- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) if type(img) ~= "table" or img.kind ~= "image" then return nil, Err.new(Err.ARG, "fromImage: expected an Image") @@ -856,18 +788,11 @@ F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) local src = type(img.meta) == "table" and img.meta.source return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) end --- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence: --- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1) F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) return Video.fromFrames(images, delays, opts) end --- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) F.video.codecs = Video --- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or --- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images --- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose --- image format is missing or broken keep image = nil and report an Err. F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err }) local errs: { [number]: Err.Err } = {} if type(scene) ~= "table" or type(scene.textures) ~= "table" then @@ -893,15 +818,6 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E return scene, errs end --- ------------------------------------------------------------------------------------------------ ops --- F.ops: editing on the standard types, loaded on first use. --- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... --- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... --- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves --- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, --- concat, fade, peak, rms --- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music) --- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector local OPS: { [string]: () -> any } = { image = function() return ImageOps @@ -3062,22 +2978,15 @@ return list end __FILES["Types"] = function() --- 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 = __include("core/Err") local Types = {} 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). type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p" @@ -3128,7 +3037,6 @@ 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 @@ -3149,16 +3057,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 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) type Decoder = { sampleRate: number, channels: number, @@ -3166,13 +3071,12 @@ type Decoder = { duration: number, -- seconds bitrate: number, -- bits per second (average) tags: Tags, - -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end); out (if given) is reused when big enough + -- read: interleaved f32, frames read (0 at the end); out is reused when big enough read: (self: any, n: number, out: buffer?) -> (buffer, number), seek: (self: any, seconds: number) -> (), position: (self: any) -> number, -- seconds } --- a fully decoded sound (F.load / F.audio.load) type Audio = { kind: "audio", sampleRate: number, @@ -3197,7 +3101,6 @@ function Audio.new(sampleRate: number, channels: number, frames: number): Audio end Types.Audio = Audio --- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI) type Module = { kind: "music", title: string, @@ -3226,12 +3129,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. type Track = { @@ -3274,11 +3171,9 @@ 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 } @@ -3316,23 +3211,10 @@ 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`. type Accessor = { data: buffer, -- tightly packed, little endian type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16", @@ -3440,7 +3322,6 @@ 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 @@ -3452,7 +3333,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 @@ -3493,7 +3373,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, @@ -3509,7 +3388,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 } @@ -3526,7 +3404,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 } } @@ -3536,8 +3413,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] @@ -3600,7 +3475,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 } @@ -3616,7 +3490,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 @@ -3646,8 +3519,6 @@ function Scene.nodeMatrix(node: Node): { number } } end 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 {} @@ -3691,7 +3562,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) @@ -3704,7 +3574,6 @@ type Cad = { meta: { [string]: any }, } --- ------------------------------------------------------------------------------------------------ Font type Font = { kind: "font", info: { family: string?, style: string?, fullName: string?, [string]: any }, @@ -3741,7 +3610,6 @@ type BitmapStrike = { map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph) } --- ------------------------------------------------------------------------------------------------ Archive type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } type Archive = { kind: "archive", @@ -3753,7 +3621,6 @@ 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() @@ -3764,12 +3631,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 @@ -3778,11 +3641,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 @@ -3790,7 +3651,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 @@ -3803,8 +3663,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 @@ -3822,8 +3680,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 = {}, {} @@ -3922,7 +3778,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 @@ -3935,11 +3790,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 @@ -3960,8 +3813,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 @@ -4017,13 +3869,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) @@ -4063,7 +3913,6 @@ type XmlNode = { [string]: any, } --- ------------------------------------------------------------------------------------------------ Vector type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } type VectorPath = { d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands @@ -4096,7 +3945,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`). @@ -4114,17 +3962,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 @@ -4150,7 +3995,6 @@ function TileMap.new(width: number, height: number, tileWidth: number, tileHeigh end Types.TileMap = TileMap --- ------------------------------------------------------------------------------------------------ Subtitles type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } } local Subtitles = {} @@ -4159,7 +4003,6 @@ function Subtitles.new(): Subtitles end Types.Subtitles = Subtitles --- ------------------------------------------------------------------------------------------------ Playlist -- the playlist-luau shape type PlaylistEntry = { url: string, @@ -4182,7 +4025,6 @@ 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) type Caps = { decode: boolean, encode: boolean, [string]: any } type Format = { @@ -4219,14 +4061,9 @@ return Types end __FILES["archive/7z"] = function() --- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose --- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) --- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / --- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, --- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, --- Windows / Unix attributes, folder and file CRC-32s (verified on read). --- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other --- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. +-- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA / +-- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s. +-- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -4251,8 +4088,8 @@ local SevenZip = { } type DecodeOptions = { - maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30) - checkCrc: boolean?, -- verify CRC-32s on read (default true) + maxBytes: number?, -- default 2^30, per folder or header + checkCrc: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -4319,7 +4156,6 @@ local function packStart(ctx: Ctx, s: Header.Streams, index: number): number end local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) - -- coder -> first in / out stream index local inBase, outBase = {}, {} local ni, no = 0, 0 for i, c in f.coders do @@ -4350,7 +4186,6 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf if size > ctx.maxBytes then return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) end - -- the coder's input: another coder's output, or a packed stream local inIdx = inBase[ci] local src: buffer, so: number, sl: number local bound = nil @@ -4512,7 +4347,6 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false - -- folder caches and the substream -> folder map local cache: { [number]: buffer } = {} local subFolder: { number }, subOffset: { number } = {}, {} do @@ -4612,10 +4446,7 @@ return SevenZip end __FILES["archive/7z/Header"] = function() --- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): --- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / --- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and --- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +-- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info. local Text = __include("codecs/text/Text") local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -5118,8 +4949,6 @@ local function header(r: Bytes.Reader): Parsed return p end --- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to --- decode and parse again. function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) local r = Bytes.reader(b, o, n) local ok, res = pcall(function(): Parsed @@ -5144,16 +4973,9 @@ return Header end __FILES["archive/adf"] = function() --- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an --- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international, --- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through --- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the --- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked --- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...), --- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are --- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description --- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk --- images (use the partition contents), dircache blocks (not needed to read). +-- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables, +-- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1 +-- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -5234,7 +5056,6 @@ local function date(d: Disk, blk: number, off: number): number return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH end --- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables) local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?) local out = {} local blk = hdr @@ -5434,15 +5255,9 @@ return Adf end __FILES["archive/applesingle"] = function() --- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740): --- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2: --- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags). --- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the --- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name --- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds --- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with --- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS / --- MS-DOS / AFP info entries (kept in meta.entries as id + length). +-- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1), +-- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile. +-- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -5460,10 +5275,10 @@ local AppleSingle = { caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, } -type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it) +type DecodeOptions = { name: string?, maxBytes: number? } type EncodeOptions = { - double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false) - name: string?, -- the name of a buffer / string value (default "data") + double: boolean?, -- default false + name: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -5626,15 +5441,9 @@ return AppleSingle end __FILES["archive/ar"] = function() --- archive/ar: Unix ar archives ("!\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/" --- and "/SYM64/" symbol tables) and BSD (inline "#1/" names, the "__.SYMDEF" symbol table), read into the standard --- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not --- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their --- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and --- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed --- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and --- deb(5) (dpkg); no code ported. Not supported: thin archives ("!"), writing symbol tables (a re-written --- library needs ranlib), writing .deb control data (any entries write as a plain ar). +-- archive/ar: Unix ar ("!\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" +-- symbols) and BSD ("#1/", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. +-- Not supported: thin archives ("!"), writing symbol tables or .deb control data. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -5658,10 +5467,10 @@ local Ar = { type DecodeOptions = { maxEntries: number?, -- default 1e6 - maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26) + maxBytes: number?, -- .deb control.tar limit (default 2^26) } type EncodeOptions = { - variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu" + variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu" } -- ------------------------------------------------------------------------------------------------ constants @@ -5761,7 +5570,6 @@ local function controlFields(s: string): { [string]: string } return out end --- control.tar[.ext] -> the control file's fields, or nil local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }? local ext = string.match(name, "^control%.tar%.?(%w*)$") local raw: buffer? @@ -5810,7 +5618,7 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local variant = "gnu" local longNames: string? = nil local symbols: { { name: string, offset: number } }? = nil - local offsets: { [number]: string } = {} -- header offset (from the start) -> member name + local offsets: { [number]: string } = {} local count = 0 local p = base + 8 while p < e do @@ -5908,7 +5716,6 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) a.meta.symbols = out end a.meta.source = { format = "ar", variant = variant } - -- Debian packages local list = a._entries if list[1] and list[1].name == "debian-binary" then a.meta.source.variant = "deb" @@ -6027,7 +5834,6 @@ function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" }) function Ar.new(): any local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } @@ -6038,13 +5844,9 @@ return Ar end __FILES["archive/arj"] = function() --- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS, --- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style --- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type --- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM). --- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files, --- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those --- entries / calls). +-- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh +-- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files, +-- multi-volume archives, chapters, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6064,7 +5866,7 @@ local Arj = { } type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } @@ -6252,13 +6054,9 @@ return Arj end __FILES["archive/binhex"] = function() --- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name, --- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified: --- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a --- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file --- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter --- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with --- archive/macbinary), several files in one .hqx (only the first is read). +-- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as +-- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several +-- files in one .hqx (the first is read). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6278,7 +6076,7 @@ local Binhex = { } type DecodeOptions = { maxBytes: number? } -- default 2^30 -type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") +type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ constants local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" @@ -6299,7 +6097,6 @@ function Binhex.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input) local function unhex(text: string, maxBytes: number): (buffer?, string?) local banner = string.find(text, BANNER, 1, true) if not banner then @@ -6443,7 +6240,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) end local src = body:finish() - -- RLE90 local rle = Bytes.writer(buffer.len(src) + 16) local n = buffer.len(src) local i = 0 @@ -6497,7 +6293,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork function Binhex.new(): any local a = Archive.new("binhex", encoder) a.meta.source = { format = "binhex" } @@ -6508,11 +6303,8 @@ return Binhex end __FILES["archive/br"] = function() --- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar --- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data"). --- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number: --- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a --- low confidence, so the extension decides between candidates. +-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read. +-- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6531,8 +6323,8 @@ local Br = { } type DecodeOptions = { - name: string?, -- the file name (the api passes it): the entry is named after it - maxBytes: number?, -- refuse output larger than this (default 2^30) + name: string?, + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants @@ -6586,10 +6378,8 @@ return Br end __FILES["archive/bz2"] = function() --- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated --- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), --- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported: --- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). +-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read, +-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6608,8 +6398,8 @@ local Bz2 = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger output (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -6652,16 +6442,9 @@ return Bz2 end __FILES["archive/cab"] = function() --- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and --- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose --- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum --- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local --- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) --- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same --- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the --- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a --- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), --- signed / self-extracting stubs before the header. +-- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried +-- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one +-- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6683,14 +6466,14 @@ local Cab = { } type DecodeOptions = { - maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65535 - verify: boolean?, -- check the data block checksums (default true) + verify: boolean?, -- default true } type EncodeOptions = { compression: ("mszip" | "none")?, -- default "mszip" - level: number?, -- deflate level 0..9 (default 6) - setId: number?, -- the cabinet set id (default 0) + level: number?, -- 0..9 (default 6) + setId: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -6716,8 +6499,7 @@ type Folder = { } type Block = { at: number, len: number, size: number } --- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next --- cabinet (a block with cbUncomp 0) +-- a block with cbUncomp 0 runs into the next cabinet local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) local list: { Block } = {} local p = f.dataAt @@ -6748,7 +6530,6 @@ local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: b return list, total, false end --- the decompressed data of a folder's blocks local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) local method = bit32.band(typ, 15) local out = buffer.create(total) @@ -6844,7 +6625,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) flags = flags, reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, } - -- folders local folders: { Folder } = {} local methods = {} for i = 1, cFolders do @@ -6869,7 +6649,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if cFiles > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries files") end - -- the folder cache: the last decompressed folder local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) if cachedIndex == f.index then @@ -6886,7 +6665,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) cachedIndex, cachedData, cachedRuns = f.index, data, runs == true return data, nil, runs end - -- files local fr = r:sub(coffFiles) for _ = 1, cFiles do local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() @@ -6959,7 +6737,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local compression = o.compression or "mszip" @@ -6987,7 +6764,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) if total > 0x7FFF8000 then return nil, Err.new(Err.ARG, "more than 2 GB of data") end - -- the folder data, in 32 KB blocks local folder = buffer.create(total) local p = 0 for _, f in files do @@ -7022,7 +6798,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) s += n end local blob = data:finish() - -- names and the file table local table_ = Bytes.writer(64 + #files * 32) local offset = 0 for _, f in files do @@ -7070,7 +6845,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) function Cab.new(): any local a = Archive.new("cab", encode) a.meta.source = { format = "cab" } @@ -7083,16 +6857,14 @@ __FILES["archive/cab/Sum"] = @native function() --- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 --- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format --- description ([MS-CAB] 2.4, CFDATA.csum). +-- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most +-- significant first, then the cbData / cbUncomp word. local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift local Sum = {} --- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) @native function Sum.of(buf: buffer, off: number, len: number, seed: number): number if off < 0 or len <= 0 or off + len > blen(buf) then return seed @@ -7116,7 +6888,6 @@ local Sum = {} return bxor(s, tail) end --- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) @native function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end @@ -7125,12 +6896,8 @@ return Sum end __FILES["archive/cpio"] = function() --- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the --- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc --- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters), --- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor, --- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1") --- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped). +-- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as +-- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7150,12 +6917,12 @@ local CpioFormat = { type DecodeOptions = { maxEntries: number?, -- default 1e6 - verify: boolean?, -- crc archives: check the data sums (default true) + verify: boolean?, -- default true } type EncodeOptions = { variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc" - format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default - block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none) + format: string?, -- any other value (the api's "cpio") means the variant default + block: number?, -- default 512, as GNU cpio; 1 = none } -- ------------------------------------------------------------------------------------------------ sniff @@ -7279,7 +7046,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er rdevminor = num(e.rdevminor), }) end - -- opts.format may also be the api's format name ("cpio"): the variant default then local o: any = opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc" @@ -7288,7 +7054,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write() function CpioFormat.new(): any local a = Archive.new("cpio", encode) a.meta.source = { format = "cpio" } @@ -7299,16 +7064,9 @@ return CpioFormat end __FILES["archive/d64"] = function() --- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info --- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and --- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are --- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are --- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII --- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the --- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any --- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS --- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers' --- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents. +-- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names +-- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as +-- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7328,8 +7086,8 @@ local D64 = { type DecodeOptions = { maxEntries: number? } -- default 4096 type EncodeOptions = { variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64" - disk: string?, -- disk name (default "rosetta" / the name read) - id: string?, -- two-character disk id (default "fl") + disk: string?, -- default "rosetta" / the name read + id: string?, -- default "fl" } -- ------------------------------------------------------------------------------------------------ constants @@ -7429,7 +7187,6 @@ local function encoder(a: any, o: any?): (buffer?, Err.Err?) return D64.encode(a, o) end --- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?) local w = Bytes.writer() local seen: { [number]: boolean } = {} @@ -7474,7 +7231,6 @@ function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) a.meta.tracks = geo.tracks a.meta.errorInfo = r:size() ~= geo.total a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } - -- the directory chain local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) local seen: { [number]: boolean } = {} local count = 0 @@ -7536,7 +7292,6 @@ end -- ------------------------------------------------------------------------------------------------ encode -- BAM layout per variant: where each track's free count + bitmap lives local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number) - -- returns (offset of the free count, offset of the bitmap, bitmap bytes) local dir = geo.offsets[geo.dirTrack] if geo.kind == "d81" then local side = if t <= 40 then 1 else 2 @@ -7586,7 +7341,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local function pad16(s: string): string return s .. string.rep("\160", 16 - #s) end - -- header / BAM local firstDir if variant == "d81" then buffer.writestring(img, dir, "\40\3\68\0") @@ -7713,7 +7467,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" }) function D64.new(variant: string?): any local a = Archive.new("d64", encoder) a.meta.variant = variant or "d64" @@ -7725,12 +7478,9 @@ return D64 end __FILES["archive/fat"] = function() --- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the --- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 --- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the --- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy --- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a --- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. +-- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat. +-- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and +-- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7749,12 +7499,12 @@ local FatFormat = { } type DecodeOptions = { - partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself) + partition: number?, -- 1..4 (default: the first FAT partition, or the image itself) maxEntries: number?, -- default 65536 } type EncodeOptions = { - size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) - label: string?, -- volume label + size: number?, -- KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) + label: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -7840,7 +7590,6 @@ function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) function FatFormat.new(): any local a = Archive.new("fat", encoder) a.meta.source = { format = "fat" } @@ -7851,11 +7600,9 @@ return FatFormat end __FILES["archive/grp"] = function() --- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, --- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive --- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they --- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. --- Not supported: the "GRP 2" / RFF / SSI variants. +-- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data), +-- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12 +-- bytes). Not supported: the "GRP 2" / RFF / SSI variants. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7875,7 +7622,7 @@ local Grp = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxEntries: number? } -- default 1e6 -type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false) +type EncodeOptions = { upper: boolean? } -- Build looks names up case-insensitively; default false -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "KenSilverman" @@ -7957,7 +7704,6 @@ function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty GRP Archive: a:add(name, data); a:write() function Grp.new(): any local a = Archive.new("grp", encode) a.meta.source = { format = "grp" } @@ -7968,11 +7714,9 @@ return Grp end __FILES["archive/gzip"] = function() --- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the --- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d --- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive --- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the --- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification. +-- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate). +-- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz). +-- Not supported: FHCRC verification. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7992,11 +7736,11 @@ local Gzip = { caps = { decode = true, encode = true, stream = true }, } -type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME +type DecodeOptions = { name: string? } type EncodeOptions = { level: number?, -- 0..9, default 6 - name: string?, -- FNAME (default: the entry's name; none for a buffer) - mtime: number?, -- MTIME (default: the entry's mtime, else 0) + name: string?, -- default: the entry's name; none for a buffer + mtime: number?, -- default: the entry's mtime, else 0 } -- ------------------------------------------------------------------------------------------------ sniff @@ -8005,7 +7749,6 @@ function Gzip.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) local function header(b: buffer, o: number, e: number): { [string]: any } local h: { [string]: any } = {} if o + 10 > e then @@ -8140,7 +7883,6 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) function Gzip.new(data: (buffer | string)?, name: string?): any local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) return Gzip.encode(arc, o) @@ -8157,14 +7899,9 @@ return Gzip end __FILES["archive/iso"] = function() --- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660: --- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories; --- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files. --- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts --- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El --- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one. --- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored --- bytes), multi-session images (the first session). +-- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet, +-- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files +-- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8183,7 +7920,7 @@ local Iso = { } type DecodeOptions = { - prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain) + prefer: ("rockridge" | "joliet" | "iso9660")?, -- default: Rock Ridge, else Joliet, else plain maxEntries: number?, -- default 1e6 } @@ -8234,16 +7971,9 @@ return Iso end __FILES["archive/lha"] = function() --- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their --- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS --- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, --- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. --- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower --- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header --- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu --- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), --- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or --- at the first header found in the first 64 KB). +-- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3, +-- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2, +-- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8263,7 +7993,7 @@ local Lha = { } type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } type EncodeOptions = {} @@ -8293,7 +8023,7 @@ function Lha.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) +-- "." / ".." collapsed as lhasa does local function path(s: string): string s = string.gsub(s, "[\\\255]", "/") local parts = {} @@ -8325,7 +8055,6 @@ type Header = { dataAt: number, } --- the extended headers from offset p (size field width w), until a zero size; returns the end offset local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) local size = first local guard = 0 @@ -8373,7 +8102,6 @@ local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } --- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker local function header(r: Bytes.Reader, p: number): (Header?, string?) local limit = r:size() if p >= limit or r:sub(p, 1):u8() == 0 then @@ -8476,7 +8204,6 @@ function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local p = 0 - -- a self-extracting stub: find the first header if not isHeader(r:peek(22)) then local head = r:peek(65536) local at = nil @@ -8618,7 +8345,7 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) dirPart, base = full .. "/", "" end local h = Bytes.writer() - h:u16le(0) -- total size, patched + h:u16le(0) h:string(if e.dir then "-lhd-" else "-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) @@ -8659,7 +8386,6 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) function Lha.new(): any local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } @@ -8670,15 +8396,9 @@ return Lha end __FILES["archive/lz4"] = function() --- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the --- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api --- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy --- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed --- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified --- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks --- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; --- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: --- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. +-- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable +-- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes +-- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8698,15 +8418,15 @@ local Lz4Format = { } type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true; the header checksum is always checked + name: string?, } type EncodeOptions = { blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) blockChecksum: boolean?, -- default false contentChecksum: boolean?, -- default true - contentSize: boolean?, -- store the content size (default false) + contentSize: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -8742,7 +8462,6 @@ end type Out = { buf: buffer, n: number, max: number } --- room for k more bytes in the output (doubling, up to max) | false local function room(out: Out, k: number): boolean local need = out.n + k if need > out.max then @@ -8756,7 +8475,6 @@ local function room(out: Out, k: number): boolean return true end --- one LZ4 frame at p -> the input offset after it | nil, Err local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) if p + 7 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) @@ -8881,7 +8599,6 @@ local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err. return q, nil end --- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then @@ -8951,7 +8668,6 @@ function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err? end -- ------------------------------------------------------------------------------------------------ encode --- compress(data, opts?) -> one LZ4 frame | nil, Err function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) if not b then @@ -9012,7 +8728,6 @@ function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffe return w:finish(), nil end --- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local data, err = Archive.streamData(value) if not data then @@ -9025,13 +8740,9 @@ return Lz4Format end __FILES["archive/macbinary"] = function() --- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags, --- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III --- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its --- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry --- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / --- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the --- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped). +-- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III +-- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile. +-- Supports: read, write III. Not supported: the secondary header's content (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9051,10 +8762,9 @@ local MacBinary = { } type DecodeOptions = { maxBytes: number? } -- default 2^30 -type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") +type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ sniff --- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o local function version(b: buffer, o: number, len: number): string? if len < 128 then return nil @@ -9228,18 +8938,9 @@ return MacBinary end __FILES["archive/mpq"] = function() --- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the --- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset --- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block --- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block --- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded --- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 --- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks --- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive --- Format", and StormLib's documentation); no code taken. --- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET --- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, --- writing. +-- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports: +-- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib / +-- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9263,9 +8964,9 @@ local Mpq = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)") + names: { string }?, maxEntries: number?, -- default 1e6 - maxBytes: number?, -- the largest file read (default 2^30) + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants @@ -9314,7 +9015,6 @@ local function unsparse(b: buffer, at: number, n: number, want: number): (buffer return out, nil end --- one compressed sector (mask byte first) -> want bytes local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) if n < 1 then return nil, Err.new(Err.CORRUPT, "empty compressed sector") @@ -9380,7 +9080,6 @@ end type Block = { offset: number, csize: number, size: number, flags: number } --- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) local flags = blk.flags if band(flags, FLAG_PATCH) ~= 0 then @@ -9479,7 +9178,6 @@ local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") end --- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil local function findHeader(r: Bytes.Reader): number? local size = r.limit - r.base local p = 0 @@ -9557,7 +9255,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local mask = hashCount - 1 local pow2 = band(hashCount, mask) == 0 - -- lookup(name) -> block index (1-based) | nil local function lookup(name: string): number? local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) local start = if pow2 then band(h0, mask) else h0 % hashCount @@ -9581,7 +9278,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local blk = blocks[bi] return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) end - -- names: (listfile) and opts.names local names: { string } = {} for _, internal in { "(attributes)", "(signature)", "(user data)" } do table.insert(names, internal) @@ -9642,7 +9338,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) Mpq.hash = Crypt.hash return Mpq @@ -9650,10 +9345,8 @@ end __FILES["archive/mpq/Crypt"] = @native function() --- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file --- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois --- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every --- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +-- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and +-- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32. local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot @@ -9676,7 +9369,7 @@ do end end --- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +-- name hash: ASCII upper case, '/' as '\' @native function Crypt.hash(name: string, kind: number): number local s1, s2 = 0x7FED7FED, 0xEEEEEEEE local base = kind * 0x100 @@ -9693,7 +9386,7 @@ end return s1 end --- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +-- whole u32s; a trailing partial word is left as is @native function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) local s2 = 0xEEEEEEEE local k = key % TWO32 @@ -9707,7 +9400,7 @@ end end end --- base name of an archived path (the file key uses it) +-- the file key uses the base name @native function Crypt.baseName(name: string): string return string.match(name, "([^\\/]*)$") or name end @@ -9716,11 +9409,9 @@ return Crypt end __FILES["archive/pak"] = function() --- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the --- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored --- bytes) and written from any Archive value. Written from the format description in the Quake source release --- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. --- Not supported: Daikatana's compressed PAK entries. +-- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte +-- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read +-- (lazy), write. Not supported: Daikatana's compressed entries. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9842,7 +9533,6 @@ function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() function Pak.new(variant: ("quake" | "sin")?): any local a = Archive.new("pak", encode) a.meta.source = { format = "pak", variant = variant or "quake" } @@ -9853,15 +9543,9 @@ return Pak end __FILES["archive/rpm"] = function() --- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature --- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in --- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with --- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload --- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed --- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not --- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package --- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio" --- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms. +-- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte +-- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed. +-- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9884,7 +9568,7 @@ local Rpm = { } type DecodeOptions = { - maxBytes: number?, -- the largest decompressed payload (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 1e6 } @@ -9893,7 +9577,6 @@ local LEAD_MAGIC = "\237\171\238\219" local HEADER_MAGIC = "\142\173\232\1" local RPMFILE_GHOST = 64 --- the tags meta.rpm names local NAMES: { [number]: string } = { [1000] = "name", [1001] = "version", @@ -9927,7 +9610,6 @@ function Rpm.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a header structure at p -> { [tag] = value }, end offset | nil, Err local function header(b: buffer, p: number, e: number): (any, any) if p + 16 > e then return nil, Err.new(Err.TRUNCATED, "header past the end", p) @@ -10000,7 +9682,6 @@ local function header(b: buffer, p: number, e: number): (any, any) return tags, se end --- the file list of the header: { name, size, mode, mtime, link, user, group, flags } local function files(tags: { [number]: any }): { any } local names: { string } = {} local bn, dn, di = tags[1117], tags[1118], tags[1116] @@ -10035,7 +9716,6 @@ local function strip(name: string): string return (string.gsub(name, "^%.?/+", "")) end --- the payload: decompressed, then its cpio entries by stripped name local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?) local n = e - p local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 } @@ -10167,7 +9847,6 @@ function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local a, err = Rpm.decode(r, opts) if not a then @@ -10188,11 +9867,8 @@ return Rpm end __FILES["archive/tar"] = function() --- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value --- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + --- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which --- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). --- Not supported: sparse files, multi-volume archives. +-- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any +-- Archive. Not supported: sparse files, multi-volume archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10299,7 +9975,6 @@ function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() function TarFormat.new(): any local a = Archive.new("tar", encode) a.meta.source = { format = "tar" } @@ -10310,13 +9985,9 @@ return TarFormat end __FILES["archive/uu"] = function() --- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin " block of a --- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode); --- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each --- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and --- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils --- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings --- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex). +-- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block); +-- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings +-- split over several files, yEnc (archive/yenc), BinHex (archive/binhex). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10334,11 +10005,11 @@ local Uu = { caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, } -type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 type EncodeOptions = { variant: ("uu" | "xx" | "base64")?, -- default "uu" - mode: number?, -- file mode when the entry has none (default 0o644) - name: string?, -- the name of a buffer / string value (default "data") + mode: number?, -- default 0o644 + name: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -10361,7 +10032,6 @@ function Uu.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the value of character c in a variant, or nil local function value(c: number, xx: boolean): number? if xx then return XX_VALUE[c] @@ -10372,7 +10042,6 @@ local function value(c: number, xx: boolean): number? return nil end --- does a data line fit the variant: every character valid and the length matching the count character local function fits(line: string, xx: boolean): boolean local n = value(string.byte(line, 1) or 0, xx) if not n then @@ -10390,7 +10059,6 @@ local function fits(line: string, xx: boolean): boolean return true end --- decode the uu / xx lines of a block into a buffer (nil, message on a bad line) local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?) local total = 0 for _, l in lines do @@ -10577,7 +10245,6 @@ function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant }) function Uu.new(): any local a = Archive.new("uu", encoder) a.meta.source = { format = "uu" } @@ -10588,15 +10255,9 @@ return Uu end __FILES["archive/vpk"] = function() --- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the --- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes --- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the --- numbered part files "_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes --- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's --- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), --- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the --- Valve Developer Community VPK file format page; no code taken. --- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. +-- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, +-- embedded (index 0x7fff) or part-file data ("_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file +-- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10618,10 +10279,10 @@ local Vpk = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - verify: boolean?, -- check each entry's CRC-32 on read (default true) - resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...) + verify: boolean?, -- default true + resolve: ((name: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names + name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk" maxEntries: number?, -- default 1e6 } type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) @@ -10644,7 +10305,6 @@ local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Vpk.encode(archive, opts) end --- the part file `index` as a buffer (cached per archive) local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) local cache: { [number]: buffer } = {} local prefix = "pak01" @@ -10896,7 +10556,6 @@ function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() function Vpk.new(version: number?): any local a = Archive.new("vpk", encode) a.meta.source = { format = "vpk", version = version or 2 } @@ -10907,22 +10566,9 @@ return Vpk end __FILES["archive/wad"] = function() --- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the --- standard Archive and written from any Archive value, plus the lumps as game data: --- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map --- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer --- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image --- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) --- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) --- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) --- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene --- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) --- Entry names: the lump names, except lumps of a map, named "/" ("MAP01/THINGS"), and later lumps --- repeating an earlier name, named "~" (n = 2, 3, ...), so every entry is unique; writing strips both again --- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom --- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. --- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, --- big-endian (Jaguar) WADs, compressed Jaguar lumps. +-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, +-- palettes, pictures, wall textures and maps. Entry names: "/", repeats "~". Not supported: UDMF +-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10947,18 +10593,18 @@ local Wad = { type DecodeOptions = { maxEntries: number? } -- default 1e6 type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" type Lump = { - name: string, -- the lump name as stored (upper case) - entry: string, -- the Archive entry name - index: number, -- 1-based position in the directory + name: string, + entry: string, + index: number, offset: number, size: number, - namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers) - map: string?, -- the map this lump belongs to + namespace: string?, -- between *_START / *_END markers + map: string?, marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) } type MapOptions = { - textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true) - palette: number?, -- PLAYPAL palette index (default 0) + textures: boolean?, -- default true + palette: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -11047,7 +10693,6 @@ function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if isMapMarker then map, udmf = name, nextName == "TEXTMAP" end - -- namespaces local marker: boolean = false local pre = string.match(name, "^(%w+)_START$") local post = string.match(name, "^(%w+)_END$") @@ -11123,7 +10768,7 @@ local function info(a: any): any return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil end --- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +-- the last lump named name (PWAD order: later lumps override) local function find(w: any, name: string, ns: string?): Lump? local up = string.upper(name) local best: Lump? = nil @@ -11146,20 +10791,17 @@ local function find(w: any, name: string, ns: string?): Lump? return best end --- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() function Wad.new(kind: ("IWAD" | "PWAD")?): any local a = Archive.new("wad", encode) a.meta.source = { format = "wad", type = kind or "PWAD" } return a end --- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) function Wad.lumps(a: any): { Lump }? local w = info(a) return w and w.lumps end --- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) local w = info(a) if not w then @@ -11173,8 +10815,6 @@ function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil end --- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) --- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then @@ -11215,7 +10855,6 @@ function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? return img, nil end --- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } local function textureDefs(w: any): { [string]: any } if w.textures then return w.textures @@ -11267,7 +10906,6 @@ local function textureDefs(w: any): { [string]: any } return defs end --- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then @@ -11291,7 +10929,6 @@ function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types. return img, nil end --- maps(a) -> { map names } in file order function Wad.maps(a: any): { string } local w = info(a) local out: { string } = {} @@ -11307,7 +10944,6 @@ function Wad.maps(a: any): { string } return out end --- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) local w = info(a) if not w then @@ -11333,9 +10969,6 @@ function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) return m, nil end --- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and --- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes --- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) local m, err = Wad.mapData(a, name) if not m then @@ -11383,14 +11016,9 @@ return Wad end __FILES["archive/wad/Map"] = function() --- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, --- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a --- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with --- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the --- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one --- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z --- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not --- supported. +-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with +-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and +-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP). local Types = __include("Types") local Polygon = __include("codecs/model/Polygon") @@ -11413,7 +11041,6 @@ type MapData = { vertices: { number }, -- x1, y1, x2, y2, ... sectors: { Sector }, } --- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows type Textures = { size: (kind: string, name: string) -> (number?, number?), image: ((kind: string, name: string) -> Types.Image?)?, @@ -11430,7 +11057,6 @@ local function side(v: number): number? return if v == 0xFFFF then nil else v + 1 end --- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do if not lumps[k] then @@ -11528,9 +11154,8 @@ function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string end -- ------------------------------------------------------------------------------------------------ sector outlines --- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; --- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; --- chains that do not close are dropped +-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest +-- right turn at forks; unclosed chains dropped local function loops(m: MapData): { [number]: { { number } } } local edges: { [number]: { { number } } } = {} local nv = #m.vertices // 2 @@ -11631,7 +11256,6 @@ type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 --- scene(m, tex, name) -> Scene function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene local batches: { [string]: Batch } = {} local order: { string } = {} @@ -11653,7 +11277,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end local V = m.vertices local nv = #V // 2 - -- floors and ceilings local secLoops = loops(m) for sec, ls in secLoops do local s = m.sectors[sec] @@ -11685,7 +11308,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end end end - -- walls local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) if tname == "-" or tname == "" or zt <= zb then return @@ -11747,7 +11369,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end end end - -- the scene local scene = Scene.new() scene.meta.up = "z" local mesh: Types.Mesh = { name = name, primitives = {} } @@ -11794,7 +11415,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene table.insert(scene.meshes, mesh) scene.nodes[1] = { name = name, children = {}, mesh = 1 } scene.roots[1] = 1 - -- things, on the floor of the sector under them for i, th in m.things do local z = th.z or 0 for sec, ls in secLoops do @@ -11827,17 +11447,13 @@ end __FILES["archive/wad/Picture"] = @native function() --- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column --- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of --- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) --- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). --- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's --- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +-- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: +-- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c; +-- no code taken. Transparent pixels are 0. local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 local Picture = {} --- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) @native function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) if n < 8 then return nil, 0, 0, 0 @@ -11855,7 +11471,6 @@ local Picture = {} return w, h, readi16(b, at + 4), readi16(b, at + 6) end --- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) @native function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) local stop = at + n for x = 0, w - 1 do @@ -11890,7 +11505,6 @@ end return true, nil end --- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) @native function Picture.flatSize(n: number): (number?, number) if n == 4096 then return 64, 64 @@ -11911,15 +11525,12 @@ end return nil, 0 end --- flat(b, at, w, h, pal, out): raw indexes, row by row @native function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end --- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), --- clipped (composite wall textures from patches) @native function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do @@ -11937,12 +11548,9 @@ return Picture end __FILES["archive/xz"] = function() --- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one --- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block --- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters +-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). +-- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ -- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. --- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true: --- the api unwraps an inner archive (a .tar.xz loads as the tar). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -11962,8 +11570,8 @@ local Xz = { } type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -12040,13 +11648,9 @@ return Xz end __FILES["archive/yenc"] = function() --- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive: --- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart --- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified --- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a --- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one --- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space --- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first). +-- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text +-- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a +-- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12064,10 +11668,10 @@ local Yenc = { caps = { decode = true, encode = true, multipart = true }, } -type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 type EncodeOptions = { - line: number?, -- characters per line (default 128) - name: string?, -- the name of a buffer / string value (default "data") + line: number?, -- default 128 + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -12094,7 +11698,6 @@ local function fields(line: string): { [string]: string } return f end --- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out) local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number local lim = buffer.len(out) local esc = false @@ -12119,7 +11722,6 @@ local function decodeData(src: buffer, i: number, j: number, out: buffer, o: num return o end --- count the decoded bytes of the data lines [i, j) local function countData(src: buffer, i: number, j: number): number local n, esc = 0, false for p = i, j - 1 do @@ -12308,7 +11910,6 @@ function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line }) function Yenc.new(): any local a = Archive.new("yenc", encoder) a.meta.source = { format = "yenc" } @@ -12319,11 +11920,9 @@ return Yenc end __FILES["archive/z"] = function() --- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one --- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a --- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed, --- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is --- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files. +-- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one +-- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z). +-- Not supported: pack (.z, 1F 1E) and compact (1F FF) files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12342,8 +11941,8 @@ local Z = { } type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } type EncodeOptions = { maxBits: number?, -- 9..16 (compress -b), default 16 @@ -12359,7 +11958,6 @@ function Z.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the entry name: the file name without .Z; .taz / .tz name a tar local function entryName(opts: DecodeOptions): string local name = Archive.streamName(opts, { "z" }) local stem, ext = string.match(name, "^(.+)%.(%w+)$") @@ -12404,7 +12002,6 @@ function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a .Z Archive holding one entry function Z.new(data: (buffer | string)?, name: string?): any local a = Archive.new("z", encode) a.meta.stream = true @@ -12419,20 +12016,9 @@ return Z end __FILES["archive/zip"] = function() --- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. --- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new --- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, --- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated --- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. --- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, --- LZMA, zstd entries are listed but not readable), multi-disk archives. --- --- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) --- for _, e in a:list() do print(e.name, e.size, e.method) end --- local data = a:read("dir/file.txt") --- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } --- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) --- local b = Zip.create() -- an empty archive +-- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer. +-- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names; +-- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12452,7 +12038,7 @@ local Zip = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - verify: boolean?, -- check every entry's CRC-32 on read (default true) + verify: boolean?, -- default true } type AddOptions = Container.AddOptions type WriteOptions = Container.FinishOptions @@ -12498,7 +12084,6 @@ function Zip.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Archive | nil, Err function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) local zip, err = Container.open(r) if not zip then @@ -12507,14 +12092,11 @@ function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err return new(zip, not (opts and opts.verify == false)), nil end --- create() -> an empty Archive function Zip.create(): Types.Archive return new(nil, true) end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written --- here), or a plain table { [name] = buffer | string }. function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") @@ -12552,9 +12134,7 @@ function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- the Archive methods (Types.Archive) --- list() -> { ArchiveEntry } in archive order (+ crc32, comment) function Archive.list(self: any): { Types.ArchiveEntry } local out = {} for _, name in self._order do @@ -12585,7 +12165,6 @@ function Archive.list(self: any): { Types.ArchiveEntry } return out end --- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup function Archive.read(self: any, name: string): (buffer?, Err.Err?) if type(name) ~= "string" then return nil, Err.new(Err.ARG, "read: name must be a string") @@ -12608,7 +12187,6 @@ function Archive.read(self: any, name: string): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "no entry " .. name) end --- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") function Archive.add(self: any, name: string, data: any, opts: AddOptions?) local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) if self._items[name] == nil then @@ -12617,7 +12195,6 @@ function Archive.add(self: any, name: string, data: any, opts: AddOptions?) self._items[name] = { data = b, opts = opts or {} } end --- remove(name) -> true when there was such an entry function Archive.remove(self: any, name: string): boolean if self._items[name] == nil then return false @@ -12630,7 +12207,6 @@ function Archive.remove(self: any, name: string): boolean return true end --- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) local w = Container.writer() for _, name in self._order do @@ -12659,12 +12235,9 @@ return Zip end __FILES["archive/zoo"] = function() --- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of --- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers), --- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit --- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read --- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not --- supported: writing, file generations beyond keeping the newest (older versions of a name get ";"). +-- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW +-- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the +-- newest (older versions of a name get ";"). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12685,7 +12258,7 @@ local Zoo = { } type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } @@ -12858,9 +12431,8 @@ return Zoo end __FILES["archive/zst"] = function() --- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded --- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else --- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. +-- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd). +-- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data". -- Not supported: dictionaries, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -12880,9 +12452,9 @@ local Zst = { } type DecodeOptions = { - maxBytes: number?, -- refuse a decompressed size over this (default 2^30) - verify: boolean?, -- check the content checksum (default true) - name: string?, -- the file name, for the entry name (the api passes it) + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -12923,10 +12495,9 @@ return Zst end __FILES["audio/aac"] = function() --- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams --- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected --- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by --- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8 +-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its +-- AAC-LC core. Not supported: writing, ADIF, LATM. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12948,13 +12519,12 @@ local AacFormat = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) + maxFrames: number?, -- default 2^22 } -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 --- the size of an ID3v2 tag at p (0 if none) local function id3Size(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 @@ -12967,7 +12537,6 @@ local function id3Size(b: buffer, p: number, limit: number): number return 10 + s + footer end --- a few ID3v2.3 / 2.4 text frames -> tags local ID3_TAGS: { [string]: string } = { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", @@ -13018,7 +12587,6 @@ function AacFormat.sniff(r: Bytes.Reader): number if not h then return 0 end - -- a second header right after the first makes it certain local h2 = Aac.adts(b, p + h.frameSize, limit) if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then return 0.9 @@ -13027,7 +12595,6 @@ function AacFormat.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the frame index: offsets of every ADTS frame (resyncing over garbage) local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) @@ -13036,14 +12603,14 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number while p + 7 <= limit do local h = Aac.adts(b, p, limit) if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then - h = nil -- a false sync inside the data + h = nil end if not h then p += 1 continue end if p + h.frameSize > limit then - break -- a truncated last frame + break end if not first then first = h @@ -13102,7 +12669,7 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, tags = tags, codec = "aac", } - -- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking + -- 1024 samples per ADTS frame; one frame of pre-roll for the overlap return Stream.packets(out, { count = nframes, start = function(i: number): number @@ -13134,12 +12701,9 @@ return AacFormat end __FILES["audio/ac3"] = function() --- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through --- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) --- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block --- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and --- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). --- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no +-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default. +-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13161,13 +12725,13 @@ local Ac3Format = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFrames: number?, -- refuse streams with more syncframes (default 2^22) - drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full - crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) + maxFrames: number?, -- default 2^22 + drc: number?, -- 0 = off (default), 1 = full + crc: boolean?, -- default true; a bad frame ends the stream with Err.CHECKSUM } -- ------------------------------------------------------------------------------------------------ sniff --- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) +-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format function Ac3Format.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit local h = Ac3.header(b, p, limit) @@ -13182,7 +12746,7 @@ function Ac3Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +-- a header counts when the next one follows it, or the data ends local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base @@ -13196,7 +12760,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number if h and not first and p + h.frameSize + 8 <= limit then local h2 = Ac3.header(b, p + h.frameSize, limit) if not h2 then - h = nil -- a false sync word + h = nil end end if not h then @@ -13212,7 +12776,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number end end if p + h.frameSize > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, h.frameSize) @@ -13283,22 +12847,10 @@ return Ac3Format end __FILES["audio/adpcm"] = function() --- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in --- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by --- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such --- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs --- here are the layouts those containers use: --- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first --- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order --- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) --- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) --- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime --- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) --- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients --- live in a header: see audio/brstm and audio/adx). --- --- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) --- local raw = Adpcm.encode(a, { codec = "ima" }) +-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts. +-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt": +-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms. +-- Not supported: raw DSP / ADX (their coefficients live in a header). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13324,10 +12876,10 @@ type Options = { codec: Codec?, -- default "ima" sampleRate: number?, -- default 22050 (decode) channels: number?, -- default 1 (decode) - blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding) - lowFirst: boolean?, -- ima: the low nibble first - interleave: number?, -- psx: bytes per channel before the next channel (default 16) - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding + lowFirst: boolean?, + interleave: number?, -- psx: bytes per channel (default 16) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -13335,7 +12887,7 @@ local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = tru -- ------------------------------------------------------------------------------------------------ sniff function Raw.sniff(_r: Bytes.Reader): number - return 0 -- no header: found by extension or opts.format only + return 0 end -- ------------------------------------------------------------------------------------------------ decode @@ -13440,17 +12992,9 @@ return Raw end __FILES["audio/adx"] = function() --- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in --- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), --- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder --- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), --- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, --- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and --- exponential (4) encoding types, AHX. --- --- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) --- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) +-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop +-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13473,11 +13017,11 @@ local Adx = { -- ------------------------------------------------------------------------------------------------ types type Loop = { start: number, stop: number } type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } type EncodeOptions = { - loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none - cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders) + loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop + cutoff: number?, -- Hz, default 500 (as CRI's encoders) } -- ------------------------------------------------------------------------------------------------ constants @@ -13679,13 +13223,9 @@ return Adx end __FILES["audio/aiff"] = function() --- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. --- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw --- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated --- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / --- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; --- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, --- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. +-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos / +-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit, +-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13706,13 +13246,12 @@ local Aiff = { } type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" - littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only - -- take 16-bit sowt, so other formats return Err.ARG) - aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) + littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false + aifc: boolean?, -- default: only when the sample format needs it } -- ------------------------------------------------------------------------------------------------ constants @@ -13720,7 +13259,6 @@ local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANN local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } local AIFC_VERSION = 0xA2805140 --- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) local function ext80(b: buffer, o: number): number local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) local hi = bit32.byteswap(buffer.readu32(b, o + 2)) @@ -13736,7 +13274,6 @@ local function ext80(b: buffer, o: number): number return if se >= 0x8000 then -v else v end --- the 10 bytes of x (> 0) as an 80-bit extended float local function writeExt80(w: Bytes.Writer, x: number) if x <= 0 or x ~= x then w:fill(0, 10) @@ -13749,7 +13286,7 @@ local function writeExt80(w: Bytes.Writer, x: number) while x < 2 ^ e do e -= 1 end - local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local m = x * 2 ^ (63 - e) local hi = math.floor(m / 4294967296) local lo = m - hi * 4294967296 w:u16be(e + 16383) @@ -13757,7 +13294,6 @@ local function writeExt80(w: Bytes.Writer, x: number) w:u32be(math.floor(lo)) end --- the sample format of a COMM chunk: Pcm format name | nil, message local function sampleFormat(comp: string, bits: number): (string?, string?) if comp == "NONE" or comp == "twos" or comp == "" then if bits >= 1 and bits <= 8 then @@ -13798,7 +13334,7 @@ local function sampleFormat(comp: string, bits: number): (string?, string?) elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil elseif comp == "ima4" then - return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks + return "ima4", nil end return nil, "compression " .. string.format("%q", comp) end @@ -13822,12 +13358,11 @@ type Info = { compression: string, aifc: boolean, dataOffset: number, -- absolute in r.buf - dataSize: number, -- bytes of sample data present + dataSize: number, truncated: boolean, tags: Types.Tags, } --- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) local function parse(r: Bytes.Reader): (Info?, Err.Err?) local b = r.buf local base, limit = r.base, r.limit @@ -13845,7 +13380,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) local ssnd: number? = nil local ssndLen = 0 local tags: Types.Tags = {} - -- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body) + -- a FORM size that undercounts still reads the last chunk's body for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start if p + 8 > formEnd then @@ -13930,7 +13465,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) return fi, nil end --- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) return parse(r) end @@ -13980,14 +13514,13 @@ function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local aifc = o.aifc or comp ~= "NONE" local w = Bytes.writer(65536) w:string("FORM") - w:u32be(0) -- patched + w:u32be(0) w:string(if aifc then "AIFC" else "AIFF") if aifc then w:string("FVER") w:u32be(4) w:u32be(AIFC_VERSION) end - -- text chunks from the tags for _, pair in TEXT_ORDER do local id, key = pair[1], pair[2] local s = src.tags[key] @@ -14081,15 +13614,9 @@ return Aiff end __FILES["audio/ape"] = function() --- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), --- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end --- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). --- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 --- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. --- --- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 --- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them --- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause, +-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32 +-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14112,7 +13639,7 @@ local Ape = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -14141,7 +13668,6 @@ function Ape.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Ape.open(r, opts) if not dec then @@ -14156,7 +13682,6 @@ function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) @@ -14217,11 +13742,9 @@ return Ape end __FILES["audio/au"] = function() --- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. --- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), --- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); --- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). --- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7 +-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them. +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14240,7 +13763,7 @@ local Au = { } type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" @@ -14308,7 +13831,7 @@ function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local w = Bytes.writer(65536) w:string(".snd") w:u32be(24 + alen) - w:u32be(0xFFFFFFFF) -- patched + w:u32be(0xFFFFFFFF) w:u32be(spec[1]) w:u32be(src.sampleRate) w:u32be(src.channels) @@ -14380,15 +13903,9 @@ return Au end __FILES["audio/brstm"] = function() --- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and --- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts --- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP --- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 --- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } --- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions --- (the whole stream plays), the track table (channels are not grouped). --- --- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) +-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255 +-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14409,7 +13926,7 @@ local Brstm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -14425,7 +13942,6 @@ function Brstm.sniff(r: Bytes.Reader): number return if bom == "\254\255" or bom == "\255\254" then 1 else 0 end --- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect function Brstm.variant(r: Bytes.Reader): string? local m = r:peek(4) return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil @@ -14446,8 +13962,6 @@ function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err end -- ------------------------------------------------------------------------------------------------ open --- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file --- start); a read out of range records the error in .err and returns 0 local function view(r: Bytes.Reader, be: boolean) local v = { err = nil :: string? } local size = r.limit - r.base @@ -14490,7 +14004,7 @@ type Layout = { frames: number, blockSize: number, lastPadded: number, - data: number, -- the first block (absolute in the file) + data: number, -- absolute adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) hist: number?, -- the per-block history table: (yn1, yn2) per channel per block histEntries: number, @@ -14680,12 +14194,9 @@ return Brstm end __FILES["audio/caf"] = function() --- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear --- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, --- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown --- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / --- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: --- other compressed formats (UNSUPPORTED). +-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either +-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM +-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14710,7 +14221,7 @@ local Caf = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPackets: number?, -- packet table limit (default 2^24) + maxPackets: number?, -- default 2^24 } type EncodeOptions = { codec: ("pcm" | "alac")?, -- default "alac" @@ -14729,7 +14240,6 @@ for k, v in INFO_TAGS do TAG_INFO[v] = k end --- mu-law / A-law -> linear 16-bit local ULAW, ALAW = table.create(256, 0), table.create(256, 0) for i = 0, 255 do local u = 255 - i @@ -14757,7 +14267,7 @@ end type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } type Parsed = { desc: Desc, - dataStart: number, -- absolute offset of the audio data + dataStart: number, -- absolute dataEnd: number, cookie: buffer?, packets: { number }?, -- sizes (pakt) @@ -14917,7 +14427,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) return p, nil end --- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err type Source = { channels: number, rate: number, @@ -15014,7 +14523,6 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) } return src, nil end - -- packetised codecs local sizes = p.packets if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then @@ -15186,7 +14694,6 @@ local function chunk(w: Bytes.Writer, typ: string, size: number) w:i64be(size) end --- encode(audio | decoder, opts?) -> buffer | nil, Err function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -15204,7 +14711,6 @@ function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if ch < 1 or ch > 64 or sr <= 0 then return nil, Err.new(Err.ARG, "bad sample rate / channels") end - -- the source frames local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if not isAudio and type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") @@ -15350,21 +14856,9 @@ return Caf end __FILES["audio/flac"] = function() --- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, --- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. --- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals --- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame --- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in --- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels --- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 --- verification on decode, chained Ogg streams, Ogg FLAC output. --- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) --- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end --- local i32, n = dec:readInt(4096) -- bit-exact integer samples --- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every +-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata +-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -15388,12 +14882,12 @@ local Flac = { -- ------------------------------------------------------------------------------------------------ types type Decoder = Stream.Decoder type OpenOptions = { - crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) - maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) + crc16: boolean?, -- default true; a bad frame is skipped by resyncing + maxFrames: number?, -- default 2^28 } type EncodeOptions = { level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) - bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + bits: number?, -- 4..24; default the source's bit depth if 4..24, else 16 blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) padding: number?, -- bytes of PADDING after the metadata (default 0) @@ -15430,7 +14924,6 @@ function Flac.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Flac.open(r, opts) if not dec then @@ -15445,7 +14938,6 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -15490,7 +14982,6 @@ function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) @@ -15515,9 +15006,7 @@ __FILES["audio/flac/Meta"] = @native function() --- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is --- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d. local VorbisComment = __include("codecs/audio/VorbisComment") local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -15565,7 +15054,7 @@ type Info = { seekTable: { SeekPoint }, vendor: string, tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " - comments: { { key: string, value: string } }, -- every comment in order + comments: { { key: string, value: string } }, pictures: { Picture }, firstFrame: number, -- byte offset just after the last metadata block } @@ -15664,7 +15153,6 @@ end return pic end --- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) @native function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" @@ -15709,7 +15197,7 @@ end end end elseif typ == 4 then - vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + vorbisComment(b, p, e, info) elseif typ == 6 then local pic = picture(b, p, e) if pic then @@ -15740,11 +15228,7 @@ __FILES["audio/flac/Stream"] = @native function() --- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through --- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, --- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed --- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an --- injected module). Nothing throws: open returns nil, message, code. +-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author). local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") local Frame = __include("codecs/audio/Flac/Frame") @@ -15780,12 +15264,10 @@ type Decoder = { local Dec = {} Dec.__index = Dec --- the sample number of a frame @native local function sampleOf(self: any, h: Header): number return if h.variable then h.number else h.number * self._nominal end --- a header that also matches the stream (guards the sync search against false syncs) @native local function plausible(self: any, h: Header): boolean if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then return false @@ -15819,7 +15301,6 @@ end end end --- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. @native local function decodeAt(self: any, pos: number): boolean local b, len = self._b, self._len while true do @@ -15853,7 +15334,7 @@ end local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then - want = 0 -- negative or NaN + want = 0 end want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 @@ -15898,29 +15379,23 @@ end return out, got end --- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is --- reused when big enough. @native function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, false, out) end --- The same as interleaved i32 integer samples (bit-exact, right-aligned) @native function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, true, out) end --- seconds, sample frame of the next frame read() returns @native function Dec.position(self: any): (number, number) local s = self._fs + self._cur return s / self.sampleRate, s end --- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets --- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. @native function Dec.seekSample(self: any, t: number): boolean t = math.floor(tonumber(t) or 0) if not (t >= 0) then - t = 0 -- negative or NaN + t = 0 end if self.frames > 0 and t >= self.frames then self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 @@ -15967,7 +15442,7 @@ end self._cur = t - self._fs return true elseif self._fs > t then - return false -- a hole in the stream: we are at the next frame + return false end pos = self._pos else @@ -15983,7 +15458,6 @@ end return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end --- Find the total length from the last frame (when STREAMINFO does not give it) @native local function scanLength(self: any): number local len = self._len local step = math.max(65536, 2 * self._si.maxFrameSize) @@ -16023,7 +15497,6 @@ end return p end --- opts.crc16 = false skips the per-frame CRC-16 check @native function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) local b, len, container if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then @@ -16123,11 +15596,9 @@ return Stream end __FILES["audio/m4a"] = function() --- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading --- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless --- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); --- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs --- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. +-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays +-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 +-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -16153,13 +15624,13 @@ local M4a = { type DecodeOptions = { track: number?, -- the track id to play (default: the first AAC / ALAC track) gapless: boolean?, -- apply the edit list (default true) - maxSamples: number?, -- sample table limit (default 2^25) + maxSamples: number?, -- default 2^25 } type EncodeOptions = { bitDepth: number?, -- 16 (default), 20 or 24 frameLength: number?, -- samples per packet, default 4096 tags: Types.Tags?, -- default: the audio's tags - pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) + pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures } -- ------------------------------------------------------------------------------------------------ constants @@ -16181,7 +15652,6 @@ function M4a.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats type PacketDecoder = { channels: number, sampleRate: number, @@ -16245,7 +15715,6 @@ local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") end --- open(r, opts?) -> Types.Decoder | nil, Err function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) @@ -16279,7 +15748,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E end local p = pd :: PacketDecoder local channels, sr = p.channels, p.sampleRate - -- media ticks -> sample frames local tickScale = sr / t.timescale local gapless = o.gapless ~= false local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 @@ -16343,7 +15811,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E }) end --- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = M4a.open(r, opts) if not dec then @@ -16358,7 +15825,6 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -16378,7 +15844,6 @@ function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local ints = table.create(fl * ch, 0) local floor = math.floor local readf32 = buffer.readf32 - -- frames from an Audio buffer or a streaming Decoder local src: buffer, srcFrames = nil :: any, 0 local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if isAudio then @@ -16465,20 +15930,9 @@ return M4a end __FILES["audio/mp3"] = function() --- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf --- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 --- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / --- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync --- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III --- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from --- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel --- extension, CRC checks, VBR / Xing output. --- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, --- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) --- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) +-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of +-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless, +-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -16505,7 +15959,7 @@ local Mp3 = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) + maxFrames: number?, -- default 2^31 } type Decoder = Stream.Decoder type EncodeOptions = { @@ -16524,7 +15978,6 @@ type EncodeOptions = { local MAX_FRAMES = 2 ^ 31 -- ------------------------------------------------------------------------------------------------ sniff --- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on function Mp3.sniff(r: Bytes.Reader): number local b, p, lim = r.buf, r.pos, r.limit local id3 = false @@ -16553,7 +16006,6 @@ function Mp3.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts) -> Types.Audio (the whole stream, through open) function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Mp3.open(r, opts) if not dec then @@ -16579,7 +16031,6 @@ local ID3_FRAMES = { { "composer", "TCOM" }, } --- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write local function id3Tag(tags: { [string]: any }): buffer? local w = Bytes.writer(256) local seen: { [string]: boolean } = {} @@ -16628,7 +16079,6 @@ local function id3Tag(tags: { [string]: any }): buffer? return out:finish() end --- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -16640,8 +16090,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "layer must be 2 or 3") end local Enc = if layer == 3 then Encode3 else Encode2 - -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else - -- the highest); other input rates go through codecs/audio/Resample local rate = o.sampleRate or src.sampleRate if o.sampleRate and not Enc.RATES[o.sampleRate] then return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) @@ -16675,7 +16123,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if layer == 2 and mode == "joint" then mode = "stereo" end - -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) if type(bitrate) == "number" and bitrate >= 1000 then bitrate /= 1000 @@ -16700,7 +16147,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } local out: { [string]: string } = {} for k, v in t do @@ -16711,7 +16157,6 @@ local function stringTags(t: any): { [string]: string } return out end --- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) local b = r.buf if r.base ~= 0 or r.limit ~= buffer.len(b) then @@ -16739,7 +16184,7 @@ function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) +Mp3.Tags = Tags return Mp3 end @@ -16747,10 +16192,7 @@ __FILES["audio/mp3/Index"] = @native function() --- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame --- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so --- it knows in advance which frames give output and where each one's samples land. That makes the total length --- exact and seeking sample-accurate. Never throws. +-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir. local Header = __include("codecs/audio/Mpa/Header") local Core = __include("codecs/audio/Mpa/Core") @@ -16775,7 +16217,6 @@ type Index = { main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) outTotal: number, -- samples (per channel) of a continuous decode, delay not cut bytes: number, -- audio bytes in indexed frames - -- format of the first frame sampleRate: number, channels: number, -- the most channels of any frame layer: number, @@ -16835,7 +16276,6 @@ end pos += i end if fs < 4 or fs > Core.MAX_FRAME then - -- cannot happen with a well-formed header, but never index an impossible frame prev = -1 pos += max(fs, 1) continue @@ -16942,8 +16382,7 @@ end __FILES["audio/mp3/Stream"] = function() --- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact --- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws. +-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author). local Core = __include("codecs/audio/Mpa/Core") local Index = __include("audio/mp3/Index") @@ -16986,7 +16425,6 @@ type Decoder = typeof(setmetatable( Decoder )) --- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count @@ -17034,7 +16472,6 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): end --- decodes frames until one has samples inside [minAbs, endAbs); false at the end local function fill(self: Decoder): boolean local idx = self._idx local n = idx.n @@ -17069,9 +16506,6 @@ local function fill(self: Decoder): boolean return false end --- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. --- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a --- smaller out is ignored. function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) local ch = self.channels local want = tonumber(maxFrames) or 4096 @@ -17080,7 +16514,7 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, end want = floor(max(0, min(want, self.frames - self._pos))) if out and buffer.len(out) < want * ch * 4 then - out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + out = nil end local dst = out or buffer.create(want * ch * 4) local got = 0 @@ -17105,8 +16539,6 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, return dst, got end --- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier --- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. function Decoder.seek(self: Decoder, seconds: number) local hz = self.sampleRate local target = floor((tonumber(seconds) or 0) * hz + 0.5) @@ -17114,7 +16546,6 @@ function Decoder.seek(self: Decoder, seconds: number) self:seekFrame(target) end --- Seeks to a sample frame (0 .. frames). function Decoder.seekFrame(self: Decoder, target: number) target = tonumber(target) or 0 if target ~= target then @@ -17132,7 +16563,6 @@ function Decoder.seekFrame(self: Decoder, target: number) self._cur = n return end - -- last frame starting at or before abs local lo, hi = 0, n - 1 while lo < hi do local mid = (lo + hi + 1) // 2 @@ -17160,12 +16590,10 @@ function Decoder.seekFrame(self: Decoder, target: number) self._cur = s end --- Current position: (seconds, sample frame) function Decoder.position(self: Decoder): (number, number) return self._pos / self.sampleRate, self._pos end --- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) function Decoder.readAll(self: Decoder): (buffer, number) return self:read(max(0, self.frames - self._pos)) end @@ -17177,9 +16605,7 @@ end __FILES["audio/mp3/Tags"] = function() --- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / --- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way --- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3. local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local ru8 = buffer.readu8 @@ -17274,7 +16700,6 @@ local function decodeText(b: buffer, i: number, j: number, enc: number): string return table.concat(out) end --- trim trailing NULs / spaces, join multi-value NUL separators with " / " local function clean(s: string): string s = string.gsub(s, "[%z%s]+$", "") s = string.gsub(s, "%z+", " / ") @@ -17343,7 +16768,6 @@ local function setField(tags: any, id: string, text: string) end end --- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags local function parseV2(b: buffer, o: number, size: number, tags: any) local ver = ru8(b, o + 3) local flags = ru8(b, o + 5) @@ -17435,9 +16859,6 @@ local function v1String(b: buffer, o: number, n: number): string return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) end --- Parses tags and returns (tags, audio start, audio end) for the buffer b. --- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?, --- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } function Tags.parse(b: buffer): (any, number, number) local len = buffer.len(b) local tags: any = { raw = {} } @@ -17495,12 +16916,9 @@ return Tags end __FILES["audio/mpc"] = function() --- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec --- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / --- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking --- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags --- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: --- writing, SV4 - SV6 (UNSUPPORTED), chapters. +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono / +-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags, +-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -17523,11 +16941,10 @@ local Mpc = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31) + maxFrames: number?, -- default 2^31 } -- ------------------------------------------------------------------------------------------------ constants --- the size of an ID3v2 tag at p (0 if none) local function id3v2(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 @@ -17593,24 +17010,9 @@ return Mpc end __FILES["audio/opus"] = function() --- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a --- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK --- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). --- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, --- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms --- pre-roll), damaged files (concealment). Output is always 48 kHz f32. --- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant --- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. --- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics --- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). --- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an --- optional output buffer; decode() fully decodes to an Audio. --- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... --- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio --- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets --- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) +-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD: +-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC; +-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -17669,7 +17071,7 @@ type Head = { mapping: { number }, } --- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. +-- OpusHead (RFC 7845 section 5.1) local function parseHead(b: buffer, off: number, size: number): (Head?, string?) if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then return nil, "not an OpusHead packet" @@ -17721,8 +17123,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?) return head, nil end --- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined --- with "; "), the raw fields +-- OpusTags (RFC 7845 section 5.2) local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field }) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then return "", {}, {} @@ -17767,7 +17168,6 @@ Opus.parseTags = parseTags Opus.SAMPLE_RATE = SAMPLE_RATE -- ------------------------------------------------------------------------------------------------ sniff --- 1 when the file starts with an Ogg page whose first packet is an OpusHead function Opus.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -17780,7 +17180,6 @@ function Opus.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Opus.open(r, opts) if not dec then @@ -17790,7 +17189,6 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) return Encode.encode(value, opts) end @@ -17799,7 +17197,6 @@ end local Stream = {} Stream.__index = Stream --- Decodes the next packet into the pending buffer. Returns false at the end of the stream. local function decodeNext(self: any): boolean local p = self.demux:nextPacket(self.serial) if p == nil then @@ -17833,8 +17230,6 @@ local function decodeNext(self: any): boolean return true end --- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if --- given and big enough) is filled instead of a new buffer. function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) local ch = self.channels local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 @@ -17849,7 +17244,6 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb break end end - -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) local s = self.pendStart + self.pendPos if s < self.next then self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) @@ -17874,17 +17268,15 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb buffer.copy(trimmed, 0, out, 0, got * ch * 4) out = trimmed end - self.endSample = self.next -- the stream ended early (truncated file) + self.endSample = self.next end return out, got end --- current playback position in seconds function Stream.position(self: any): number return (self.next - self.preSkip) / SAMPLE_RATE end --- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll function Stream.seek(self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) @@ -17909,7 +17301,6 @@ function Stream.seek(self: any, seconds: number) self.next = target end --- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) if not demux then @@ -17997,11 +17388,7 @@ return Opus end __FILES["audio/opus/Encode"] = function() --- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/audio/Opus/CeltEncoder: CELT-only packets (TOC config 31: --- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + --- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at --- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in --- rosetta. +-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") @@ -18022,7 +17409,6 @@ type Options = { local floor = math.floor --- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o: Options = opts or {} local src, serr = Pcm.source(value) @@ -18039,12 +17425,11 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) end local bitrate = o.bitrate or 64000 * ch if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then - bitrate *= 1000 -- kbit/s + bitrate *= 1000 end if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end - -- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats if rate ~= 48000 then local rs, rerr = Resample.source(src, 48000) if not rs then @@ -18066,7 +17451,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY local packets = (n48 + preSkip + FRAME - 1) // FRAME - -- zero padding to whole frames for i = n48 * ch + 1, packets * FRAME * ch do pcm[i] = 0 end @@ -18098,7 +17482,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) - -- audio local toc = 31 * 8 + (if ch == 2 then 4 else 0) for p = 0, packets - 1 do local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) @@ -18116,15 +17499,9 @@ return Encode end __FILES["audio/qoa"] = function() --- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in --- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order --- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its --- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): --- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel --- count or rate change mid-stream (Err.UNSUPPORTED). --- --- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder --- local file = Qoa.encode(audio) +-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and +-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode, +-- 1-8 channels. Not supported: channel count or rate changes mid-stream. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18146,7 +17523,7 @@ local Qoa = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -18239,7 +17616,6 @@ function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) return nil, h.err end local buf = r.buf - -- the frame index: offsets, first frames local offs, starts = {}, {} local p, total = r.base + 8, 0 local ch, rate = 0, 0 @@ -18303,13 +17679,9 @@ return Qoa end __FILES["audio/tta"] = function() --- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the --- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). --- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. --- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. --- --- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt --- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24 +-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected +-- files, TTA2, ID3v2 contents, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18332,11 +17704,10 @@ local Tta = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff --- the size of an ID3v2 tag at the reader's start (0 when none) local function id3Size(r: Bytes.Reader): number if r:peek(3) ~= "ID3" then return 0 @@ -18358,7 +17729,6 @@ function Tta.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Tta.open(r, opts) if not dec then @@ -18373,7 +17743,6 @@ function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) @@ -18428,18 +17797,9 @@ return Tta end __FILES["audio/vag"] = function() --- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same --- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow --- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono --- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / --- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. --- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame --- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game --- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). --- --- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) --- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) +-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp / +-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18462,7 +17822,7 @@ local Vag = { -- ------------------------------------------------------------------------------------------------ types type Loop = { start: number, stop: number } type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } type EncodeOptions = { loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the @@ -18573,8 +17933,7 @@ function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end --- flag 3), or nil +-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3 local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? local ls, le = -1, -1 for k = 0, frames - 1 do @@ -18661,13 +18020,9 @@ return Vag end __FILES["audio/voc"] = function() --- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. --- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), --- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit --- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played --- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version --- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM --- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). +-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9 +-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9 +-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18686,7 +18041,7 @@ local Voc = { } type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" @@ -18735,7 +18090,6 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E local truncated = false local tags: Types.Tags = {} local p = base + hsize - -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? if channels == 0 then channels, rate = ch, sr @@ -18839,7 +18193,7 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E local n = s.frames * channels if s.fmt then Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) - end -- silence: the buffer is already zero + end o += n * 4 end a.tags = tags @@ -18900,7 +18254,7 @@ function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) blockAt = w:tell() blockFrames = 0 w:u8(9) - w:u24le(0) -- patched + w:u24le(0) w:u32le(src.sampleRate) w:u8(spec[3]) w:u8(src.channels) @@ -18941,17 +18295,9 @@ return Voc end __FILES["audio/vorbis"] = function() --- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau --- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct, --- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last --- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). --- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, --- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level --- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic --- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook --- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since --- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. --- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing). +-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT, +-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels, +-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18984,7 +18330,6 @@ type EncodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants --- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels) local function waveOrder(ch: number): { number } local m = Pcm.WAVE_FROM_VORBIS[ch] if m then @@ -18997,7 +18342,6 @@ local function waveOrder(ch: number): { number } return id end --- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then @@ -19040,7 +18384,6 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -19072,7 +18415,6 @@ end local Stream = {} Stream.__index = Stream --- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) local lo = math.max(g0, self.startG, self.skipTo) if hi > g0 + count then @@ -19094,7 +18436,6 @@ local function copyOut(self: any, count: number): { { number } } return t end --- decode packets until something is queued; false at the end of the stream local function decodeMore(self: any): boolean local reader, st = self.reader, self.st while not self.ended do @@ -19193,7 +18534,6 @@ function Stream.position(self: any): number return (self.next - self.startG) / self.sampleRate end --- back to the first audio packet local function restart(self: any) local r = self.reader r:rewind() @@ -19372,11 +18712,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three --- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. --- local pd = Vorbis.packetDecoder(h1, h2, h3) --- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] --- pd:reset() -- after a seek +-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) local function pk(b: buffer): any return { data = b, offset = 0, size = buffer.len(b) } @@ -19415,15 +18751,8 @@ __FILES["audio/vorbis/Encode"] = @native function() --- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification --- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the --- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a --- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- --- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer --- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then --- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian --- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact --- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048), +-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths. local Mdct = __include("codecs/audio/Mdct") local Pcm = __include("codecs/audio/Pcm") local VorbisComment = __include("codecs/audio/VorbisComment") @@ -19513,7 +18842,6 @@ type Book = { values: number, -- lookup1 values per dimension } --- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) @native local function huffmanLengths(w: { number }): { number } local n = #w local total = 0 @@ -19526,7 +18854,6 @@ type Book = { return lens end local minw = total * 2 ^ -20 - -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues local order = table.create(n, 0) for i = 1, n do order[i] = i @@ -19542,8 +18869,8 @@ type Book = { end return a < b end) - local q1, h1 = order, 1 -- leaves, ascending - local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local q1, h1 = order, 1 + local q2, h2, t2 = table.create(n, 0), 1, 0 local nextId = n @native local function pop(): number local a = if h1 <= n then q1[h1] else nil @@ -19575,7 +18902,7 @@ type Book = { return lens end --- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +-- the spec's codeword assignment (lowest free leaf, in entry order) @native local function assign(lens: { number }): { number } local codes = table.create(#lens, 0) local available = table.create(33, 0) @@ -19622,7 +18949,6 @@ end return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } end --- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) @native local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book local values = 2 * h + 1 local entries = values ^ dims @@ -19716,7 +19042,6 @@ do table.insert(xs, x) end table.sort(xs) - -- bisection order over the sorted list local queue = { { 1, #xs } } local qh = 1 while qh <= #queue do @@ -19838,7 +19163,7 @@ end end end end - return 0 -- unreachable for t in range; fall back to the prediction + return 0 end -- ------------------------------------------------------------------------------------------------ headers @@ -19973,7 +19298,6 @@ type Options = { serial: number, } --- the residue of one partition: vectors of each pass for class c @native local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) local b = CLASS_BOOKS[c][pass] if b < 0 then @@ -20053,7 +19377,6 @@ end local k = 0 local lastWanted = -1 -- the last packet index needed (known once the input ends) while true do - -- shift in the next 1024 input samples (zeros past the end) for c = 1, ch do local fr = frame[c] table.move(fr, N2 + 1, N, 1) @@ -20092,8 +19415,6 @@ end lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) end -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) - -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) - -- MDCT per channel local energy = 0 for c = 1, ch do local fr = frame[c] @@ -20235,7 +19556,6 @@ end return mux:finish(), nil end --- the codebooks (tests check the Huffman lengths are a valid prefix code) Encode.BOOKS = BOOKS return Encode @@ -20243,19 +19563,9 @@ end __FILES["audio/wav"] = function() --- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no --- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. --- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE --- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF --- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). --- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when --- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, --- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. --- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. --- --- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames --- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio --- local file = Wav.encode(audio, { sampleFormat = "s24" }) +-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit, +-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end); +-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -20279,14 +19589,14 @@ local Wav = { -- ------------------------------------------------------------------------------------------------ types type Tags = { [string]: string } type OpenOptions = { - maxBytes: number?, -- unused (the file is already in memory); kept for symmetry + maxBytes: number?, } type EncodeOptions = { sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) - tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...) + tags: Tags?, -- default: the Audio's tags rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) } @@ -20387,7 +19697,6 @@ type Decoder = typeof(setmetatable( )) local function trimTag(s: string): string - -- strip trailing NULs / spaces local e = #s while e > 0 do local c = string.byte(s, e) @@ -20409,7 +19718,6 @@ function Wav.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole file function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Wav.open(r, opts) if not dec then @@ -20434,7 +19742,6 @@ local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTY local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } local BLOCK = 65536 -- frames per data piece when streaming a Decoder --- the body of the encoder: { buffer } pieces of the file | nil, Err local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") @@ -20555,19 +19862,15 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): return w:finish({ parts = asParts }) end --- encode(audio or decoder, opts?) -> buffer | nil, Err function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return encodeParts(value, opts, false) end --- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other --- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) return encodeParts(value, opts, true) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" or type(r) == "string" then r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) @@ -20793,8 +20096,6 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples --- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) local ch = self.channels local req = math.floor(tonumber(maxFrames) or 0) @@ -20824,7 +20125,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, self._pos += want return dst, want end - -- block formats: decode a block into the cache, copy out of it local spb, ba = self._spb, self.blockAlign local cache = self._cache :: buffer local done = 0 @@ -20855,7 +20155,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, return dst, done end --- Moves to a time in seconds (clamped to the stream). function Decoder.seek(self: Decoder, seconds: number) local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) if f ~= f then @@ -20864,7 +20163,6 @@ function Decoder.seek(self: Decoder, seconds: number) self._pos = math.clamp(f, 0, self.frames) end --- Moves to a frame index (clamped). function Decoder.seekFrame(self: Decoder, frame: number) local f = math.floor(tonumber(frame) or 0) if f ~= f then @@ -20873,12 +20171,10 @@ function Decoder.seekFrame(self: Decoder, frame: number) self._pos = math.clamp(f, 0, self.frames) end --- Current position in seconds. function Decoder.position(self: Decoder): number return self._pos / self.sampleRate end --- Current position in frames. function Decoder.tell(self: Decoder): number return self._pos end @@ -20889,10 +20185,7 @@ __FILES["audio/wav/Codecs"] = @native function() --- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The --- ADPCM block decoders moved to codecs/audio/Adpcm. --- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) --- only calls them with ranges it has checked against the source length and the output size. +-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 @@ -20901,8 +20194,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b local Codecs = {} --- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, --- from src[off] to dst (f32) starting at sample index d. +-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed @native function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) local o = d * 4 if bytes == 1 then @@ -20952,7 +20244,6 @@ local Codecs = {} end end --- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. @native function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, tmp: buffer) local o = d * 4 @@ -20983,7 +20274,6 @@ end end end --- 8-bit companded (A-law / mu-law) through a 256-entry f32 table @native function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) local o = d * 4 for i = 0, count - 1 do @@ -20991,13 +20281,10 @@ end end end --- copy frames from a block cache into the output: count f32 values @native function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end --- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), --- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. @native function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) local so = s * 4 if kind == "f32" then @@ -21062,19 +20349,9 @@ return Codecs end __FILES["audio/wavpack"] = function() --- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction --- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 --- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). --- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the --- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("c") --- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking --- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file --- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. --- --- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... --- local f32, n = dec:read(4096) --- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them --- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's +-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as +-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -21098,9 +20375,9 @@ local WavPack = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) - resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths) - name: string?, -- the file name (the api passes it) - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + resolve: ((uri: string) -> buffer?)?, + name: string?, + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -21113,7 +20390,6 @@ function WavPack.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = WavPack.open(r, opts) if not dec then @@ -21130,7 +20406,6 @@ end -- ------------------------------------------------------------------------------------------------ open type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } --- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence local function index(buf: buffer, base: number, limit: number): (Index?, string?) local at = base local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } @@ -21205,7 +20480,6 @@ local function correctionFile(opts: OpenOptions?): buffer? return nil end --- open(r, opts?) -> Decoder | nil, Err function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) @@ -21230,7 +20504,6 @@ function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err local count = #idx.offsets local last = idx.starts[count] + idx.samples[count] local frames = if idx.total >= 0 then math.min(idx.total, last) else last - -- the correction file: its frames by start sample local cbuf = if info.hybrid then correctionFile(opts) else nil local cfor: { [number]: { number } } = {} if cbuf then @@ -21283,26 +20556,9 @@ return WavPack end __FILES["cad/step"] = function() --- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). --- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / --- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and --- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; --- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to --- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, --- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / --- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same --- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). --- --- B-rep bodies and tessellation come from an injected kernel, never required by rosetta: --- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, --- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } --- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } --- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / --- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / --- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, --- millimetres (meta.unit = 0.001). --- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), --- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). +-- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA +-- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the +-- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -21325,19 +20581,19 @@ local Step = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 2^30) - maxEntities: number?, -- refuse more instances (default 2^24) + maxBytes: number?, -- default 2^30 + maxEntities: number?, -- default 2^24 } type EncodeOptions = { - schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA - name: string?, -- FILE_NAME name (default: the header's, else "model") - timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00") - crlf: boolean?, -- CRLF line ends (default LF) + schema: string?, -- overrides the header's FILE_SCHEMA + name: string?, -- default: the header's, else "model" + timestamp: string?, -- default "1970-01-01T00:00:00" + crlf: boolean?, } type BrepOptions = { - brep: any?, -- the plug-in (else opts.plugins.brep) + brep: any?, plugins: { [string]: any }?, - chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead + chord: number?, -- millimetres (default 0.05) tess: { [string]: any }?, } @@ -21352,7 +20608,6 @@ local SCHEMAS = { } Step.SCHEMAS = SCHEMAS --- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself local function schemaOf(name: string): string local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then @@ -21487,7 +20742,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) end end end - -- entities by section, in id order local ids = {} for id, e in cad.entities do if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then @@ -21541,7 +20795,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- get(cad, id | { ref = id }) -> the entity function Step.get(cad: Types.Cad, id: any): Types.StepEntity? if type(id) == "table" then id = id.ref @@ -21549,7 +20802,6 @@ function Step.get(cad: Types.Cad, id: any): Types.StepEntity? return cad.entities[id] end --- ids(cad) -> the instance ids in ascending order function Step.ids(cad: Types.Cad): { number } local out = {} for id in cad.entities do @@ -21559,7 +20811,6 @@ function Step.ids(cad: Types.Cad): { number } return out end --- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending function Step.byType(cad: Types.Cad, name: string): { number } local n = string.upper(name) local out = {} @@ -21579,7 +20830,6 @@ function Step.byType(cad: Types.Cad, name: string): { number } return out end --- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) function Step.part(e: Types.StepEntity?, name: string): { any }? if not e then return nil @@ -21597,7 +20847,6 @@ function Step.part(e: Types.StepEntity?, name: string): { any }? return nil end --- add(cad, type, args) -> id: a new instance after the highest id function Step.add(cad: Types.Cad, type: string, args: { any }): number local top = 0 for id in cad.entities do @@ -21611,7 +20860,6 @@ function Step.add(cad: Types.Cad, type: string, args: { any }): number return id end --- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) function Step.real(t: { [any]: any }, key: any): { [any]: any } local mt: any = getmetatable(t) if not mt then @@ -21622,12 +20870,10 @@ function Step.real(t: { [any]: any }, key: any): { [any]: any } return t end --- new(schema?) -> an empty Cad ("AP214" by default) function Step.new(schema: string?): Types.Cad return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } end --- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason Step.plugin = Brep.plugin local function textOf(cad: Types.Cad): (string?, Err.Err?) @@ -21638,7 +20884,6 @@ local function textOf(cad: Types.Cad): (string?, Err.Err?) return buffer.tostring(buf), nil end --- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) local plug, perr = Brep.find(opts) if not plug then @@ -21655,7 +20900,6 @@ function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) return bodies, res end --- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) if type(bodies) ~= "table" then return nil, Err.new(Err.ARG, "needs a list of bodies") @@ -21671,7 +20915,6 @@ function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err. return Step.decode(Bytes.reader(buffer.fromstring(text))) end --- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) local plug, perr = Brep.find(opts) if not plug then @@ -21695,18 +20938,9 @@ return Step end __FILES["cad/step/Brep"] = function() --- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises --- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a --- Scene. Interpreted on purpose: the plug-in's errors unwind through here. --- --- The interface (every function may throw; results are checked): --- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, --- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) --- write(bodies: { Body }, opts) -> string bodies -> STEP text --- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based --- triples }, faceOf = { [triangle] = Face (face.color?) }? } --- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = --- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall. +-- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text; +-- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is. local Err = __include("core/Err") local Types = __include("Types") @@ -21726,7 +20960,7 @@ local function rgbOf(c: any): (number?, number?, number?) if type(c) == "table" then return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] end - return (c :: any).R, (c :: any).G, (c :: any).B -- Color3 + return (c :: any).R, (c :: any).G, (c :: any).B end) if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then return r, g, b @@ -21734,7 +20968,6 @@ local function rgbOf(c: any): (number?, number?, number?) return nil, nil, nil end --- plugin(p) -> the normalised interface, or nil + the reason function Brep.plugin(p: any): (Plugin?, string?) if type(p) ~= "table" then return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" @@ -21778,7 +21011,6 @@ function Brep.plugin(p: any): (Plugin?, string?) return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" end --- find(opts) -> the plug-in from opts.brep or opts.plugins.brep function Brep.find(opts: any): (Plugin?, Err.Err?) local p = nil if type(opts) == "table" then @@ -21794,7 +21026,6 @@ function Brep.find(opts: any): (Plugin?, Err.Err?) return plug, nil end --- read(plug, text, opts) -> bodies, result | nil, Err function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) local ok, res = pcall(plug.read, text, opts) if not ok then @@ -21806,7 +21037,6 @@ function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err return res.bodies, res, nil end --- write(plug, bodies, opts) -> text | nil, Err function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) local w = plug.write if not w then @@ -21826,7 +21056,7 @@ local function xyz(p: any): (number, number, number) if type(p) == "table" then return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 end - return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3 + return (p :: any).X, (p :: any).Y, (p :: any).Z end local function linear(c: number): number @@ -21834,8 +21064,7 @@ local function linear(c: number): number return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 end --- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by --- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +-- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) local tess = plug.tessellate if not tess then @@ -21892,7 +21121,6 @@ function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Er end end local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) - -- triangles grouped by colour, in first-seen order local groups: { { mat: number, tris: { number } } } = {} local byMat: { [number]: { mat: number, tris: { number } } } = {} local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} @@ -21946,16 +21174,8 @@ end __FILES["cad/step/Parse"] = @native function() --- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass --- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), --- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every --- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, --- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. --- --- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; --- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) --- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so --- the writer prints it back as a real; integral numbers without that mark are written as integers. +-- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). +-- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`). local Parse = {} local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor @@ -21978,7 +21198,6 @@ type Ctx = { return nil end --- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) @native local function skip(ctx: Ctx, i: number): number local s, n = ctx.s, ctx.n while i <= n do @@ -22006,7 +21225,6 @@ end return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end --- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none @native local function keyword(ctx: Ctx, i: number): (string?, number) local s, n = ctx.s, ctx.n local j = i @@ -22023,7 +21241,6 @@ end return string.upper(ssub(s, i, j - 1)), j end --- UTF-8 of a code point @native local function utf8char(cp: number): string if cp < 0x80 then return schar(cp) @@ -22046,9 +21263,7 @@ Parse.utf8char = utf8char return tonumber(h, 16) end --- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, --- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) --- pass through. +-- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through @native function Parse.unescape(raw: string): string if not sfind(raw, "[\\']") then return raw @@ -22131,11 +21346,9 @@ end mt.__reals[key] = true end --- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) @native local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) - -- i is just past "(" local s = ctx.s local out = {} i = skip(ctx, i) @@ -22255,7 +21468,6 @@ value = @native function(ctx: Ctx, i: number, depth: number): (any, number, bool end Parse.value = value --- the simple record at i: NAME(params) -> type, args, next @native local function record(ctx: Ctx, i: number): (string?, { any }?, number) local word, j = keyword(ctx, i) if not word then @@ -22272,7 +21484,6 @@ Parse.value = value return word, args, k end --- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil @native local function expect(ctx: Ctx, i: number, ch: number, what: string): number? i = skip(ctx, i) if sbyte(ctx.s, i) ~= ch then @@ -22299,7 +21510,6 @@ type Result = { terminated: boolean, } --- parse(s, opts) -> Result | nil, message, offset (1-based position in s) @native function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } local res: Result = { @@ -22521,17 +21731,14 @@ end __FILES["cad/step/Write"] = @native function() --- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings --- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid --- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: --- failures return nil, message. +-- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). local Write = {} local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge local MAX_DEPTH = 100 --- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +-- Part 21 real: a '.' always, upper-case E @native function Write.real(v: number): string? if v ~= v or v == huge or v == -huge then return nil @@ -22566,7 +21773,6 @@ local HEX = "0123456789ABCDEF" return table.concat(out) end --- a string's Part 21 literal (with the quotes) @native function Write.str(s: string): string if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" @@ -22593,7 +21799,6 @@ end end i += 1 else - -- a UTF-8 sequence -> code point local cp: number? = nil local len = 1 if c >= 0xC2 and c < 0xE0 then @@ -22756,7 +21961,6 @@ value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolea end Write.value = value --- record(ctx, type, args) -> appends TYPE(args) @native function Write.record(ctx: Ctx, t: any, args: any): boolean if not isName(t) then ctx.err = "bad entity type " .. tostring(t) @@ -107061,16 +106265,8 @@ return Source end __FILES["containers/Archive"] = function() --- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data --- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder --- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be --- encoded by any writable archive format through its list() / read(). --- --- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err --- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 }) --- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end }) --- a:list() a:read("a.txt") a:add("c.txt", "text") a:write() --- +-- containers/Archive: the in-memory Archive value (Types.Archive) archive formats return. Entries hold their data or +-- a lazy loader; write() calls the encoder the format attached, and any Archive can be encoded by any archive writer. -- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them -- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. local Err = __include("core/Err") @@ -107096,7 +106292,6 @@ type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?) local Methods = {} Methods.__index = Methods --- the public fields of an entry (no data / loader) local function public(e: Entry): Types.ArchiveEntry local out: any = {} for k, v in e :: any do @@ -107115,7 +106310,6 @@ function Methods.list(self: any): { Types.ArchiveEntry } return out end --- read(name) -> buffer | nil, Err (directories read as an empty buffer) function Methods.read(self: any, name: string): (buffer?, Err.Err?) local e: Entry? = self._byName[name] if not e then @@ -107137,7 +106331,6 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?) return buffer.create(0), nil end --- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name function Methods.add(self: any, name: string, data: buffer | string, opts: any?) local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) local o = opts or {} @@ -107152,7 +106345,6 @@ function Methods.add(self: any, name: string, data: buffer | string, opts: any?) Archive.put(self, e) end --- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) local enc: Encoder? = self._encode if not enc then @@ -107161,7 +106353,6 @@ function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) return enc(self, opts) end --- new(format, encode?) -> an empty Archive function Archive.new(format: string, encode: Encoder?): any return setmetatable({ kind = "archive", @@ -107173,7 +106364,6 @@ function Archive.new(format: string, encode: Encoder?): any }, Methods) end --- put(archive, entry): append (or replace by name) an entry function Archive.put(a: any, e: Entry) local old = a._byName[e.name] if old then @@ -107187,8 +106377,6 @@ function Archive.put(a: any, e: Entry) a._byName[e.name] = e end --- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another --- format's): what encoders iterate. nil when the value is not an archive. function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }? if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then return nil @@ -107215,7 +106403,6 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> return out end --- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?) return function(): (buffer?, Err.Err?) local out = buffer.create(n) @@ -107224,8 +106411,6 @@ function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err. end end --- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read --- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?) local items = Archive.entries(value) if not items then @@ -107246,8 +106431,6 @@ function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buff return out, nil end --- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value, --- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take. function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?) if type(value) == "buffer" or type(value) == "string" then local b = if type(value) == "string" then buffer.fromstring(value) else value @@ -107270,8 +106453,6 @@ function Archive.files(value: any, name: string?): ({ { name: string, data: buff return out, nil end --- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or --- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err function Archive.streamData(value: any): (buffer?, Err.Err?) if type(value) == "buffer" then return value, nil @@ -107302,8 +106483,7 @@ function Archive.streamData(value: any): (buffer?, Err.Err?) return Tar.write(list) end --- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store --- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date +-- MS-DOS date / time: stamp = date * 65536 + time (LHA / ARJ / ZIP); local time without a zone, read as UTC function Archive.fromDos(stamp: number): number? local time, date = stamp % 65536, stamp // 65536 local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) @@ -107314,7 +106494,7 @@ function Archive.fromDos(stamp: number): number? return Types.Date.daysFromCivil(y, m, d) * 86400 + secs end --- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31) +-- MS-DOS dates cover 1980-01-01 .. 2107-12-31 function Archive.toDos(t: number?): number if type(t) ~= "number" or t ~= t or t < 315532800 then return 0x210000 -- 1980-01-01 00:00 @@ -107329,8 +106509,6 @@ function Archive.toDos(t: number?): number return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 end --- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension --- (".tgz" -> ".tar"), else "data" function Archive.streamName(opts: any?, exts: { string }): string local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil if not name then @@ -107354,20 +106532,9 @@ return Archive end __FILES["containers/AudioWrap"] = function() --- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone --- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another --- format). New in rosetta. --- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); --- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; --- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV; --- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); --- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; --- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); --- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); --- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; --- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). --- --- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +-- containers/AudioWrap: a video container's audio track as a stream an audio format reads (a format never requires +-- another). New in rosetta. PCM / WAVEFORMATEX -> WAV, adpcm_swf -> f32 WAV, mp1-3 / ac3 -> frames back to back, +-- flac -> fLaC + metadata blocks, opus / vorbis -> Ogg, aac -> ADTS. E-AC-3 is UNSUPPORTED. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -107413,7 +106580,6 @@ local function concat(packets: { Types.Packet }, prefix: buffer?): buffer return out end --- ------------------------------------------------------------------------------------------------ WAV local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source) pcm_u8 = { 1, 8, 0 }, pcm_s8 = { 1, 8, 0 }, @@ -107514,7 +106680,6 @@ local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, return wav(f:finish(), data), nil end --- ------------------------------------------------------------------------------------------------ Ogg -- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) local function opusSamples(b: buffer): number local n = buffer.len(b) @@ -107670,7 +106835,6 @@ local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean } return nil, nil end --- ------------------------------------------------------------------------------------------------ ADTS local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) local c = track.config local profile, rateIndex, chanConfig @@ -107708,10 +106872,8 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er return w:finish(), nil end --- ------------------------------------------------------------------------------------------------ trim --- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's --- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus --- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding) +-- trim: a container's codec delay (Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, as ffmpeg) +-- and end padding function AudioWrap.trim(dec: any, skip: number, length: number?): any if skip <= 0 and length == nil then return dec @@ -107767,8 +106929,6 @@ function AudioWrap.trim(dec: any, skip: number, length: number?): any return w end --- ------------------------------------------------------------------------------------------------ wrap --- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) if type(track) ~= "table" or track.kind ~= "audio" then return nil, nil, Err.new(Err.ARG, "not an audio track") @@ -107875,18 +107035,9 @@ return AudioWrap end __FILES["containers/Avi"] = function() --- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in rosetta. --- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk --- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets --- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). --- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. --- --- local avi, err = Avi.read(buf, base, limit) --- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf --- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute --- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() --- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) --- +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + OpenDML 1.02), read and written. New in rosetta. The chunk +-- index comes from the OpenDML super index (indx -> ix##), else idx1 (movi-relative or absolute, detected), else a +-- scan of the movi lists. Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an odml / dmlh header. -- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -107924,8 +107075,6 @@ local function u32(b: buffer, o: number): number return readu32(b, o) end --- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not --- entered); returns where it stopped local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number while p + 8 <= limit do local id = readstring(b, p, 4) @@ -108069,7 +107218,6 @@ local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: numb return false end --- read(buf, base, limit) -> File | nil, Err function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then return nil, Err.new(Err.CORRUPT, "not an AVI file", base) @@ -108218,7 +107366,6 @@ function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) return file, nil end --- ------------------------------------------------------------------------------------------------ writing type WStream = { type: string, -- "vids" | "auds" handler: string, -- fccHandler (4 chars) @@ -108240,7 +107387,6 @@ type WOptions = { software: string?, } --- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order function Avi.write(opts: WOptions, chunks: { { any } }): buffer local ns = #opts.streams local lengths = table.create(ns, 0) @@ -108273,7 +107419,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer local riffSize = w:tell() w:u32le(0) w:string("AVI ") - -- hdrl w:string("LIST") local hdrlSize = w:tell() w:u32le(0) @@ -108351,7 +107496,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer w:u32le(4) w:u32le(frames) w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) - -- INFO local sw = (opts.software or "rosetta") .. "\0" if #sw % 2 == 1 then sw ..= "\0" @@ -108362,7 +107506,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer w:string("ISFT") w:u32le(#sw) w:string(sw) - -- movi w:string("LIST") local moviSize = w:tell() w:u32le(0) @@ -108384,7 +107527,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n }) end w:setU32le(moviSize, w:tell() - moviSize - 4) - -- idx1 w:string("idx1") w:u32le(#index * 16) for _, e in index do @@ -108397,7 +107539,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer return w:finish() end --- ------------------------------------------------------------------------------------------------ BITMAPINFO type BitmapInfo = { width: number, height: number, -- signed: > 0 = bottom-up rows @@ -108407,9 +107548,8 @@ type BitmapInfo = { extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none } --- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | --- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; --- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +-- BITMAPINFOHEADER: the palette is the last (2^bits) * 4 bytes after the header (B, G, R, x; a trailing "BottomUp" +-- tag skipped), as the VfW codecs store it function Avi.bitmapInfo(f: buffer): BitmapInfo? local n = buffer.len(f) if n < 40 then @@ -108447,16 +107587,9 @@ return Avi end __FILES["containers/Chunks"] = function() --- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional --- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a --- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing --- the loop. New in rosetta (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). --- --- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf) --- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG --- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end --- local c = Chunks.find(list, "SSND") --- +-- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and +-- padding): RIFF / RIFX / RF64, IFF / AIFF / AIFC, PNG (size first, CRC trailer), CAF (64-bit sizes). New in rosetta +-- (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). -- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in -- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). -- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one @@ -108513,7 +107646,6 @@ local function u32(b: buffer, o: number, be: boolean): number return if be then bit32.byteswap(v) else v end --- walk(b, p, limit, layout?) -> { Chunk } of [p, limit) function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Chunk } local L: Layout = layout or Chunks.RIFF local be = L.bigEndian == true @@ -108577,7 +107709,6 @@ function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Ch return list end --- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index function Chunks.find(list: { Chunk }, id: string, from: number?): (Chunk?, number?) for i = from or 1, #list do if list[i].id == id then @@ -108591,18 +107722,9 @@ return Chunks end __FILES["containers/Cpio"] = function() --- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment), --- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the --- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the --- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar --- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks --- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as --- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The --- archive formats (archive/cpio, archive/rpm's payload) build on it. --- --- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err --- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" }) --- +-- containers/Cpio: cpio, read and written, from cpio(5) (libarchive, GNU cpio) and POSIX.1-1988 (odc). Reads newc +-- (070701), crc (070702, byte sums verified), odc (070707), old binary in both byte orders; writes newc / crc / odc +-- padded to opts.block (512, as GNU cpio). A hard link group's data sits on its last link (as GNU cpio and bsdtar). -- Never throws: bad data returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -108654,7 +107776,6 @@ Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter local TRAILER = "TRAILER!!!" --- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset function Cpio.format(b: buffer, o: number): string? local n = buffer.len(b) if o + 6 <= n then @@ -108691,7 +107812,7 @@ local function num(b: buffer, o: number, n: number, base: number): number? return tonumber(s, base) end --- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32) +-- the crc format's checksum: the sum of the data bytes mod 2^32 function Cpio.checksum(b: buffer, o: number, n: number): number local s = 0 local i = o @@ -108708,7 +107829,6 @@ function Cpio.checksum(b: buffer, o: number, n: number): number return s % 4294967296 end --- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?) local h: any = {} local nameAt @@ -108771,7 +107891,6 @@ local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.E return h, nil end --- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) local o = offset or 0 local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) @@ -108870,7 +107989,6 @@ function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOption return out, { format = fmt } end --- ------------------------------------------------------------------------------------------------ writing type WriteEntry = { name: string, data: buffer?, -- file data (a symlink: its target, else taken from link) @@ -108908,7 +108026,6 @@ local function oct(v: number, w: number): string? return string.rep("0", w - #s) .. s end --- write(entries, opts?) -> buffer | nil, Err function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) local fmt = (opts and opts.format) or "newc" if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then @@ -109034,16 +108151,7 @@ end __FILES["containers/Demux"] = function() -- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). --- New in rosetta. A container parses its file once into an index of packets (track, pts, dts, duration, --- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives --- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file --- independently), a file-order cursor, keyframe seeking, packet copies on demand. --- --- local d = Demux.new("mkv", tracks, src, meta) --- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order --- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src --- d:finish() -- durations, per-track indexes --- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +-- New in rosetta. Packets are offset + length into the source buffer (or own bytes); per-track cursors are independent. local Types = __include("Types") local Demux = {} @@ -109076,7 +108184,6 @@ type Demux = typeof(setmetatable( D )) --- new(format, tracks, src, meta?) -> an empty index function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux return setmetatable({ kind = "demuxer" :: "demuxer", @@ -109102,7 +108209,6 @@ function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { }, D) end --- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number) local i = self.n + 1 self.n = i @@ -109115,13 +108221,11 @@ function D.add(self: Demux, track: number, pts: number, dts: number?, duration: self.len[i] = length end --- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer) self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) self.data[self.n] = data end --- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) function D.setExtra(self: Demux, key: string, value: any) local e = self.extra[self.n] if not e then @@ -109131,8 +108235,6 @@ function D.setExtra(self: Demux, key: string, value: any) e[key] = value end --- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's --- frame rate), and the track / file durations (seconds) where the container gave none function D.finish(self: Demux) local byTrack: { [number]: { number } } = {} for _, t in self.tracks do @@ -109192,7 +108294,6 @@ function D.finish(self: Demux) self.startTime = if start ~= math.huge and start > 0 then start else 0 end --- the Packet for index entry i (a copy of its bytes) function D._packet(self: Demux, i: number): Types.Packet local data = self.data[i] if not data then @@ -109224,7 +108325,6 @@ function D._packet(self: Demux, i: number): Types.Packet return p end --- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end function D.read(self: Demux, track: number?): Types.Packet? if track == nil then local i = self.gcur @@ -109247,14 +108347,12 @@ function D.read(self: Demux, track: number?): Types.Packet? return self:_packet(i) end --- packets(track?) -> an iterator of Packets from the current position (advancing it) function D.packets(self: Demux, track: number?): () -> Types.Packet? return function(): Types.Packet? return self:read(track) end end --- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors function D.count(self: Demux, track: number): number local list = self.byTrack[track] return if list then #list else 0 @@ -109268,7 +108366,6 @@ function D.get(self: Demux, track: number, k: number): Types.Packet? return self:_packet(i) end --- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?) local list = self.byTrack[track] local i = list and list[k] @@ -109278,7 +108375,6 @@ function D.info(self: Demux, track: number, k: number): (number?, number?, numbe return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] end --- rewind(track?): a track's cursor (or every cursor) back to the start function D.rewind(self: Demux, track: number?) if track then self.cur[track] = 1 @@ -109290,7 +108386,6 @@ function D.rewind(self: Demux, track: number?) self.gcur = 1 end --- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) function D.seek(self: Demux, seconds: number) local g = self.n + 1 for _, t in self.tracks do @@ -109313,7 +108408,6 @@ function D.seek(self: Demux, seconds: number) self.gcur = if g > self.n then 1 else g end --- track(kind) -> the first default track of the kind, else the first of the kind function D.track(self: Demux, kind: string): Types.Track? local first = nil for _, t in self.tracks do @@ -109336,11 +108430,6 @@ __FILES["containers/Ebml"] = function() -- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, -- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and -- minimal-length value elements. --- --- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated --- for id, off, size in Ebml.children(buf, off, limit) do ... end --- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() --- -- Never throws: malformed input gives nil (readers) or stops iteration. local Bytes = __include("core/Bytes") @@ -109350,7 +108439,6 @@ local Ebml = {} Ebml.UNKNOWN = -1 --- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) if pos >= limit then return nil, nil @@ -109383,7 +108471,6 @@ function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) return v, len end --- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) local v, len = Ebml.vint(buf, pos, limit) if v == nil or len == nil then @@ -109395,7 +108482,6 @@ function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) return v - (2 ^ (7 * len - 1) - 1), len end --- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) if pos >= limit then return nil, nil @@ -109412,7 +108498,6 @@ function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) return v, len end --- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) local id, il = Ebml.id(buf, pos, limit) if not id or not il then @@ -109425,8 +108510,6 @@ function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number? return id, size, pos + il + sl end --- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the --- limit is clipped; a malformed header ends the iteration) function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number) local pos = off return function(): (number?, number, number) @@ -109446,7 +108529,6 @@ function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, end end --- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) function Ebml.uint(buf: buffer, off: number, len: number): number local v = 0 for i = 0, math.min(len, 8) - 1 do @@ -109488,18 +108570,15 @@ function Ebml.binary(buf: buffer, off: number, len: number): buffer return b end --- ------------------------------------------------------------------------------------------------ writing local W = {} W.__index = W type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W)) --- writer(capacity?) -> an EBML byte builder function Ebml.writer(capacity: number?): Writer return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) end --- idBytes(id) -> the ID's bytes as written local function writeId(w: Bytes.Writer, id: number) if id >= 0x1000000 then w:u32be(id) @@ -109512,7 +108591,6 @@ local function writeId(w: Bytes.Writer, id: number) end end --- size as a minimal vint (n bytes: force a length) local function writeSize(w: Bytes.Writer, size: number, n: number?) local len = n or 1 if not n then @@ -109532,7 +108610,6 @@ local function writeSize(w: Bytes.Writer, size: number, n: number?) end Ebml.writeSize = writeSize --- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) function Ebml.vintString(v: number, n: number?): string local w = Bytes.writer(8) writeSize(w, v, n) @@ -109543,7 +108620,6 @@ function W.tell(self: Writer): number return self.w:tell() end --- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder function W.open(self: Writer, id: number): number writeId(self.w, id) local at = self.w:tell() @@ -109553,7 +108629,6 @@ function W.open(self: Writer, id: number): number return at end --- close(handle): patches the size of the element opened at handle function W.close(self: Writer, at: number) local w = self.w local v = w:tell() - at - 8 @@ -109564,7 +108639,6 @@ function W.close(self: Writer, at: number) end end --- unknownSize(id): a master element with an unknown size (live streams) function W.openUnknown(self: Writer, id: number) writeId(self.w, id) self.w:u8(0x01) @@ -109621,7 +108695,6 @@ function W.string(self: Writer, id: number, s: string) self.w:string(s) end --- binary(id, buf, off?, len?) function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?) local o = off or 0 local n = len or (buffer.len(b) - o) @@ -109630,7 +108703,6 @@ function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number self.w:bytes(b, o, n) end --- raw bytes (a pre-built element, block headers) function W.raw(self: Writer, s: string) self.w:string(s) end @@ -109638,13 +108710,11 @@ function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?) local o = off or 0 self.w:bytes(b, o, len or (buffer.len(b) - o)) end --- element header for a binary element whose payload follows in pieces: id + size function W.header(self: Writer, id: number, size: number) writeId(self.w, id) writeSize(self.w, size) end --- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space function W.void(self: Writer, n: number) self.w:u8(0xEC) if n - 2 < 127 then @@ -109668,17 +108738,9 @@ return Ebml end __FILES["containers/Fat"] = function() --- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories --- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names, --- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images --- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from --- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout. --- --- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message --- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/") --- local data, err = Fat.read(vol, entry) -- buffer | nil, message --- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image --- +-- containers/Fat: FAT12 / FAT16 / FAT32 over a byte range (BPB, chains, VFAT long names checksum-validated against +-- their 8.3 entry, NT lower-case flags; an MBR's first FAT partition) and a FAT12 floppy writer. New code, from +-- Microsoft's fatgen103 and the VFAT long-name layout. -- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by -- the cluster count (loops are errors). local Archive = __include("containers/Archive") @@ -109717,7 +108779,6 @@ type Entry = { shortName: string, } --- ------------------------------------------------------------------------------------------------ open local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?) if len < 512 then return nil, "truncated: smaller than a boot sector" @@ -109823,7 +108884,6 @@ function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Vol return nil, if o.partition then "no partition " .. o.partition else "no FAT partition" end --- ------------------------------------------------------------------------------------------------ chains local function nextCluster(v: Volume, c: number): number local f = v.base + v.fatOffset if v.bits == 12 then @@ -109849,7 +108909,6 @@ local function nextCluster(v: Volume, c: number): number return bit32.band(readu32(v.b, p), 0x0FFFFFFF) end --- the clusters of a chain (nil, message when it leaves the volume or loops) local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?) local out = {} local c = first @@ -109873,7 +108932,6 @@ local function clusterOffset(v: Volume, c: number): number return v.base + v.dataOffset + (c - 2) * v.spc * v.bps end --- the bytes of a chain, up to size bytes (nil = the whole chain) local function readChain(v: Volume, first: number, size: number?): (buffer?, string?) local csize = v.spc * v.bps local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters @@ -109902,7 +108960,6 @@ local function readChain(v: Volume, first: number, size: number?): (buffer?, str return out, nil end --- ------------------------------------------------------------------------------------------------ directories local function latin1(s: string): string if not string.find(s, "[\128-\255]") then return s @@ -109928,7 +108985,6 @@ local function ucs2(b: buffer, o: number, n: number, out: { number }) end end --- the entries of one directory's bytes local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry } local lfn: { [number]: { number } } = {} local lfnSum, lfnCount = -1, 0 @@ -110018,7 +109074,6 @@ local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry } return subdirs end --- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents) function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?) local out: { Entry } = {} local limit = maxEntries or 65536 @@ -110072,7 +109127,6 @@ function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?) return out, nil end --- read(vol, entry) -> the file's bytes function Fat.read(v: Volume, e: Entry): (buffer?, string?) if e.dir or e.size == 0 then return buffer.create(0), nil @@ -110083,7 +109137,6 @@ function Fat.read(v: Volume, e: Entry): (buffer?, string?) return readChain(v, e.cluster, e.size) end --- ------------------------------------------------------------------------------------------------ write type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? } type WriteOptions = { size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440) @@ -110108,7 +109161,6 @@ end type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number } --- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean) local base, ext = string.match(name, "^(.*)%.([^%.]*)$") if not base or base == "" then @@ -110160,7 +109212,6 @@ local function shortName(name: string, used: { [string]: boolean }): (string, nu return " ___", 0, true end --- the directory entries (32 bytes each) of a node's children local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer local w = {} local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?) @@ -110225,7 +109276,6 @@ local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label return out end --- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths) function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?) local o: WriteOptions = opts or {} local g = GEOMETRY[o.size or 1440] @@ -110350,7 +109400,6 @@ function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string? setFat(1, 0xFFF) buffer.copy(img, bps, fat) buffer.copy(img, (1 + g.fat) * bps, fat) - -- boot sector buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") buffer.writeu16(img, 11, bps) buffer.writeu8(img, 13, g.spc) @@ -110377,20 +109426,10 @@ return Fat end __FILES["containers/Iso9660"] = function() --- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary, --- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross --- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is --- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names --- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the --- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE --- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock --- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog --- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet --- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns --- the stored bytes), UDF, writing. --- --- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err --- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents) +-- containers/Iso9660: ISO 9660 (ECMA-119) images, read; from ECMA-119, SUSP / RRIP 1.12, Joliet and El Torito 1.0, no +-- code ported. Name sets: Rock Ridge, else Joliet (%/@, %/C, %/E), else plain (";1" and a trailing "." dropped); +-- multi-extent files joined, CL / RE / PL relocations resolved, El Torito catalog in info.boot. Not supported: zisofs +-- (read returns the stored bytes), interleaved files (Err.UNSUPPORTED), UDF, writing. local Err = __include("core/Err") local Types = __include("Types") local Text = __include("codecs/text/Text") @@ -110423,7 +109462,6 @@ type ReadOptions = { local SECTOR = 2048 local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" } --- ------------------------------------------------------------------------------------------------ fields local function u16(b: buffer, o: number): number return buffer.readu16(b, o) end @@ -110456,10 +109494,8 @@ local function longDate(b: buffer, o: number): number? return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 }) end --- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge type Susp = { [string]: any } --- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } } local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } } local out = {} while o + 4 <= e do @@ -110494,7 +109530,6 @@ local function suspEntries(b: buffer, base: number, limit: number, o: number, e: return out end --- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs } local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp local rr: Susp = {} local name: { string }? = nil @@ -110567,7 +109602,6 @@ local function rockRidge(b: buffer, base: number, limit: number, o: number, e: n return rr end --- ------------------------------------------------------------------------------------------------ directories type Record = { name: string, dir: boolean, @@ -110580,7 +109614,6 @@ type Record = { rr: Susp?, } --- the records of a directory extent (without "." and "..") | nil, Err local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?) if at + size > limit then return nil, Err.new(Err.TRUNCATED, "directory past the end", at) @@ -110636,7 +109669,6 @@ local function records(b: buffer, base: number, limit: number, at: number, size: return out, nil end --- the root record of a volume descriptor at vd -> lba, size local function root(b: buffer, vd: number): (number, number) return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10) end @@ -110659,7 +109691,6 @@ local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number return nil end --- ------------------------------------------------------------------------------------------------ El Torito local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }? if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then return nil @@ -110687,8 +109718,6 @@ local function boot(b: buffer, base: number, limit: number, vd: number, bs: numb return info end --- ------------------------------------------------------------------------------------------------ read --- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) local base = offset or 0 local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base))) @@ -110876,7 +109905,6 @@ function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOpt return out, info end --- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?) if e.interleaved then return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name) @@ -110894,7 +109922,6 @@ function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err return out, nil end --- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16 function Iso9660.valid(b: buffer, offset: number?): boolean local p = (offset or 0) + 16 * SECTOR return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001" @@ -110907,15 +109934,6 @@ __FILES["containers/IsoBmff"] = function() -- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) -- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, -- mov, heif, avif build on it. Written from the specifications; no third-party code. --- --- local IsoBmff = require("@rosetta/containers/IsoBmff") --- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) --- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) --- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) --- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs --- local data = IsoBmff.itemData(r, items, id) -- an item's bytes --- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) --- -- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit -- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', -- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), @@ -110945,8 +109963,6 @@ local TOP: { [string]: boolean } = { styp = true, sidx = true, meta = true, uuid = true, PICT = true, } --- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, --- nil when it is not an ISO BMFF file function IsoBmff.sniff(r: Bytes.Reader): string? local head = r:peek(12) if #head < 8 then @@ -110965,18 +109981,15 @@ function IsoBmff.sniff(r: Bytes.Reader): string? return nil end --- parse(r, opts?) -> Movie | nil, Err function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?) return Demux.parse(r, opts) end --- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture }) local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") return Meta.tags(r.buf, ilst) end --- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) local meta = Box.path(movie.boxes, "meta") if not meta then @@ -110985,12 +109998,10 @@ function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) return Meta.items(r.buf, meta) end --- itemData(r, items, id) -> buffer | nil, Err function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?) return Meta.itemData(r.buf, r.base, r.limit, items, id) end --- sample(r, track, i) -> a copy of sample i (1-based) function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? if i < 1 or i > t.sampleCount then return nil @@ -111001,8 +110012,6 @@ function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? return out end --- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / --- dts / duration in their track's timescale ticks and a copy of the sample bytes. function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) local movie, err = Demux.parse(r, opts) if not movie then @@ -111042,7 +110051,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) cursor[trackId] = i + 1 return packet(t, i) end - -- all tracks in file order local best: Track? = nil local bestOff = math.huge for _, t in movie.tracks do @@ -111059,7 +110067,7 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) return packet(best, i) end end - -- seek(seconds): every track to its last sync sample at or before the time + -- every track to its last sync sample at or before the time function dmx.seek(_self: any, seconds: number) for _, t in movie.tracks do local target = seconds * t.timescale @@ -111085,7 +110093,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) return dmx, nil end --- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?) return Mux.mux(spec) end @@ -111137,7 +110144,6 @@ local function isIlstItem(parentType: string?): boolean return parentType == "ilst" end --- header(buf, p, limit) -> Box (without children) | nil, Err function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) if p + 8 > limit then return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) @@ -111174,8 +110180,6 @@ function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil end --- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A --- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?) local d = depth or 0 local out: { Box } = {} @@ -111228,7 +110232,6 @@ function Box.list(b: buffer, p: number, limit: number, parentType: string?, dept return out, firstErr end --- child(box, type) -> the first child of that type function Box.child(box: Box?, typ: string): Box? if not box or not box.children then return nil @@ -111241,7 +110244,6 @@ function Box.child(box: Box?, typ: string): Box? return nil end --- children(box, type) -> every child of that type function Box.childrenOf(box: Box?, typ: string): { Box } local out = {} if box and box.children then @@ -111254,7 +110256,6 @@ function Box.childrenOf(box: Box?, typ: string): { Box } return out end --- path(boxes or box, "moov/trak/mdia") -> the first box along the path function Box.path(root: any, path: string): Box? local cur: any = root for part in string.gmatch(path, "[^/]+") do @@ -111276,7 +110277,6 @@ function Box.path(root: any, path: string): Box? return cur end --- version / flags of a full box function Box.fullHeader(b: buffer, box: Box): (number, number) if box.data + 4 > box.stop then return -1, 0 @@ -111289,12 +110289,9 @@ return Box end __FILES["containers/IsoBmff/Demux"] = function() --- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): --- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration --- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / --- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). --- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the --- reader's buffer. Never throws. +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8), +-- edit lists and fragments (mvex / trex, moof / traf / tfhd / tfdt / trun). The per-sample tables are columnar arrays, +-- offsets absolute in the reader's buffer. Never throws. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Box = __include("containers/IsoBmff/Box") @@ -111310,8 +110307,6 @@ local Demux = {} type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) --- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the --- sample tables and the ISO facts type Track = { id: number, kind: "video" | "audio" | "subtitle" | "data", @@ -111337,7 +110332,6 @@ type Track = { skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming) delay: number, -- movie ticks of an initial empty edit playDuration: number?, -- media ticks the edit list plays (nil: all) - -- samples sampleCount: number, offsets: { number }, -- absolute offsets in the buffer sizes: { number }, @@ -111400,7 +110394,6 @@ local function descLen(r: Bytes.Reader): number return n end --- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) local r = reader(b, box) r:skip(4) -- version / flags @@ -111440,7 +110433,6 @@ function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) return oti, dsi, avg end --- the sample entry `e` of a track with handler `handler`: fills the codec facts into t local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) local r = reader(b, e) r:skip(6) @@ -111543,7 +110535,6 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) end end --- media handler / header / sample tables of one trak -> Track | nil, Err local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?) local tkhd = Box.child(trak, "tkhd") local mdia = Box.child(trak, "mdia") @@ -111611,7 +110602,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ if not stbl then return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) end - -- sample descriptions local stsd = Box.child(stbl, "stsd") if stsd and stsd.data + 8 <= stsd.stop then local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") @@ -111620,7 +110610,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ end t.sampleEntries = entries end - -- edit list local elst = Box.path(trak, "edts/elst") if elst then local r = reader(b, elst) @@ -111663,7 +110652,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ end end end - -- sample sizes local maxSamples = o.maxSamples or 2 ^ 25 local sizes = t.sizes local count = 0 @@ -111722,7 +110710,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ end end end - -- decode times local dts, durs = t.dts, t.durations local stts = Box.child(stbl, "stts") if stts and count > 0 then @@ -111756,7 +110743,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ dts[i], durs[i] = 0, 0 end end - -- composition offsets local ctts = Box.child(stbl, "ctts") if ctts and count > 0 then local r = reader(b, ctts) @@ -111783,7 +110769,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ t.cts = cts end end - -- sync samples local stss = Box.child(stbl, "stss") if stss then local r = reader(b, stss) @@ -111797,7 +110782,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ t.sync = sync end end - -- chunk offsets + sample-to-chunk -> sample offsets local stco = Box.child(stbl, "stco") local co64 = Box.child(stbl, "co64") local chunks: { number } = {} @@ -111904,12 +110888,10 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ t.sampleDescription = nil end end - -- fragment defaults t.trex = trex[t.id] return t, nil end --- the movie fragments (moof) after the moov: appends their samples to the tracks local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err? local maxSamples = o.maxSamples or 2 ^ 25 for _, moof in top do @@ -112041,7 +111023,6 @@ type Movie = { fragmented: boolean, } --- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) local o: Options = opts or {} local b = r.buf @@ -112186,7 +111167,6 @@ local function uint(r: Bytes.Reader, size: number): number return 0 end --- ------------------------------------------------------------------------------------------------ HEIF items type Property = { type: string, box: Box.Box, [string]: any } type Item = { id: number, @@ -112257,7 +111237,6 @@ local function property(b: buffer, box: Box.Box): Property return p end --- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) local out: Items = { items = {}, order = {}, properties = {} } local pitm = Box.child(meta, "pitm") @@ -112407,8 +111386,6 @@ function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) return out, nil end --- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit --- bound the file in the buffer function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?) local it = items.items[id] if not it then @@ -112450,7 +111427,6 @@ function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: return out, nil end --- ------------------------------------------------------------------------------------------------ iTunes tags -- ilst item -> standard tag name local TAG: { [string]: string } = { ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", @@ -112484,7 +111460,6 @@ local GENRES = { type Picture = { mime: string, data: buffer } --- tags(buf, ilst) -> Tags, { Picture } function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture }) local tags: { [string]: string } = {} local pics: { Picture } = {} @@ -112550,7 +111525,6 @@ function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture return tags, pics end --- ------------------------------------------------------------------------------------------------ ilst writer local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ()) local start = w:tell() w:u32be(0) @@ -112580,8 +111554,6 @@ local function num(s: string?): number return math.clamp(math.floor(v), 0, 65535) end --- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' --- freeform com.apple.iTunes items) and cover pictures function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) box(w, "ilst", function() local keys = {} @@ -112660,7 +111632,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { end) end --- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +-- udta / meta (hdlr mdir) / ilst function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) box(w, "udta", function() box(w, "meta", function() @@ -112683,11 +111655,9 @@ return Meta end __FILES["containers/IsoBmff/Mux"] = function() --- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak --- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks --- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample --- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + --- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +-- containers/IsoBmff/Mux: writes a progressive ISO BMFF / MP4 / M4A file (ISO/IEC 14496-12): ftyp, moov first ("fast +-- start"), the samples interleaved in chunks in one mdat, udta / meta / ilst tags; co64 past 4 GB. Audio and video +-- sample entries with their configuration box, plus raw child boxes. Never throws: bad specs return nil, Err.ARG. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Meta = __include("containers/IsoBmff/Meta") @@ -112838,7 +111808,6 @@ end type Chunk = { track: number, first: number, count: number, time: number, offset: number } --- runs of equal values: { { count, value } } local function runs(n: number, value: (number) -> number): { { number } } local out = {} for i = 1, n do @@ -113065,7 +112034,6 @@ local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: bo end) end --- mux(spec) -> buffer | nil, Err function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") @@ -113160,7 +112128,6 @@ function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) end end local co64 = mdatSize > 4294967295 - 2 ^ 24 - -- ftyp local w = Bytes.writer(mdatSize + 4096) box(w, "ftyp", function() w:string(spec.brand or "isom") @@ -113210,10 +112177,6 @@ __FILES["containers/IsoBmff/QtPalette"] = function() -- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey -- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the -- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). --- --- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) --- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil --- -- Never throws. local readu8, writeu32 = buffer.readu8, buffer.writeu32 @@ -113276,8 +112239,7 @@ local function defaultTable(bits: number): buffer return pal end --- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size --- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +-- Cinepak's grey flag selects its own grey mode, so no grey palette is made for it function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) if start + 86 > stop or stop > buffer.len(b) then return nil, nil @@ -113331,11 +112293,6 @@ __FILES["containers/MacFile"] = function() -- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with -- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix -- seconds) and comment. Writers pair them back with collect(). --- --- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" }) --- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string --- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes --- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped) -- New code. Never throws. local Err = __include("core/Err") local Archive = __include("containers/Archive") @@ -113383,7 +112340,6 @@ for i, u in ROMAN do FROM_UNICODE[u] = 127 + i end --- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through) function MacFile.name(s: string): string if not string.find(s, "[\128-\255]") then return s @@ -113396,7 +112352,6 @@ function MacFile.name(s: string): string return table.concat(out) end --- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes) function MacFile.roman(s: string): string if not string.find(s, "[\128-\255]") or not utf8.len(s) then return s @@ -113415,8 +112370,6 @@ local function four(s: any): string return string.sub(s .. "\0\0\0\0", 1, 4) end --- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and --- there is a resource fork) and, when non-empty, the resource fork entry function MacFile.put(a: any, f: Info, noData: boolean?) local common = { macType = f.type, @@ -113439,8 +112392,6 @@ function MacFile.put(a: any, f: Info, noData: boolean?) end end --- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a --- buffer or a string (one data fork named name, default "data") function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?) local files, err = Archive.files(value, name) if not files then @@ -113494,7 +112445,6 @@ local readu8 = buffer.readu8 local MpegEs = {} --- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil function MpegEs.findStart(b: buffer, p: number, limit: number): number? local i = p while i + 3 <= limit do @@ -113527,7 +112477,6 @@ type Picture = { } type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } --- info(b, off, limit) -> the first sequence header's facts | nil function MpegEs.info(b: buffer, off: number, limit: number): Info? local p = MpegEs.findStart(b, off, limit) local info: Info? = nil @@ -113551,7 +112500,6 @@ function MpegEs.info(b: buffer, off: number, limit: number): Info? return info end --- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number) local p = MpegEs.findStart(b, off, limit) local count = 0 @@ -113566,8 +112514,6 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num return 0, 0 end --- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture --- coding extension (3 = frame when there is none: MPEG-1) function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number local q = MpegEs.findStart(b, p + 4, limit) local count = 0 @@ -113587,9 +112533,6 @@ function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number return 3 end --- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its --- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures --- is one unit (fields = 2) function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local out: { Picture } = {} local unitStart: number? = nil @@ -113638,7 +112581,6 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } return out end --- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean local p = MpegEs.findStart(b, off, limit) local count = 0 @@ -113666,12 +112608,7 @@ __FILES["containers/MpegPs"] = function() -- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private -- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, -- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). --- --- local ps, err = MpegPs.read(buf, base, limit) --- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or --- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance --- --- Never throws: malformed packets are skipped and counted in ps.errors. +-- Never throws: malformed packets are skipped (ps.errors). Private stream 1 sub-streams are keyed 0xBD00 + their id. local Err = __include("core/Err") local MpegEs = __include("containers/MpegEs") @@ -113706,7 +112643,6 @@ local function ts(b: buffer, p: number): number return v end --- read(buf, base, limit) -> File | nil, Err function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 } local types: { [number]: number } = {} @@ -113889,16 +112825,8 @@ __FILES["containers/MpegTs"] = @native function() -- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same --- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a --- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections --- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity --- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. --- --- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } --- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed --- --- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is --- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. +-- author; no third-party code); changed: the unit queue keeps an explicit tail (#q on a table with holes at its front +-- loses units under LuaJIT's border rule). Never throws: bad input is skipped and counted in `stats`. local Crc32 = __include("core/Crc32") local MpegTs = {} @@ -114060,7 +112988,6 @@ type Demuxer = typeof(setmetatable( return self end --- PSI --------------------------------------------------------------------------------------------------------- @native local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) local info = CODECS[streamType] @@ -114147,7 +113074,6 @@ end end buffer.copy(s.buf, s.len, src, from, n) s.len += n - -- every complete section in the buffer while s.active and s.len >= 3 do if readu8(s.buf, 0) == 0xFF then s.active = false -- stuffing: no more sections until the next unit start @@ -114192,7 +113118,6 @@ end sectionBytes(self, pid, s, b, pos, stop) end --- PES --------------------------------------------------------------------------------------------------------- @native local function completePes(self: Demuxer, pid: number, st: PesState) st.active = false @@ -114404,7 +113329,6 @@ end end end --- packets ----------------------------------------------------------------------------------------------------- @native local function packet(self: Demuxer, b: buffer, pk: number) local stats = self.stats @@ -114460,7 +113384,6 @@ end return -- adaptation field only: the counter does not advance end end - -- continuity counter local ccError = false local last = self._cc[pid] if last ~= nil and not discontinuity then @@ -114480,8 +113403,6 @@ end end end --- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for --- pull(). Returns false for a bad argument. @native function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean local src: buffer if type(data) == "string" then @@ -114500,7 +113421,6 @@ end if n < 0 then return false end - -- append to the pending bytes local need = self._pendLen + n if need > buffer.len(self._pend) then local cap = buffer.len(self._pend) @@ -114566,7 +113486,6 @@ end return true end --- The next completed unit (any PID), or nil. @native function Demuxer.pull(self: Demuxer): Unit? local q = self._queue local h = self._qhead @@ -114585,8 +113504,6 @@ end return u end --- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next --- unit start). Units still queue up for pull(). @native function Demuxer.flush(self: Demuxer) local pids = {} for pid, st in self._pes do @@ -114601,7 +113518,6 @@ end self._pendLen = 0 end --- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). @native function Demuxer.reset(self: Demuxer) self._pendLen = 0 for _, st in self._pes do @@ -114620,7 +113536,6 @@ end self._qtail = 0 end --- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). @native function Demuxer.streamFor(self: Demuxer, kind: string): Stream? for _, s in self.streams do if s.kind == kind then @@ -114632,9 +113547,6 @@ end type DemuxOptions = { videoPid: number?, audioPid: number? } --- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / --- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / --- audio (PES stream_id). Never throws; a bad argument gives empty lists. @native function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed local d = MpegTs.new() d:push(data) @@ -114684,7 +113596,6 @@ type DemuxOptions = { videoPid: number?, audioPid: number? } } end --- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). @native function MpegTs.concat(units: { Unit }): buffer local n = 0 for _, u in units do @@ -114706,24 +113617,9 @@ __FILES["containers/Ogg"] = @native function() --- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 --- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and --- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture --- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); --- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad --- input gives nil, err). --- --- local demux, err = Ogg.open(buf) --- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end --- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator --- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil --- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) --- --- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) --- local s = mux:stream(serial?) -- one logical stream --- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages --- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes --- local file = mux:finish() -- every stream ends with an eos page +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer (absorbed from ogg-luau be9f604, same author, no third-party +-- code) and the muxer (Ogg/Mux, new). Packets are reassembled across pages per serial; seeking bisects byte offsets +-- to the page holding a granule. Never throws. local Err = __include("core/Err") local Page = __include("containers/Ogg/Page") local Mux = __include("containers/Ogg/Mux") @@ -114756,7 +113652,6 @@ type Stream = { lastGranule: number, -- the last known granule of the stream (-1 if none) } --- Reader: the packet cursor of one logical stream local Reader = {} Reader.__index = Reader @@ -114781,7 +113676,6 @@ Reader.__index = Reader }, Reader) end --- Load the next page of this serial; false at the end of the data @native function Reader._nextPage(self: any): boolean local b, d = self.buf, self.demux while true do @@ -114834,7 +113728,6 @@ end end end --- The next packet, or nil at the end of the stream @native function Reader.nextPacket(self: any): Packet? if self.ended then return nil @@ -114912,7 +113805,6 @@ end end end --- Back to the start of the stream (the identification packet comes next) @native function Reader.rewind(self: any) self.pagePos = self.start self.page = nil @@ -114923,7 +113815,6 @@ end self.ended = false end --- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them @native function Reader._at(self: any, p: PageInfo) self:rewind() self.pagePos = p.offset @@ -114942,10 +113833,7 @@ end self.ended = false end --- Seek so that the next packet is the first one that starts at or before granule g: positions after the last --- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the --- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start --- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +-- seekGranule: after the last page with granule <= g (bisection, then a short scan); before every granule rewinds (-1) @native function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) local b, d = self.buf, self.demux local serial = self.serial @@ -114991,13 +113879,9 @@ end return best.granule, nil end --- Demux local Demux = {} Demux.__index = Demux --- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied --- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = --- true lists every bos page in the file (chained streams), not just the first group @native function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) local buf: buffer if type(src) == "buffer" then @@ -115064,7 +113948,6 @@ Demux.__index = Demux return d, nil end --- Scan backwards from the end for each stream's last granule @native function Demux._scanLast(self: any) if self._lastDone then return @@ -115087,7 +113970,6 @@ end end end --- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } @native function Demux.streams(self: any): { Stream } self:_scanLast() return self._streams @@ -115098,7 +113980,6 @@ end return self._bySerial[serial] end --- The serial of the first stream of a codec, or nil @native function Demux.find(self: any, codec: string): number? for _, s in self._streams do if s.codec == codec then @@ -115108,7 +113989,6 @@ end return nil end --- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err @native function Demux.reader(self: any, serial: number): (any, Err.Err?) local r = self._readers[serial] if r then @@ -115143,7 +114023,6 @@ end end end --- for p in demux:packets(serial) do ... end (continues from the stream's current position) @native function Demux.packets(self: any, serial: number): () -> Packet? local r = self:reader(serial) return @native function() @@ -115151,7 +114030,6 @@ end end end --- Copy a packet's bytes into a fresh buffer of its own @native function Ogg.copy(p: Packet): buffer local c = buffer.create(p.size) buffer.copy(c, 0, p.data, p.offset, p.size) @@ -115169,14 +114047,6 @@ __FILES["containers/Ogg/Mux"] = @native function() -- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last -- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages -- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. --- --- local mux = Mux.new({ pageSize = 4096 }) --- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) --- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page --- s:packet(tags, 0, { flush = true }) --- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) --- local out = mux:finish() -- closes every stream with an eos page --- -- Never throws: a bad argument returns false, Err. local Err = __include("core/Err") local Page = __include("containers/Ogg/Page") @@ -115198,7 +114068,6 @@ type PacketOptions = { eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) } --- new(opts?) -> Mux @native function Mux.new(opts: Options?): any local size = opts and opts.pageSize or 4096 if type(size) ~= "number" or size < 1 then @@ -115213,7 +114082,6 @@ type PacketOptions = { }, Mux) end --- stream(serial?) -> Stream (serials must be unique in the file) @native function Mux.stream(self: any, serial: number?): any local sr = serial or self.nextSerial self.nextSerial = math.max(self.nextSerial, sr + 1) @@ -115243,7 +114111,6 @@ end return c end --- close the page being built (also when empty, for eos) @native function Stream._flush(self: any, eos: boolean) local nseg = #self.lacing local n = 27 + nseg + self.dataLen @@ -115284,8 +114151,6 @@ end end end --- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet --- (-1: unknown, not recommended); offset / length select a range of data. @native function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) if self.ended then return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) @@ -115342,14 +114207,12 @@ end return true, nil end --- flush(): close the current page now (if it holds anything) @native function Stream.flush(self: any) if not self.ended and #self.lacing > 0 then self:_flush(false) end end --- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) @native function Mux.finish(self: any): buffer for _, s in self.streams do if not s.ended then @@ -115374,10 +114237,9 @@ __FILES["containers/Ogg/Page"] = @native function() --- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header --- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, --- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. --- +-- containers/Ogg/Page: Ogg pages (RFC 3533): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the crc field read as +-- zero), header parsing and the capture-pattern resync. Absorbed from ogg-luau be9f604 (same author, no third-party +-- code). Never throws: invalid or truncated data gives nil. -- A page header (27 bytes + segment table): -- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) -- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data @@ -115405,7 +114267,6 @@ type Info = { local CRC = Crc32.MSB_TABLE Page.CRC_TABLE = CRC --- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc @native local function crcRange(b: buffer, from: number, to: number, crc: number): number for i = from, to - 1 do crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) @@ -115413,7 +114274,7 @@ Page.CRC_TABLE = CRC return crc end --- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +-- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed) @native function Page.crc32(b: buffer, offset: number?, len: number?): number local o = offset or 0 local n = len or (buffer.len(b) - o) @@ -115423,8 +114284,6 @@ end return crcRange(b, o, o + n, 0) end --- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", --- "version", "crc"). verify = false skips the CRC check. @native function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) local size = buffer.len(b) if pos < 0 or pos + 27 > size then @@ -115475,8 +114334,6 @@ end }, nil end --- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the --- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. @native function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? local size = buffer.len(b) local lim = math.min(limit or size, size - 27 + 1) @@ -115495,7 +114352,6 @@ end return nil end --- The last valid page starting at an offset in [floor, pos] (searching backwards). @native function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? local size = buffer.len(b) local lo = math.max(floor or 0, 0) @@ -115514,7 +114370,6 @@ end return nil end --- The identification of a codec from a stream's first packet (the bos page's packet) @native function Page.codec(b: buffer, off: number, len: number): string @native local function is(s: string, at: number): boolean if at + #s > len then @@ -115552,18 +114407,6 @@ __FILES["containers/Riff"] = function() -- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently -- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from -- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. --- --- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer --- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false --- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf --- local c = Riff.find(f, "fmt ") --- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type) --- --- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX) --- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } }) --- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB --- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB --- -- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past -- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a -- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of @@ -115602,13 +114445,11 @@ type ReadOptions = { maxChunks: number?, -- stop after this many chunks (default 100000) } --- ------------------------------------------------------------------------------------------------ read local function u32(b: buffer, o: number, be: boolean): number local v = readu32(b, o) return if be then bit32.byteswap(v) else v end --- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil function Riff.sniff(r: any): string? local magic = r:peek(4) if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then @@ -115618,8 +114459,6 @@ function Riff.sniff(r: any): string? return if #form == 4 then form else nil end --- walk(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2, --- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64) local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any): { Chunk } local layout: Chunks.Layout = { bigEndian = be, @@ -115639,7 +114478,6 @@ local function walk(b: buffer, p: number, limit: number, be: boolean, opts: Read return Chunks.walk(b, p, limit, layout) :: any end --- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) local r = if type(src) == "buffer" then Bytes.reader(src) else src if type(r) ~= "table" or type(r.buf) ~= "buffer" then @@ -115697,7 +114535,6 @@ function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) return f, nil end --- find(file, id, from?) -> the first chunk with that id (after index from), and its index function Riff.find(f: File, id: string, from: number?): (Chunk?, number?) for i = (from or 0) + 1, #f.chunks do if f.chunks[i].id == id then @@ -115707,7 +114544,6 @@ function Riff.find(f: File, id: string, from: number?): (Chunk?, number?) return nil, nil end --- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil function Riff.listType(f: File, c: Chunk): string? if c.avail < 4 then return nil @@ -115715,7 +114551,6 @@ function Riff.listType(f: File, c: Chunk): string? return readstring(f.buf, c.offset, 4) end --- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type) function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } if c.avail < 4 then return {} @@ -115723,12 +114558,10 @@ function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) end --- body(file, chunk) -> a Reader over the chunk's available body function Riff.body(f: File, c: Chunk): Bytes.Reader return Bytes.reader(f.buf, c.offset, c.avail) end --- u16 / u32 in the file's byte order (for chunk bodies) function Riff.u16(f: File, o: number): number if f.bigEndian then return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) @@ -115739,7 +114572,6 @@ function Riff.u32(f: File, o: number): number return u32(f.buf, o, f.bigEndian) end --- ------------------------------------------------------------------------------------------------ write local Writer = {} Writer.__index = Writer @@ -115750,7 +114582,6 @@ type WriteOptions = { rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF) } --- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file function Riff.writer(form: string, opts: WriteOptions?): any return setmetatable({ form = string.sub(form .. " ", 1, 4), @@ -115762,8 +114593,6 @@ function Riff.writer(form: string, opts: WriteOptions?): any }, Writer) end --- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a --- list of buffers written one after the other (a data chunk bigger than one buffer) function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?) local parts = {} local n = 0 @@ -115781,7 +114610,6 @@ function Writer.chunk(self: any, id: string, body: any, offset: number?, length: table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) end --- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style) function Writer.list(self: any, listType: string, items: { { any } }) local w = Bytes.writer() w:string(string.sub(listType .. " ", 1, 4)) @@ -115803,7 +114631,6 @@ function Writer.list(self: any, listType: string, items: { { any } }) self:chunk("LIST", w:finish()) end --- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied) function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?) local total = 4 -- the form type local big = false @@ -115894,18 +114721,9 @@ return Riff end __FILES["containers/Tar"] = function() --- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles --- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, --- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, --- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar --- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, --- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX --- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- --- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). --- --- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } --- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) --- +-- containers/Tar: tar (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written; from POSIX pax(1) (IEEE Std +-- 1003.1-2017) and the GNU tar manual. Reads v7 / ustar / GNU / pax headers ('x' / 'g', 'L' / 'K', base-256, signed +-- checksums); writes ustar + pax, or GNU 'L' / 'K'. Not supported: sparse files, multi-volume (listed as "S" / "M"). -- Never throws: bad data returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -115973,7 +114791,6 @@ local function checksum(b: buffer, o: number): (number, number) return u, s end --- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum function Tar.valid(b: buffer, o: number): boolean if o + BLOCK > buffer.len(b) or zeros(b, o) then return false @@ -116012,7 +114829,6 @@ end type ReadOptions = { maxEntries: number? } -- default 1e6 --- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?) local o = offset or 0 local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) @@ -116156,7 +114972,6 @@ function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions return out, nil end --- ------------------------------------------------------------------------------------------------ writing type WriteEntry = { name: string, data: buffer?, @@ -116200,7 +115015,6 @@ local function paxRecord(key: string, value: string): string return tostring(n) .. body end --- one header block (the checksum filled in) local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer local h = buffer.create(BLOCK) field(h, 0, 100, name) @@ -116235,7 +115049,6 @@ local function split(path: string): (string?, string?) return nil, nil end --- write(entries, opts?) -> buffer | nil, Err function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) local fmt = (opts and opts.format) or "pax" local w = Bytes.writer(BLOCK * (2 * #entries + 2)) @@ -116323,24 +115136,10 @@ end __FILES["containers/Zip"] = function() --- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from --- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an --- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor --- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, --- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly --- (codecs/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/Deflate compress, stored --- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. --- --- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader --- for _, e in zip:list() do print(e.name, e.size) end --- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked --- --- local w = Zip.writer() --- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds --- local file = w:finish({ comment = "..." }) --- --- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native --- code it reaches (Deflate, Crc32) does not throw either. +-- containers/Zip: ZIP (PKWARE APPNOTE 6.3), read and written. The reader is absorbed from zip-luau 121d4b0 (same +-- author, no third-party code): EOCD search, ZIP64, prefix shifts (self-extractor stubs), stored / deflated entries, +-- data descriptors. The writer is new: stored / deflated, UTF-8 names, DOS times, raw entry copies, ZIP64 when needed. +-- Never throws: corrupt archives and bad arguments return nil, Err. local Err = __include("core/Err") local Types = __include("Types") local Bytes = __include("core/Bytes") @@ -116373,7 +115172,6 @@ type Entry = { cdExtraLen: number, } --- ------------------------------------------------------------------------------------------------ read local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 @@ -116408,7 +115206,6 @@ local Archive = {} Archive.__index = Archive --- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) function Zip.isZip(buf: buffer | string): boolean local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) @@ -116576,8 +115373,6 @@ local function parse(b: buffer): (any, Err.Err?) }, Archive) end --- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a --- part of a bigger buffer) function Zip.open(src: any): (any, Err.Err?) local b: buffer if type(src) == "string" then @@ -116602,14 +115397,11 @@ function Zip.open(src: any): (any, Err.Err?) return res, err end --- every entry (directories included), in central directory order function Archive.list(self: any): { Entry } return self.entries end --- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename --- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and --- macOS "__MACOSX/" / "._" files never match by basename. +-- lookup: exact, then case-insensitive, then by basename (never __MACOSX/ or ._ files); "\\" and "/" are the same function Archive.find(self: any, name: string): Entry? local n = normalize(name) local e = self._exact[n] @@ -116650,8 +115442,8 @@ local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) return out end --- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers --- get the local extra length wrong) +-- data offset candidates: the local header's lengths, then the central directory's (some writers get the local +-- extra length wrong) function Zip._starts(b: buffer, e: Entry): { number } local o = e.offset local starts = {} @@ -116668,7 +115460,6 @@ function Zip._starts(b: buffer, e: Entry): { number } return starts end --- read(entry | name, verify = true) -> buffer | nil, Err function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry if not e then @@ -116713,7 +115504,6 @@ function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buff return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) end --- readString(entry | name, verify?) -> string | nil, Err function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) local out, err = self:read(entry, verify) if not out then @@ -116722,7 +115512,6 @@ function Archive.readString(self: any, entry: Entry | string, verify: boolean?): return buffer.tostring(out), nil end --- ------------------------------------------------------------------------------------------------ write local Writer = {} Writer.__index = Writer @@ -116739,7 +115528,6 @@ type FinishOptions = { zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) } --- writer() -> Writer function Zip.writer(): any return setmetatable({ files = {} :: { any } }, Writer) end @@ -116786,7 +115574,6 @@ local function isAscii(s: string): boolean return string.find(s, "[\128-\255]") == nil end --- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) if type(name) ~= "string" or name == "" or #name > 65535 then return false, Err.new(Err.ARG, "add: bad entry name") @@ -116836,7 +115623,6 @@ function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boo return true, nil end --- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) local b = archive.buf local start: number? = nil @@ -116867,7 +115653,6 @@ function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (bo return true, nil end --- finish(opts?) -> the archive | nil, Err function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) local comment = opts and opts.comment or "" if #comment > 65535 then @@ -116985,19 +115770,14 @@ __FILES["core/Adler32"] = @native function() -- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; -- no third-party code). Never throws: the range is clamped. --- --- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it) --- Adler32.string(s, adler?) -> u32 local readu8 = buffer.readu8 --- Adler-32 of buf[off, off + len), continuing adler (default 1) @native local function adler32(buf: buffer, off: number, len: number, adler: number?): number local a0 = adler or 1 local a, b = a0 % 65536, a0 // 65536 local i, e = off, off + len while i < e do - -- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far - -- more, but keeping the sums small keeps them exact and cheap. + -- zlib NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32 local stop = math.min(e, i + 5552) while i < stop do a += readu8(buf, i) @@ -117010,7 +115790,6 @@ local readu8 = buffer.readu8 return b * 65536 + a end --- clamp (offset, length) to the buffer @native local function range(buf: buffer, offset: number?, length: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) @@ -117039,12 +115818,6 @@ __FILES["core/Base64"] = @native function() -- Used by tiled map data, glTF / SVG / CSS data: URIs, plist , YAML !!binary, FBX, the Brotli static tables. -- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a -- lone last character is an error. Never throws. --- --- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input) --- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length) --- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message" --- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg --- local uri = Base64.dataUri(buf, "image/png") local Base64 = {} type EncodeOptions = { @@ -117072,7 +115845,6 @@ buffer.writeu8(DEC, string.byte("="), 65) local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length) @native function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: number?, length: number?): string local buf: buffer = if type(data) == "string" then buffer.fromstring(data) else data local total = buffer.len(buf) @@ -117080,7 +115852,7 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 local n = math.clamp(length or (total - o), 0, total - o) local enc = if opts and opts.url then ENC_URL else ENC local pad = not (opts and opts.pad == false) - local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0 -- groups per line + local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0 local full = n // 3 local rest = n - full * 3 local textLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) @@ -117127,7 +115899,6 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return buffer.tostring(out) end --- decode(s) -> buffer | nil, message @native function Base64.decode(s: string | buffer): (buffer?, string?) local src: buffer = if type(s) == "string" then buffer.fromstring(s) else s local n = buffer.len(src) @@ -117164,8 +115935,7 @@ end return res, nil end --- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data --- when not base64) +-- RFC 2397: data:[][;params][;base64], (percent-encoded data when not base64) @native function Base64.decodeDataUri(uri: string): (buffer?, string?) if string.sub(uri, 1, 5) ~= "data:" then return nil, "not a data: URI" @@ -117194,7 +115964,6 @@ end return buffer.fromstring(decoded), mime end --- dataUri(buf, mime?) -> "data:;base64,..." @native function Base64.dataUri(buf: buffer | string, mime: string?): string return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) end @@ -117206,25 +115975,14 @@ __FILES["core/Bits"] = @native function() -- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data -- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. --- -- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. --- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see --- codecs/compress/Deflate/Inflate) and uses these for headers. --- -- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). --- --- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader --- local v = br:read(5); if br.err then return nil, br.err end --- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() --- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path --- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) local Err = __include("core/Err") local Bytes = __include("core/Bytes") local readu8, blen = buffer.readu8, buffer.len local floor = math.floor --- 2^n for n = 0..32 local POW = table.create(33, 0) for i = 0, 32 do POW[i + 1] = 2 ^ i @@ -117233,7 +115991,6 @@ end local Bits = {} Bits.POW = POW --- ------------------------------------------------------------------------------------------------ readers type BitReader = { buf: buffer, pos: number, -- next byte to load @@ -117312,14 +116069,12 @@ end end Lsb.read(self, n) end --- align(): drop the bits up to the next byte boundary @native function Lsb.align(self: any) local k = self.cnt % 8 if k > 0 then Lsb.read(self, k) end end --- bytePos(): the offset of the first byte not yet (even partly) consumed @native function Lsb.bytePos(self: any): number return self.pos - floor(self.cnt / 8) end @@ -117400,7 +116155,6 @@ Msb.bitsLeft = Lsb.bitsLeft return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any end --- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader @native function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader return reader(Lsb, buf, offset, length) end @@ -117408,7 +116162,6 @@ end return reader(Msb, buf, offset, length) end --- ------------------------------------------------------------------------------------------------ writers type BitWriter = { out: Bytes.Writer, -- the bytes so far (whole bytes only) acc: number, @@ -117438,7 +116191,6 @@ LsbW.__index = LsbW end self.acc, self.cnt = acc, cnt end --- align(): pad with zero bits to a byte boundary @native function LsbW.align(self: any) if self.cnt > 0 then self.out:u8(self.acc) @@ -117482,8 +116234,7 @@ end return self.out:finish() end --- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, --- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). +-- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } @native function Bits.msbPut(w: RawWriter, v: number, n: number) if n == 0 then @@ -117503,7 +116254,6 @@ type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } w.acc, w.cnt, w.pos = acc, cnt, p end --- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter @native function Bits.lsbWriter(capacity: number?): BitWriter return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any end @@ -117518,19 +116268,8 @@ __FILES["core/Bytes"] = @native function() -- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a -- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. --- -- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor --- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads: --- --- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length) --- local magic, w, h = r:string(4), r:u32be(), r:u32be() --- if r.err then return nil, r.err end --- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end --- --- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) --- w:string("abcd"); w:u32be(width); local out = w:finish() --- --- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads. local Err = __include("core/Err") local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 @@ -117544,7 +116283,6 @@ local scratch = bcreate(8) -- reinterpret casts for big-endian floats local Bytes = {} --- ------------------------------------------------------------------------------------------------ Reader local Reader = {} Reader.__index = Reader @@ -117559,7 +116297,6 @@ type Reader = typeof(setmetatable( Reader )) --- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer @native function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader local n = blen(buf) local o = math.clamp(offset or 0, 0, n) @@ -117567,7 +116304,6 @@ type Reader = typeof(setmetatable( return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) end --- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)` @native function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) if not self.err then self.err = Err.new(code, message, self.pos) @@ -117575,7 +116311,6 @@ end return nil, self.err :: Err.Err end --- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end @native function Reader.need(self: Reader, n: number): boolean if self.pos + n <= self.limit and n >= 0 then return true @@ -117600,7 +116335,6 @@ end return self.pos >= self.limit end --- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED @native function Reader.seek(self: Reader, offset: number): boolean if offset < 0 or self.base + offset > self.limit then self.pos = self.limit @@ -117621,7 +116355,6 @@ end return false end --- align(n): skip to the next multiple of n (relative to the reader's start) @native function Reader.align(self: Reader, n: number): boolean local r = (self.pos - self.base) % n if r == 0 then @@ -117630,7 +116363,6 @@ end return self:skip(n - r) end --- integers @native function Reader.u8(self: Reader): number local p = self.pos if p + 1 > self.limit then @@ -117729,7 +116461,6 @@ end local v = self:u32be() return if v >= 2147483648 then v - TWO32 else v end --- 64-bit integers as doubles (exact below 2^53) @native function Reader.u64le(self: Reader): number local lo = self:u32le() return lo + self:u32le() * TWO32 @@ -117747,7 +116478,6 @@ end return hi * TWO32 + self:u32be() end --- floats @native local function half(h: number): number local s = if h >= 32768 then -1 else 1 local e = bit32.band(bit32.rshift(h, 10), 31) @@ -117798,7 +116528,6 @@ end return readf64(scratch, 0) end --- strings @native function Reader.string(self: Reader, n: number): string local p = self.pos if n < 0 or p + n > self.limit then @@ -117809,14 +116538,12 @@ end return readstring(self.buf, p, n) end --- fixed(n): an n-byte field, cut at the first NUL @native function Reader.fixed(self: Reader, n: number): string local s = self:string(n) local z = string.find(s, "\0", 1, true) return if z then string.sub(s, 1, z - 1) else s end --- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED @native function Reader.cstring(self: Reader, max: number?): string local p = self.pos local e = if max then math.min(self.limit, p + max) else self.limit @@ -117834,7 +116561,6 @@ end return readstring(buf, p, q - p) end --- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error @native function Reader.match(self: Reader, s: string): boolean local p, n = self.pos, #s if p + n > self.limit or readstring(self.buf, p, n) ~= s then @@ -117844,7 +116570,6 @@ end return true end --- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error @native function Reader.peek(self: Reader, n: number, at: number?): string local p = self.pos + (at or 0) if p < self.base or p >= self.limit then @@ -117853,7 +116578,6 @@ end return readstring(self.buf, p, math.min(n, self.limit - p)) end --- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end @native function Reader.peekU8(self: Reader, at: number?): number local p = self.pos + (at or 0) if p < self.base or p >= self.limit then @@ -117862,7 +116586,6 @@ end return readu8(self.buf, p) end --- bytes(n) -> a new buffer with a copy of the next n bytes @native function Reader.bytes(self: Reader, n: number): buffer local p = self.pos if n < 0 or p + n > self.limit then @@ -117875,8 +116598,6 @@ end return b end --- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is --- left, and the parent records TRUNCATED. @native function Reader.slice(self: Reader, n: number): Reader local p = self.pos local l = math.max(0, math.min(n, self.limit - p)) @@ -117888,15 +116609,12 @@ end return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader) end --- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without --- moving the cursor @native function Reader.sub(self: Reader, offset: number, length: number?): Reader local o = math.clamp(self.base + offset, self.base, self.limit) local l = math.clamp(length or (self.limit - o), 0, self.limit - o) return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) end --- ------------------------------------------------------------------------------------------------ Writer local Writer = {} Writer.__index = Writer @@ -117908,12 +116626,10 @@ type Writer = typeof(setmetatable( Writer )) --- writer(capacity?) -> Writer @native function Bytes.writer(capacity: number?): Writer return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) end --- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf) @native function Writer.reserve(self: Writer, n: number): number local p = self.pos local cap = blen(self.buf) @@ -118009,12 +116725,10 @@ end writestring(self.buf, p, s) self.pos = p + n end --- cstring(s): s and a NUL @native function Writer.cstring(self: Writer, s: string) self:string(s) self:u8(0) end --- bytes(b, offset?, length?): copy a buffer range @native function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) local o = offset or 0 local n = length or (blen(b) - o) @@ -118028,7 +116742,6 @@ end self.pos = p + n end --- patch fields written earlier (lengths, CRCs) at an absolute offset < pos @native function Writer.setU32le(self: Writer, at: number, v: number) writeu32(self.buf, at, v) end @@ -118042,7 +116755,6 @@ end writeu8(self.buf, at, v) end --- finish() -> a buffer of exactly the written bytes (the writer can keep going) @native function Writer.finish(self: Writer): buffer local b = bcreate(self.pos) bcopy(b, 0, self.buf, 0, self.pos) @@ -118052,8 +116764,6 @@ end Bytes.Reader = Reader Bytes.Writer = Writer --- ------------------------------------------------------------------------------------------------ arguments --- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else @native function Bytes.toBuffer(v: any): buffer? if type(v) == "string" then return buffer.fromstring(v) @@ -118061,8 +116771,6 @@ Bytes.Writer = Writer return if type(v) == "buffer" then v else nil end --- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string, --- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end) @native function Bytes.span(what: string, input: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) local b = Bytes.toBuffer(input) if not b then @@ -118085,11 +116793,9 @@ end __FILES["core/Crc16"] = @native function() --- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code. --- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0, --- MacBinary II / III headers) --- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC) --- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer. +-- core/Crc16: the 16-bit CRCs old archive formats use, table driven. New code. ccitt: CRC-16/XMODEM (0x1021, MSB first, +-- init 0, no final XOR; BinHex 4.0, MacBinary II / III). arc: CRC-16/ARC (0x8005 reflected = 0xA001, init 0; LHA, Zoo, +-- ARC). Never throws: the range is clamped. local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift local readu8 = buffer.readu8 @@ -118140,14 +116846,7 @@ __FILES["core/Crc32"] = @native function() -- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. --- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; --- no third-party code). Never throws: the range is clamped. --- --- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) --- Crc32.string(s, crc?) -> u32 --- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no --- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF) --- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2) +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; no third-party code). Never throws. local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -118182,8 +116881,6 @@ for n = 0, 255 do T7[n + 1] = c end --- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion --- happens inside), so crc(b, crc(a)) == the CRC of a .. b. @native local function crc32(buf: buffer, off: number, len: number, crc: number?): number local c = bxor(crc or 0, 0xFFFFFFFF) local i, e = off, off + len @@ -118216,7 +116913,6 @@ end return bxor(c, 0xFFFFFFFF) end --- clamp (offset, length) to the buffer @native local function range(buf: buffer, offset: number?, length: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) @@ -118234,10 +116930,10 @@ end return crc32(buffer.fromstring(s), 0, #s, crc) end --- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) Crc32.raw = crc32 --- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks +-- MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected, raw register, no inversions): Ogg pages (init 0), +-- MPEG-2 PSI sections and bzip2 blocks (init 0xFFFFFFFF) local MSB = table.create(256, 0) for n = 0, 255 do local c = lshift(n, 24) @@ -118248,7 +116944,6 @@ for n = 0, 255 do end Crc32.MSB_TABLE = MSB --- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range) @native function Crc32.msb(buf: buffer, off: number, len: number, init: number?): number local c = init or 0 for i = off, off + len - 1 do @@ -118264,9 +116959,6 @@ __FILES["core/Err"] = function() -- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). -- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". -- Never throws: --!native modules may require it. --- --- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos) --- if err.code == Err.UNSUPPORTED then ... end local Err = {} -- codes @@ -118295,24 +116987,16 @@ Meta.__tostring = function(e: Err): string return s .. ": " .. e.message end --- new(code, message, offset?) -> Err function Err.new(code: string, message: string, offset: number?): Err return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any end --- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) local KIND: { [string]: string } = {} for _, c in { "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" } do KIND[c] = c KIND[string.lower(c)] = c end --- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns --- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the --- message decides: a ": ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; --- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; --- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes --- through unchanged. function Err.from(message: any, offset: number?, kind: string?): Err if Err.is(message) then return message @@ -118336,13 +117020,10 @@ function Err.from(message: any, offset: number?, kind: string?): Err return Err.new(code :: string, msg, offset) end --- is(v) -> true when v is an Err function Err.is(v: any): boolean return type(v) == "table" and getmetatable(v) == Meta end --- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to --- tag errors with the format name. function Err.wrap(e: any, format: string?): Err if not Err.is(e) then e = Err.new(Err.CORRUPT, tostring(e)) @@ -118359,9 +117040,6 @@ __FILES["core/Input"] = function() -- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files -- through the host adapter the API passes in (core never requires host itself). --- --- local buf, err, name = Input.resolve(src, opts, host) --- -- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path -- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). -- name: the path (for the extension fallback) or opts.name. Never throws. @@ -118375,12 +117053,10 @@ type HostLike = { exists: (path: string) -> boolean, } --- looksLikePath(s) -> true for short strings without NUL / newline bytes function Input.looksLikePath(s: string): boolean return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") end --- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?) local o = opts or {} local t = type(src) @@ -118408,7 +117084,6 @@ function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil end --- extension(name) -> the lower-case extension without the dot ("png"), or nil function Input.extension(name: string?): string? if not name then return nil @@ -118417,8 +117092,6 @@ function Input.extension(name: string?): string? return if ext then string.lower(ext) else nil end --- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive --- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) function Input.sibling(opts: any?, uri: string): buffer? if type(opts) ~= "table" then return nil @@ -118445,11 +117118,6 @@ __FILES["core/Md5"] = @native function() -- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); -- not for security. --- --- local h = Md5.new() --- h:update(buf, offset?, length?) -- any number of times --- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) --- Md5.hex(digest) / Md5.of(buf) -> hex string -- Never throws (ranges are clamped to the buffer). local Md5 = {} @@ -118587,7 +117255,6 @@ end } end --- hex(digest) -> 32 lower-case hex digits @native function Md5.hex(d: string): string local out = table.create(#d) for i = 1, #d do @@ -118596,7 +117263,6 @@ end return table.concat(out) end --- of(buf, offset?, length?) -> hex digest @native function Md5.of(buf: buffer, offset: number?, length: number?): string local h = Md5.new() h:update(buf, offset, length) @@ -118609,27 +117275,18 @@ __FILES["core/Sniff"] = function() -- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and -- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. --- --- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 --- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score --- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped --- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too --- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file local Sniff = {} type Peeker = { peek: (any, number, number?) -> string } --- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 function Sniff.magic(r: Peeker, s: string, at: number?, score: number?): number return if r:peek(#s, at) == s then score or 1 else 0 end --- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) function Sniff.dropBom(s: string): string return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s end --- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) function Sniff.text(r: Peeker, n: number, trim: boolean?): string local s = r:peek(n) if string.sub(s, 1, 3) == "\239\187\191" then @@ -118645,12 +117302,9 @@ return Sniff end __FILES["data/cbor"] = function() --- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / --- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, --- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), --- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences --- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, --- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. +-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double +-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences +-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -118668,11 +117322,11 @@ local Cbor = { } type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item) + all: boolean?, -- default false } type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of items, written as a sequence - selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7) + all: boolean?, + selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7) } -- ------------------------------------------------------------------------------------------------ sniff @@ -118737,9 +117391,9 @@ function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.tagged = Codec.tagged Cbor.isTagged = Codec.isTagged -Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.simple = Codec.simple Cbor.isSimple = Codec.isSimple Cbor.undefined = Codec.undefined @@ -118748,8 +117402,7 @@ end __FILES["data/cbor/Codec"] = @native function() --- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, --- message, offset. +-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -118764,14 +117417,13 @@ end } local SimpleMeta = { __tostring = @native function(s: any): string return "cbor.simple(" .. s.value .. ")" end } --- tagged(tag, value) -> { tag, value }: a tag this library does not interpret @native function Codec.tagged(tag: number, value: any): { tag: number, value: any } return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any end @native function Codec.isTagged(v: any): boolean return type(v) == "table" and getmetatable(v) == TaggedMeta end --- simple(n) -> an unassigned simple value (0..19, 32..255) +-- unassigned simple values: 0..19, 32..255 @native function Codec.simple(n: number): { value: number } return setmetatable({ value = n }, SimpleMeta) :: any end @@ -118782,7 +117434,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = @native function( return "undefined" end })) --- decimal text of a big-endian unsigned byte string (any length) @native local function bigText(s: string): string local limbs = {} -- base 1e7, little-endian for i = 1, #s do @@ -118806,7 +117457,6 @@ end })) end return table.concat(out) end --- text + 1 for a decimal string @native local function incText(s: string): string local digits: { number } = table.create(#s) :: { number } for i = 1, #s do @@ -118829,18 +117479,18 @@ end end type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text - null: any?, -- the value for null (default Types.null) - undefined: any?, -- the value for undefined (default Codec.undefined) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + undefined: any?, -- default Codec.undefined maxDepth: number?, -- default 512 - dates: boolean?, -- tags 0 / 1 as Types.Date (default true) + dates: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } -local BREAK = {} -- the 0xFF stop code, inside indefinite items +local BREAK = {} -- 0xFF break stop code --- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +-- additional information 31: indefinite length @native local function arg(st: St, ai: number): (number?, string?, string?) local r = st.r if ai < 24 then @@ -118917,7 +117567,7 @@ local half = Bytes.half n = n * 256 + string.byte(s, i) end if n >= 9007199254740992 then - -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + -- read back from the exact text: correctly rounded, unlike the running sum local text = bigText(s) if t == 3 then text = incText(text) @@ -119095,7 +117745,6 @@ end if v == BREAK then return nil, "unexpected break" end - -- bignum content arrives as a buffer: hand the tag its bytes if (n == 2 or n == 3) and type(v) == "buffer" then return tag(st, n, buffer.tostring(v)) end @@ -119103,7 +117752,6 @@ end end end --- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) @native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -119126,10 +117774,10 @@ end -- ------------------------------------------------------------------------------------------------ encode type EncodeOptions = { - compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") - dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds + compactFloats: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" + dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds maxDepth: number?, -- default 512 (also catches cycles) } @@ -119158,7 +117806,6 @@ type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean end end --- the half-float bits of x when x is exactly representable, else nil @native local function toHalf(x: number): number? if x ~= x then return 0x7E00 @@ -119171,7 +117818,7 @@ end if a == 0 then return sign end - local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local m, e = math.frexp(a) local exp = e - 1 + 15 if exp >= 31 then return nil @@ -119302,7 +117949,6 @@ local scratch = buffer.create(8) return true end --- encode(v, opts) -> buffer | nil, message @native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { @@ -119324,12 +117970,9 @@ return Codec end __FILES["data/csv"] = function() --- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any --- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded --- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column --- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only --- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters --- other than the doubled quote, multi-byte delimiters. +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or +-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode +-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -119349,19 +117992,19 @@ local Csv = { } type DecodeOptions = { - delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) - quote: string?, -- the quote byte (default '"') - header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) - numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) - maxRows: number?, -- refuse more rows (default unlimited) + delimiter: string?, -- default ","; "auto": one of , ; tab | + quote: string?, -- default '"' + header: boolean?, -- default false + numbers: boolean?, -- default false + maxRows: number?, -- default unlimited } type EncodeOptions = { delimiter: string?, -- default "," quote: string?, -- default '"' - newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) - quoteAll: boolean?, -- quote every field (default false: only those that need it) - columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) - header: boolean?, -- keyed rows: write the header row (default true) + newline: string?, -- default "\r\n" (RFC 4180) + quoteAll: boolean?, -- default false + columns: { string }?, -- default: keys in first-seen order + header: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -119405,7 +118048,6 @@ local function guess(s: string, q: string): string return best end --- rows(s, opts) -> { { string } } | nil, Err function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local o: DecodeOptions = opts or {} local q = o.quote or '"' @@ -119423,7 +118065,7 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local row: { string } = {} local n = #s local i = 1 - local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + local rowEmpty = true while true do local c = byte(s, i) local field: string @@ -119466,7 +118108,6 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) rowEmpty = false i += 1 else - -- end of the row: CRLF / LF / CR / end of data if c == 13 and byte(s, i + 1) == 10 then i += 2 elseif c ~= nil then @@ -119641,13 +118282,9 @@ return Csv end __FILES["data/ini"] = function() --- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. --- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, --- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at --- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a --- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level --- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested --- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. +-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports: +-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline +-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -119667,10 +118304,10 @@ local Ini = { } type DecodeOptions = { - inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser) - allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error) - types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans - strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge) + inlineComments: boolean?, -- default false (configparser) + allowNoValue: boolean?, -- default false + types: boolean?, + strict: boolean?, -- default false } type EncodeOptions = { delimiter: string?, -- default " = " @@ -119734,9 +118371,8 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if trimmed == "" then lastKey = nil elseif string.match(trimmed, "^[;#]") then - -- a comment line (configparser: also when indented); it does not end a continuation + -- configparser: comment lines may be indented and do not end a continuation elseif lastKey and indent > lastIndent then - -- continuation of the previous value local v = trimmed if o.inlineComments then v = string.match(v, "^(.-)%s+[;#]") or v @@ -119892,9 +118528,8 @@ return Ini end __FILES["data/json"] = function() --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). --- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON +-- Lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -119913,10 +118548,10 @@ local JsonFormat = { } type DecodeOptions = Json.DecodeOptions & { - lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value) + lines: boolean?, -- default false } type EncodeOptions = Json.EncodeOptions & { - lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line + lines: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -119985,11 +118620,9 @@ return JsonFormat end __FILES["data/msgpack"] = function() --- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the --- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as --- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a --- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for --- non-integers unless opts.float32). Not supported: nothing in the spec. +-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as +-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the +-- smallest forms. Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120007,10 +118640,10 @@ local Msgpack = { } type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- decode every concatenated value into an array (default false: exactly one value) + all: boolean?, -- default false } type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of values, written one after another + all: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -120069,7 +118702,6 @@ function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) Msgpack.ext = Codec.ext Msgpack.isExt = Codec.isExt @@ -120078,8 +118710,7 @@ end __FILES["data/msgpack/Codec"] = @native function() --- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with --- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -120087,7 +118718,7 @@ local Codec = {} local TWO32 = 4294967296 --- an extension value: { type = -128..127, data = buffer } +-- ext type: -128..127 local ExtMeta = { __tostring = @native function(e: any): string return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" end } @@ -120098,13 +118729,11 @@ end return type(v) == "table" and getmetatable(v) == ExtMeta end --- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact @native local function u64text(hi: number, lo: number): string if hi == 0 then return string.format("%d", lo) end local digits = {} - -- long division by 10 on four 16-bit limbs local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do local rem = 0 @@ -120120,11 +118749,11 @@ end Codec.u64text = u64text type DecodeOptions = { - bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text - null: any?, -- the value for nil (default Types.null) - maxDepth: number?, -- nesting limit (default 512) - timestamps: boolean?, -- ext -1 as a Types.Date (default true) - ordered: boolean?, -- maps as Types.object with key order (default true) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + maxDepth: number?, -- default 512 + timestamps: boolean?, -- default true + ordered: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } @@ -120133,7 +118762,6 @@ type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: bool local r = st.r local hi, lo = r:u32be(), r:u32be() if signed and hi >= 0x80000000 then - -- negative: two's complement local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo if nlo == TWO32 then nlo = 0 @@ -120317,7 +118945,6 @@ end return nil, string.format("reserved type byte 0x%02x", b) end --- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) @native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -120337,11 +118964,11 @@ end -- ------------------------------------------------------------------------------------------------ encode type EncodeOptions = { - float32: boolean?, -- non-integer numbers as float32 (default false: float64) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + float32: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" maxDepth: number?, -- default 512 (also catches cycles) - stringsAsBin: boolean?, -- strings as bin (default false: str) + stringsAsBin: boolean?, -- default false } type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } @@ -120503,7 +119130,6 @@ Codec.isArray = isArray return true end --- encode(v, opts) -> buffer | nil, message @native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { @@ -120525,12 +119151,9 @@ return Codec end __FILES["data/nbt"] = function() --- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and --- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and --- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / --- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression --- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. --- Not supported: nothing in the format. +-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT +-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info). +-- Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120580,18 +119203,16 @@ function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.info = Nbt.info NbtFormat.Nbt = Nbt return NbtFormat end __FILES["data/plist"] = function() --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is --- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> --- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> --- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past --- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . +-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib), +-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral +-- reals write back as . -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120613,11 +119234,11 @@ local Plist = { } type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + bigInts: ("number" | "string")?, maxDepth: number?, -- default 512 } type EncodeOptions = { - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + sortKeys: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -120888,7 +119509,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.uid = Binary.uid Plist.isUid = Binary.isUid return Plist @@ -120896,11 +119517,7 @@ end __FILES["data/plist/Binary"] = @native function() --- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in --- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte --- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, --- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles --- are errors. Never throws: errors return nil, message. +-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. local Types = __include("Types") local Binary = {} @@ -120940,7 +119557,6 @@ end type Options = { bigInts: ("number" | "string")?, maxDepth: number? } --- decode(buf, base, len, opts) -> value | nil, message @native function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) if len < 40 then return nil, "truncated: shorter than header + trailer" @@ -121026,7 +119642,6 @@ type Options = { bigInts: ("number" | "string")?, maxDepth: number? } if h >= 0x80000000 and nib == 3 then v = (h - TWO32) * TWO32 + l elseif opts and opts.bigInts == "string" and h >= 0x200000 then - -- exact decimal text of h * 2^32 + l local digits = {} local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do @@ -121168,9 +119783,7 @@ return Binary end __FILES["data/snbt"] = function() --- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over --- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt --- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. -- Not supported: the 1.21.5 bool(...) / uuid(...) operations. -- ------------------------------------------------------------------------------------------------ requires @@ -121191,8 +119804,8 @@ local SnbtFormat = { type DecodeOptions = { maxDepth: number? } type EncodeOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- '"' (default) or "'" + indent: (number | string)?, -- default: compact + quote: string?, -- default '"' } -- ------------------------------------------------------------------------------------------------ sniff @@ -121233,13 +119846,9 @@ return SnbtFormat end __FILES["data/toml"] = function() --- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, --- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range --- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules --- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / --- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to --- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral --- values are written as integers). +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0 +-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer / +-- float distinction (integral values write as integers). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -121261,8 +119870,7 @@ type DecodeOptions = Decode.Options type EncodeOptions = Encode.Options -- ------------------------------------------------------------------------------------------------ sniff --- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, --- so this stays low and the extension decides +-- INI looks the same: a [table] or key = value start scores low and the extension decides function Toml.sniff(r: Bytes.Reader): number local head = r:peek(512) if string.find(head, "%z") then @@ -121305,10 +119913,7 @@ return Toml end __FILES["data/toml/Decode"] = function() --- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with --- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control --- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and --- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset). local Text = __include("codecs/text/Text") local Types = __include("Types") @@ -121317,7 +119922,7 @@ local Decode = {} local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char type Options = { - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") + bigInts: ("number" | "string")?, -- default "number" } local utf8char = Text.utf8char @@ -121338,7 +119943,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return nil end - -- input checks: BOM, UTF-8, control characters, bare CR if sub(s, 1, 3) == "\239\187\191" then s = sub(s, 4) end @@ -121386,7 +119990,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) local function ws(i: number): number return match(s, "^[ \t]*()", i) :: any end - -- whitespace, newlines and comments (inside arrays) local function wsnl(i: number): number while true do i = match(s, "^[ \t\n]*()", i) :: any @@ -121420,7 +120023,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return fail("bad escape", p) end - -- strings: value, next | nil local function basic(i: number): (string?, number) local parts = {} local j = i + 1 @@ -121510,7 +120112,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return sub(s, j, e - 1) .. string.rep("'", extra), q end - -- a (dotted) key: { parts }, next | nil local function key(i: number): ({ string }?, number) local keys: { string } = {} while true do @@ -121548,7 +120149,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end end - -- numbers and datetimes local function number(i: number): (any, number) local tok = match(s, "^[%+%-]?[%w_%.]+", i) if not tok then @@ -121862,7 +120462,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end ni += 1 end - -- walk to the parent local t = root for j = 1, #keys - 1 do local k = keys[j] @@ -121942,11 +120541,7 @@ return Decode end __FILES["data/toml/Encode"] = function() --- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables --- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as --- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date --- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, --- message. +-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws. local Types = __include("Types") local Json = __include("codecs/text/Json") @@ -121955,8 +120550,8 @@ local Encode = {} local format, gsub, find = string.format, string.gsub, string.find type Options = { - inline: boolean?, -- write every sub-table as an inline table (default false: [sections]) - indent: (number | string)?, -- indent keys of nested sections (default none) + inline: boolean?, -- default false + indent: (number | string)?, -- default none } local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } @@ -121979,7 +120574,6 @@ local function keyText(k: string): string return quote(k) end --- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays local function isMap(t: { [any]: any }): boolean if Types.isObject(t) then return true @@ -121999,7 +120593,6 @@ local function isDate(v: any): boolean return Types.Date.is(v) end --- an array of tables: non-empty, every element a map local function isAot(v: any): boolean if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then return false @@ -122139,7 +120732,6 @@ local function section(st: State, t: any, path: string, out: { string }, inlineA return true end --- encode(t, opts) -> text | nil, message function Encode.encode(t: any, opts: Options?): (string?, string?) if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then return nil, "the top level must be a table with string keys" @@ -122158,9 +120750,8 @@ return Encode end __FILES["data/xml"] = function() --- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: --- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not --- supported: external entities / DTDs, validation. +-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an +-- element. Not supported: external entities / DTDs, validation. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -122215,13 +120806,9 @@ return XmlFormat end __FILES["data/yaml"] = function() --- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / --- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as --- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null --- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. --- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). --- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; --- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases +-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style. +-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -122263,7 +120850,6 @@ function Yaml.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local text = buffer.readstring(r.buf, r.base, r.limit - r.base) local docs, code, msg, at = Parse.run(text, opts) @@ -122281,7 +120867,6 @@ function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local s, err = Emit.encode(value, opts) if not s then @@ -122294,11 +120879,7 @@ return Yaml end __FILES["data/yaml/Emit"] = function() --- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when --- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars --- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as --- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad --- values (cycles, functions, collection keys) return nil, message. +-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools). local Types = __include("Types") local Base64 = __include("core/Base64") local Parse = __include("data/yaml/Parse") @@ -122306,11 +120887,11 @@ local Parse = __include("data/yaml/Parse") local Emit = {} type Options = { - indent: number?, -- spaces per level (default 2) - all: boolean?, -- the value is an array of documents, written with "---" separators - explicitStart: boolean?, -- start the (first) document with "---" (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order) - null: any?, -- the value written as null besides Types.null + indent: number?, -- default 2 + all: boolean?, + explicitStart: boolean?, -- default false + sortKeys: boolean?, -- default true + null: any?, } local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub @@ -122391,7 +120972,6 @@ local function plainOk(s: string): boolean return true end --- a string as a scalar on a line at indentation ind (for block scalars) local function str(s: string, ind: string, key: boolean): string if plainOk(s) then return s @@ -122421,7 +121001,6 @@ local keyLess = Types.keyLess type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } --- count references to tables (anchors for those seen twice); false on a cycle local function count(st: St, v: any, onStack: { [any]: boolean }): boolean if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then return true @@ -122445,7 +121024,6 @@ local function count(st: St, v: any, onStack: { [any]: boolean }): boolean return true end --- scalar text for a non-collection value, or nil local function scalar(st: St, v: any, ind: string, key: boolean): string? local tv = type(v) if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then @@ -122466,7 +121044,6 @@ end local write: (st: St, v: any, depth: number) -> string? --- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) function write(st: St, v: any, depth: number): string? local ind = string.rep(" ", st.step * (depth + 1)) local s = scalar(st, v, ind, false) @@ -122539,19 +121116,16 @@ local function document(st: St, v: any): string? if not t then return nil end - -- the top level: drop the separator write() put before the first line if string.sub(t, 1, 1) == "\n" then return string.sub(t, 2) end local body = string.sub(t, 2) if string.sub(body, 1, 1) == "&" then - -- "&id001\n- a": an anchored top-level collection return body end return body end --- encode(v, opts) -> text | nil, message function Emit.encode(v: any, opts: Options?): (string?, string?) local o: Options = opts or {} local st: St = { @@ -122595,13 +121169,7 @@ return Emit end __FILES["data/yaml/Parse"] = function() --- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): --- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with --- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared --- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless --- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core --- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a --- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it. local Text = __include("codecs/text/Text") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -122611,11 +121179,11 @@ local Parse = {} local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char type Options = { - all: boolean?, -- every document as an array (default false: the first document; none -> Types.null) - tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged - maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard - maxDepth: number?, -- nesting limit (default 500) - null: any?, -- the value for null (default Types.null) + all: boolean?, -- default false + tags: ("error" | "ignore")?, -- default "error" + maxAliasNodes: number?, -- default 1e6 (billion laughs guard) + maxDepth: number?, -- default 500 + null: any?, -- default Types.null } type St = { @@ -122650,7 +121218,7 @@ local function col(s: string, p: number): number return p - q end -local function isWsEnd(c: number?): boolean -- space, tab, newline or the end +local function isWsEnd(c: number?): boolean return c == nil or c == 32 or c == 9 or c == 10 end @@ -122662,7 +121230,6 @@ local function docMarker(s: string, p: number): boolean return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) end --- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) local function skip(s: string, p: number): number local n = #s while p <= n do @@ -122682,7 +121249,6 @@ local function skip(s: string, p: number): number return p end --- the number of leading spaces on p's line, and whether a tab comes before p on it local function lineIndent(s: string, p: number): (number, boolean) local q = p while q > 1 and byte(s, q - 1) ~= 10 do @@ -122701,7 +121267,6 @@ local function noTabs(s: string, p: number, ind: number?) end end --- skip spaces / tabs on the line local function skipLine(s: string, p: number): number return match(s, "^[ \t]*()", p) :: any end @@ -122716,7 +121281,6 @@ end local utf8char = Text.utf8char -- ------------------------------------------------------------------------------------------------ resolution --- the core schema: a plain scalar's value function Parse.resolve(t: string, nullv: any): any if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then return nullv @@ -122764,7 +121328,6 @@ local function base64(t: string): buffer? return (Base64.decode(t)) end --- a scalar's value given its tag (nil = untagged, "!" = non-specific) local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any if tag == nil then return if plain then Parse.resolve(raw, st.null) else raw @@ -122833,7 +121396,6 @@ local function collectionTag(st: St, tag: string?, kind: string, p: number) end end --- expansion size of a value (nodes), memoized local function size(st: St, v: any): number if type(v) ~= "table" or v == st.null then return 1 @@ -122853,7 +121415,6 @@ end -- ------------------------------------------------------------------------------------------------ properties type Props = { anchor: string?, tag: string?, at: number } --- anchors / tags at p -> props?, the position after them (and the spaces after them) local function properties(st: St, p: number): (Props?, number) local s = st.s local props: Props? = nil @@ -122944,8 +121505,7 @@ local function alias(st: St, p: number): (any, number) end -- ------------------------------------------------------------------------------------------------ scalars --- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. --- Lines holding only spaces / tabs count as empty. +-- line folding: lines holding only spaces / tabs count as empty local function fold(s: string, p: number): (string, number) local empties = 0 local q = p + 1 @@ -122981,7 +121541,6 @@ local ESC: { [number]: string } = { [80] = "\226\128\169", } --- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote local function quoted(st: St, p: number, ind: number): (string, number) local s = st.s local dq = byte(s, p) == 34 @@ -123052,15 +121611,13 @@ local function quoted(st: St, p: number, ind: number): (string, number) end end --- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind --- (block context); flow: the flow-context rules (stops at , [ ] { }). +-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { } local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) local s = st.s local parts: { string } = {} local i = p local lastEnd = p while true do - -- one line's worth local j = i local stopAt = nil while true do @@ -123088,7 +121645,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu if stopAt or byte(s, j) == nil then return table.concat(parts), lastEnd end - -- a continuation line? local f, q = fold(s, j) local r = skipLine(s, q) local c = byte(s, r) @@ -123103,7 +121659,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu end end --- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it local function blockScalar(st: St, p: number, ind: number): (string, number) local s = st.s local folded = byte(s, p) == 62 @@ -123125,7 +121680,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) end local nl = find(s, "\n", q, true) local lines: { string } = {} - local trailing = 0 -- empty lines after the last content line + local trailing = 0 if not nl then return "", #s + 1 end @@ -123164,7 +121719,6 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) indent = ind + 1 end end - -- the lines local r = ls local pendingEmpty = 0 local endPos = ls @@ -123221,7 +121775,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) empties = 0 end end - trailing += empties -- empty lines after the last content line (or all of them) + trailing += empties body = table.concat(out) end if not folded then @@ -123262,7 +121816,6 @@ local function enter(st: St, p: number) end end --- a flow node at p (after skip) -> value, next, wasEmpty local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local s = st.s local props, q = properties(st, p) @@ -123284,7 +121837,6 @@ local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local t, r = quoted(st, q, ind) return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then - -- an empty node return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then corrupt("unexpected character in a flow collection", q) @@ -123415,7 +121967,7 @@ end -- ------------------------------------------------------------------------------------------------ block local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) --- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +-- implicit key: on one line, followed by ':' and a space or the end of the line local function implicitKey(st: St, p: number): (any, number?) local s = st.s local c = byte(s, p) @@ -123443,7 +121995,6 @@ local function implicitKey(st: St, p: number): (any, number?) end return nil, nil elseif c == 91 or c == 123 then - -- a flow collection used as a key? local e = find(s, "\n", p, true) or #s + 1 local line = sub(s, p, e - 1) if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then @@ -123488,7 +122039,7 @@ local function readKey(st: St, p: number, props: Props?): (any, number) end k, q = alias(st, p) q = skipLine(s, q) - q += 1 -- the ':' + q += 1 elseif c == 34 or c == 39 then local t, r = quoted(st, p, -1) if find(sub(s, p, r - 1), "\n", 1, true) then @@ -123508,7 +122059,6 @@ local function readKey(st: St, p: number, props: Props?): (any, number) return checkKey(st, k, p), q end --- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) local s = st.s local r = skip(s, p) @@ -123522,7 +122072,6 @@ local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapP return st.null, p end --- the value after a ':' (at p, just past it) of a mapping at column mc local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) local s = st.s local r = skipLine(s, p) @@ -123640,7 +122189,6 @@ local function blockSeq(st: St, sc: number, p: number): (any, number) return t, q end --- the node at q after its properties (props may be nil); start = where the properties began local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) local s = st.s local tag = props and props.tag @@ -123707,9 +122255,6 @@ local function afterProps(st: St, ind: number, start: number, q: number, props: return finish(st, props, scalarValue(st, text, true, tag, q)), e end --- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the --- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's --- indentation may follow properties that end their line. function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) local s = st.s local props, q = properties(st, p) @@ -123849,7 +122394,6 @@ local function stream(st: St): { any } p = q else if explicit and not find(sub(s, p, q), "\n", 1, true) then - -- content on the "---" line local ok, _, q2 = pcall(properties, st, q) local c = byte(s, q2) if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then @@ -123878,7 +122422,6 @@ local function stream(st: St): { any } return docs end --- run(text, opts) -> docs | nil, code, message, offset function Parse.run(text: string, opts: Options?): (any, any, any, any) local o: Options = opts or {} local s = text @@ -123919,15 +122462,9 @@ return Parse end __FILES["font/bdf"] = function() --- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the --- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in --- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), --- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to --- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for --- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and --- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font --- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. --- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1 +-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes +-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -123947,9 +122484,9 @@ local Bdf = { type DecodeOptions = { maxGlyphs: number? } -- default 1114112 type EncodeOptions = { - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - name: string?, -- the FONT (XLFD) name (default built from the font's family / style) + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + name: string?, -- XLFD; default built from the family / style } -- ------------------------------------------------------------------------------------------------ sniff @@ -124143,7 +122680,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil local px = strike.size - -- the font bounding box local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, g in strike.glyphs do if g.width > 0 and g.height > 0 then @@ -124164,7 +122700,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) string.format("SIZE %d 75 75", px), string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), } - -- the default glyph: the strike's default, else glyph 0 local defaultIndex = (strike.default or 0) + 1 local props: { { any } } = { { "FAMILY_NAME", quote(family) }, @@ -124216,13 +122751,9 @@ return Bdf end __FILES["font/bmfont"] = function() --- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and --- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize --- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are --- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the --- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / --- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. --- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). +-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont +-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. +-- Not supported: packed multi-channel glyphs (read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -124241,25 +122772,24 @@ local Bmfont = { } type DecodeOptions = { - pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) - loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) + pages: { Types.Image }?, -- page id 0 first + loadPage: ((file: string, page: number) -> any)?, } type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" - px: number?, -- fonts without a BMFont description are baked first (see bake) + px: number?, chars: (string | { number })?, - file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") - name: string?, -- the destination's file name (set by the api) - files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes - -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages + file: string?, -- default: opts.name without its extension, else "font" + name: string?, + files: { [string]: any }?, encodeImage: ((img: any, format: string) -> (buffer?, any))?, } type BakeOptions = { - px: number?, -- pixels per em (default 32) - chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) - pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) - padding: number?, -- empty pixels around each glyph (default 1) - file: string?, -- page file name prefix (default "font"): pages are _.png + px: number?, -- default 32 + chars: (string | { number })?, -- default printable ASCII 32..126 + pageSize: number?, -- default: the smallest power of two that fits, up to 4096 + padding: number?, -- default 1 + file: string?, -- default "font"; pages are _.png } -- ------------------------------------------------------------------------------------------------ sniff @@ -124278,7 +122808,6 @@ function Bmfont.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the Font value local Face = {} Face.__index = Face @@ -124297,10 +122826,9 @@ function Face.kern(self: any, a: number, b: number): number return self._kern[ca.id * 2097152 + cb.id] or 0 end function Face.outline(_self: any, _g: number): { any }? - return nil -- bitmap font + return nil end --- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) local load = loader or self.meta.pageLoader if type(load) ~= "function" then @@ -124320,8 +122848,6 @@ end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 --- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; --- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. function Face.rasterize(self: any, g: number, px: number?): Types.Image? local c = self._chars[g] if not c then @@ -124358,7 +122884,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? return img end --- the Font value of a description local function face(d: Parse.Desc, variant: string): any local f: any = setmetatable({ kind = "font", @@ -124461,7 +122986,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local d = type(font.meta) == "table" and font.meta.bmfont or nil local pages = font.pages if d == nil then - -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") @@ -124479,7 +123003,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end - -- the page images into opts.files, under the names the descriptor gives them local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then @@ -124527,9 +123050,6 @@ local function codepoints(chars: any): { number } return out end --- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are --- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are --- kept (rounded to pixels). function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") @@ -124658,12 +123178,7 @@ return Bmfont end __FILES["font/bmfont/Parse"] = function() --- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one --- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation --- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the --- descriptor has no nesting that matters, no text content). --- --- Never throws on bad input: parse functions return nil, message. +-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html). local Bytes = __include("core/Bytes") local Parse = {} @@ -124683,12 +123198,12 @@ type Char = { type Desc = { info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl - pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1]) + pages: { string }, -- by page id: page id 0 is pages[1] chars: { Char }, kernings: { { number } }, -- { first, second, amount } } -local LIMIT = 1000000 -- chars / kernings +local LIMIT = 1000000 local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } @@ -124713,7 +123228,6 @@ local function new(): Desc return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } end --- one tag's attributes (already split into key -> string) into the description local function apply(d: Desc, tag: string, a: { [string]: string }): string? if tag == "info" then d.info.face = a.face or "" @@ -125117,12 +123631,9 @@ return Parse end __FILES["font/eot"] = function() --- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, --- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and --- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot --- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, --- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C --- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. +-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header +-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes. +-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -125142,8 +123653,8 @@ local Eot = { type DecodeOptions = {} type EncodeOptions = { - xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false) - rootString: string?, -- the URLs allowed to use the font (default "") + xor: boolean?, -- XOR 0x50; default false + rootString: string?, -- default "" } -- ------------------------------------------------------------------------------------------------ constants @@ -125352,12 +123863,8 @@ return Eot end __FILES["font/fon"] = function() --- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the --- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE --- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first --- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI --- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). --- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as +-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252. -- Not supported: vector FNT (Err.UNSUPPORTED), writing. -- ------------------------------------------------------------------------------------------------ requires @@ -125377,7 +123884,7 @@ local Fon = { caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, } -type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first) +type DecodeOptions = { size: number? } -- default: the first strike -- ------------------------------------------------------------------------------------------------ sniff local function isFnt(h: string): boolean @@ -125403,7 +123910,6 @@ function Fon.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one FNT resource -> Font local function fnt(r: Bytes.Reader): (any, Err.Err?) local version = r:u16le() local total = r:u32le() @@ -125498,7 +124004,6 @@ local function fnt(r: Bytes.Reader): (any, Err.Err?) }), nil end --- the RT_FONT resources of an NE executable: { { offset, length } } local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) local rt = r:sub(ne + 0x24, 2):u16le() local t = r:sub(ne + rt) @@ -125528,7 +124033,7 @@ local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) return out, nil end --- the RT_FONT (8) resources of a PE executable: { { offset, length } } +-- RT_FONT: resource type 8 local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) local h = r:sub(pe + 4, 20) h:skip(2) @@ -125543,7 +124048,6 @@ local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) if opt.err or rsrcRva == 0 then return {}, nil end - -- the section holding the resources local secs = r:sub(pe + 24 + optSize, nsec * 40) local base, rva0 = -1, 0 for _ = 1, nsec do @@ -125642,15 +124146,9 @@ return Fon end __FILES["font/hershey"] = function() --- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph --- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", --- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths --- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster --- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of --- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i --- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph --- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: --- writing, the Hershey "occidental" index files (.hmp), filled rendering. +-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character +-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up. +-- Not supported: writing, .hmp index files, filled rendering. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -125669,8 +124167,8 @@ local Hershey = { } type DecodeOptions = { - map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii") - strokeWidth: number?, -- stroke width in font units for rasterize (default 2) + map: ("ascii" | "id")?, -- default "ascii" + strokeWidth: number?, -- font units; default 2 maxGlyphs: number?, -- default 65536 } @@ -125736,7 +124234,6 @@ function Face.outline(self: any, g: number): { any }? return out end --- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) function Face.rasterize(self: any, g: number, px: number): Types.Image? local gl = self._glyphs[g + 1] if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then @@ -125844,13 +124341,8 @@ return Hershey end __FILES["font/pcf"] = function() --- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the --- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), --- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad --- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. --- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets --- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver --- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. +-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver +-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -125883,7 +124375,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Table = { format: number, size: number, offset: number } --- a reader positioned after a table's format word, with the integer readers for its byte order type TR = { r: Bytes.Reader, format: number, big: boolean } local function open(r: Bytes.Reader, t: Table?): TR? @@ -125936,7 +124427,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- properties local props: { [string]: any } = {} local pt = open(r, tables[PROPERTIES]) if pt then @@ -125967,14 +124457,12 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) return nil, Err.new(Err.TRUNCATED, "properties table") end end - -- accelerators: ascent / descent local ascent: number?, descent: number? = nil, nil local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) if at then at.r:skip(8) ascent, descent = i32(at), i32(at) end - -- metrics local mt = open(r, tables[METRICS]) if not mt then return nil, Err.new(Err.CORRUPT, "no METRICS table") @@ -125997,7 +124485,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if mt.r.err then return nil, Err.new(Err.TRUNCATED, "metrics table") end - -- bitmaps local bt = open(r, tables[BITMAPS]) if not bt then return nil, Err.new(Err.CORRUPT, "no BITMAPS table") @@ -126047,7 +124534,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local px = Bitmap.unpack(bits, offsets[k], w, h, stride) glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } end - -- encodings local encodings: { [number]: number } = {} local default: number? = nil local et = open(r, tables[BDF_ENCODINGS]) @@ -126078,7 +124564,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- glyph names local nt = open(r, tables[GLYPH_NAMES]) if nt then local n = u32(nt) @@ -126136,16 +124621,9 @@ return Pcf end __FILES["font/psf"] = function() --- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 --- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and --- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry --- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map --- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell --- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: --- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through --- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps --- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd --- project's psf documentation (Andries Brouwer). +-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF / +-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the +-- cell height. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126165,10 +124643,10 @@ local Psf = { type DecodeOptions = { maxGlyphs: number? } -- default 65536 type EncodeOptions = { - version: number?, -- 1 or 2 (default 2) - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - unicode: boolean?, -- write the Unicode table (default true) + version: number?, -- 1 or 2; default 2 + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + unicode: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -126240,7 +124718,7 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end local map: { [number]: number } = {} local sequences = {} - local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order + local unicodeTable: { { any } } = {} if hasTable then local t = r:sub(glyphAt + count * size) for i = 0, count - 1 do @@ -126278,7 +124756,6 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) inSeq = true continue end - -- UTF-8 local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1 if n < 0 then return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") @@ -126345,7 +124822,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if n == 0 then return nil, Err.new(Err.ARG, "no glyphs") end - -- the cell local width = 0 for _, g in glyphs do width = math.max(width, g.advance, g.left + g.width) @@ -126378,7 +124854,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) end buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) end - -- the Unicode table: each glyph's code point and the extra mappings onto it local cps: { { number } } = {} for i = 1, count do cps[i] = {} @@ -126466,11 +124941,9 @@ return Psf end __FILES["font/ttf"] = function() --- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. --- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. +-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype +-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap / +-- colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126488,7 +124961,7 @@ local Ttf = { } type DecodeOptions = { - index: number?, -- the font of a collection (default 0) + index: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ sniff @@ -126511,7 +124984,6 @@ function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- count(r) -> the number of fonts in the file (1 unless a collection) function Ttf.count(r: Bytes.Reader): number return TrueType.count(r.buf, r.base) end @@ -126520,14 +124992,9 @@ return Ttf end __FILES["font/type1"] = function() --- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the --- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, --- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, --- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring --- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph --- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through --- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple --- Master and CID-keyed (Type 9 / 11) fonts, writing. +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font +-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames. +-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126562,7 +125029,6 @@ function Type1.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA local function sections(r: Bytes.Reader): (string?, buffer?, string?) local b = r.buf local n = r:size() @@ -126725,7 +125191,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) local ptext = buffer.tostring(priv) local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 - -- Subrs local subrs: { buffer } = {} local function charstring(p: number, len: number): buffer? local raw = binaryAt(priv, p, len) @@ -126762,7 +125227,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) p = e + n end end - -- CharStrings local names: { string } = {} local charstrings: { buffer } = {} local byName: { [string]: number } = {} @@ -126773,7 +125237,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) break end local e = e0 :: number - -- stop at the end of the dictionary if string.find(string.sub(ptext, p, s), "%send%s") then break end @@ -126802,7 +125265,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] byName[names[1]], byName[names[nd + 1]] = 0, nd end - -- the encoding local encoding: { [number]: string } = {} if string.find(clear, "/Encoding%s+StandardEncoding") then for code, gname in GlyphNames.STANDARD do @@ -126827,7 +125289,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) cmap[cp] = k - 1 end end - -- font matrix / bbox local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") local scale = 0.001 if fm then @@ -126890,17 +125351,10 @@ return Type1 end __FILES["font/type1/Charstring"] = function() --- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted --- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side --- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, --- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; --- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, --- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the --- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored. local Charstring = {} type Result = { cmds: { any }, advance: number, sbx: number } --- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? } local readu8 = buffer.readu8 @@ -126909,7 +125363,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?) local cmds: { any } = {} local stack: { number } = {} local sp = 0 - local ps: { number } = {} -- the PostScript stack callothersubr / pop use + local ps: { number } = {} local x, y = 0, 0 local advance, sbx = 0, 0 local open = false @@ -127175,9 +125629,8 @@ return Charstring end __FILES["font/woff"] = function() --- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended --- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through +-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -127196,7 +125649,7 @@ local Woff = { } type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -127205,7 +125658,6 @@ function Woff.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local base = r.base @@ -127309,9 +125761,8 @@ return Woff end __FILES["font/woff2"] = function() --- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. +-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms, +-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -127330,7 +125781,7 @@ local Woff2 = { } type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -127340,7 +125791,6 @@ function Woff2.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local at = r.base @@ -127368,12 +125818,7 @@ return Woff2 end __FILES["font/woff2/Rebuild"] = function() --- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table --- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, --- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx --- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). --- --- Never throws: malformed data returns nil, message. +-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx). local Bytes = __include("core/Bytes") local Brotli = __include("codecs/compress/Brotli") @@ -127409,7 +125854,6 @@ local function base128(r: Bytes.Reader): number? return nil end --- a cursor over a stream inside the decompressed block type Stream = { buf: buffer, p: number, e: number, bad: boolean } local function stream(b: buffer, p: number, n: number): Stream return { buf = b, p = p, e = p + n, bad = false } @@ -127446,7 +125890,6 @@ local function withSign(flag: number, v: number): number return if band(flag, 1) ~= 0 then v else -v end --- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) local h = stream(b, p, n) su16(h) -- reserved @@ -127501,7 +125944,6 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s return nil, "empty glyph with a bounding box" end elseif nc > 0 then - -- simple glyph local ends = table.create(nc, 0) local total = 0 for c = 1, nc do @@ -127732,7 +126174,6 @@ local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: nu return out:finish(), nil end --- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) if not r:match("wOF2") then return nil, "bad signature", "corrupt" @@ -127802,7 +126243,6 @@ function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, str if buffer.len(data) < streamTotal then return nil, "decompressed stream shorter than the tables", "corrupt" end - -- the tables, glyf / loca / hmtx rebuilt local byTag: { [string]: any } = {} for _, e in dir do byTag[e.tag] = e @@ -127920,11 +126360,6 @@ __FILES["host"] = function() -- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE -- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). --- --- local host = require("@rosetta/host") --- print(host.name) -- "roblox" | "love" | "luajit" | "luau" --- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO --- -- where there is no file system) local Err = __include("core/Err") type Host = { @@ -127958,9 +126393,7 @@ elseif name == "luajit" then else host = __include("host/Luau") :: any end --- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine --- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only --- allows more traces; set _G.ROSETTA_NO_JIT_TUNE = true before requiring the library to leave them alone. +-- LuaJIT: the big decoders outgrow the default 1000 traces / 8 MB of mcode; _G.ROSETTA_NO_JIT_TUNE = true skips this. if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536") end @@ -127971,10 +126404,7 @@ end __FILES["host/Love"] = function() -- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for --- paths outside them; converts the standard types to LÖVE objects: --- host.toImageData(img) -> love ImageData (rgba8) --- host.fromImageData(imageData) -> Image (rgba8) --- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit) +-- paths outside them. ImageData is rgba8; SoundData is 16-bit. local Err = __include("core/Err") local Types = __include("Types") @@ -128013,7 +126443,6 @@ function Host.readFile(path: string): (buffer?, Err.Err?) return buffer.fromstring(s), nil end --- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) local s = buffer.tostring(data) if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then @@ -128044,7 +126473,6 @@ function Host.exists(path: string): boolean return false end --- toImageData(img) -> ImageData | nil, Err function Host.toImageData(img: any): (any, Err.Err?) if img.format ~= "rgba8" then return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) @@ -128061,7 +126489,6 @@ function Host.toImageData(img: any): (any, Err.Err?) return love().image.newImageData(img.width, img.height, "rgba8", bytes) end --- fromImageData(imageData) -> Image (rgba8 copy) function Host.fromImageData(id: any): Types.Image local w, h = id:getDimensions() local img = Types.Image.new(w, h, "rgba8") @@ -128076,11 +126503,9 @@ function Host.fromImageData(id: any): Types.Image return img end --- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end). function Host.toSoundData(a: any): (any, Err.Err?) local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate if samples == nil then - -- a Decoder: read everything local parts, total = {}, 0 while true do local out, n = a:read(65536) @@ -128195,12 +126620,7 @@ end __FILES["host/Roblox"] = function() -- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the --- standard types to engine objects: --- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first) --- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh --- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours) --- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh --- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime). +-- standard types to EditableImage / EditableMesh. local Err = __include("core/Err") local Types = __include("Types") @@ -128220,7 +126640,6 @@ function Host.exists(_path: string): boolean return false end --- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8". function Host.toEditableImage(img: any): (any, Err.Err?) if img.format ~= "rgba8" then return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) @@ -128237,24 +126656,8 @@ function Host.toEditableImage(img: any): (any, Err.Err?) return ei end --- ---------------------------------------------------------------------------------------------------------- meshes --- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One --- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client --- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through --- AssetService:CreateEditableMeshAsync), destroy it, then build the next. --- --- local prims = F.ops.mesh.merge(scene, { byMaterial = true }) --- for _, prim in prims do --- for _, page in assert(F.host.meshPages(prim)) do --- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs --- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em)) --- part.Position = Vector3.new(centre[1], centre[2], centre[3]) --- end --- end --- --- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y") --- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV --- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted. +-- EditableMesh limits (measured in Studio): ~20k triangles and 60k vertices each, 8 growable per client. +-- Roblox is y-up, right-handed, counter-clockwise front faces, as glTF; EditableMesh colours are sRGB, COLOR_0 linear. type MeshPage = { first: number, -- the first triangle (0-based) of the primitive in this page @@ -128292,7 +126695,6 @@ type MeshOptions = { yieldEvery: number?, -- default 2000 } --- the index of each corner (0-based vertex numbers) or nil, Err local function cornerReader(prim: any): ((number) -> number)? local idx = prim.indices if not idx then @@ -128320,8 +126722,6 @@ local function checkPrim(prim: any): (number, Err.Err?) return n // 3, nil end --- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces --- counted when doubleSided) and maxVertices. function Host.meshPages(prim: any, opts: MeshOptions?): ({ MeshPage }?, Err.Err?) local tris, err = checkPrim(prim) if err then @@ -128390,8 +126790,6 @@ local function toSrgb(c: number): number return if c <= 0.0031308 then c * 12.92 else 1.055 * c ^ (1 / 2.4) - 0.055 end --- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for --- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours). function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData?, Err.Err?) local _, err = checkPrim(prim) if err then @@ -128434,7 +126832,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData positions[j + 2] = ((getP :: any)(v, 1) - oy) * sy positions[j + 3] = ((getP :: any)(v, 2) - oz) * sz if normals then - -- normals of a scaled mesh scale by the inverse local x, y, z = (getN :: any)(v, 0) / sx, (getN :: any)(v, 1) / sy, (getN :: any)(v, 2) / sz local len = math.sqrt(x * x + y * y + z * z) if len > 0 then @@ -128469,9 +126866,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData }, nil end --- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole --- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart --- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then. function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (any, any) local o: MeshOptions = opts or {} local pg = page @@ -128526,7 +126920,6 @@ function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (a if C and cids then local k = (i - 1) * 4 local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4] - -- equal colours share one id (voxel palettes, flat-coloured models) local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5)) local id = palette[key] if not id then @@ -128585,13 +126978,9 @@ return Host end __FILES["image/ani"] = function() --- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; --- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, --- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) --- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames --- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors --- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a --- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). +-- image/ani: Windows animated cursor (RIFF "ACON": anih header, rate / seq chunks, LIST fram of ICO / CUR chunks). +-- Supports: the steps as img.frames (seq order; rate or iDispRate in 1/60 s jiffies), CUR hotspots, INFO title / +-- author; icons through opts.decodeImage / opts.encodeImage. Not supported: raw frame bitmaps (AF_ICON clear). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -128611,11 +127000,11 @@ local Ani = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one) - maxFrames: number?, -- refuse more steps (default 10000) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxFrames: number?, -- default 10000 } type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -128653,7 +127042,6 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if not decodeImage then return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") end - -- the icon chunks local icons: { Types.Image } = {} for _, c in f.chunks do if c.id == "LIST" and Riff.listType(f, c) == "fram" then @@ -128684,7 +127072,7 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local im = icons[idx + 1] if not im then if s >= #icons and not seq then - break -- fewer icons than steps: keep what is there + break end return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) end @@ -128770,16 +127158,9 @@ return Ani end __FILES["image/blp"] = function() --- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written --- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. --- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: --- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual --- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); --- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); --- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha --- type 0 / 1 / 7), uncompressed BGRA. --- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). --- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). +-- image/blp: Blizzard BLP textures (BLP1 Warcraft III, BLP2 World of Warcraft), from the wowdev.wiki BLP page. +-- Supports: mip 0 of BLP1 JPEG (4 components: BGRA, no colour conversion) / palette and BLP2 palette (1 / 4 / 8-bit +-- alpha, LSB first) / DXT1 / DXT3 / DXT5 / BGRA; writes BLP2 BGRA + mips. Not supported: BLP0 (.b00 mips), BLP2 JPEG. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -128800,7 +127181,7 @@ local Blp = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxPixels: number? } -- default 2^26 -type EncodeOptions = { mips: boolean? } -- write the mip chain (default false) +type EncodeOptions = { mips: boolean? } -- default false -- ------------------------------------------------------------------------------------------------ constants local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 @@ -128812,13 +127193,11 @@ function Blp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha local function swap(v: number, a: number): number local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256 return r + g * 256 + b * 65536 + a * 16777216 end --- alpha of pixel i from a packed plane at p of depth bits local function alphaAt(b: buffer, p: number, depth: number, i: number): number if depth == 8 then return readu8(b, p + i) @@ -128961,7 +127340,6 @@ function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) local function halve(px: buffer, w: number, h: number): (buffer, number, number) local nw, nh = math.max(1, w // 2), math.max(1, h // 2) local out = buffer.create(nw * nh * 4) @@ -129039,17 +127417,9 @@ end __FILES["image/bmp"] = function() --- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a --- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 --- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or --- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), --- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the --- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit --- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). --- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance --- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with --- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. --- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. +-- image/bmp: Windows / OS/2 BMP; absorbed from bmp-luau b86aed6 (same author), new encoder. Supports: headers 12 / +-- 16..64 / 40 / 52 / 56 / 108 / 124, 1..32 bpp, BITFIELDS / ALPHABITFIELDS, RLE8 / RLE4, both row orders, Pillow's +-- leniency and mask scaling; writes 8 / 24 / 32 bpp as Pillow. Not supported: embedded JPEG / PNG, OS/2 Huffman, RLE24. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -129079,11 +127449,11 @@ type Info = { } type DecodeOptions = { - maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx) + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32 - header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow) + bitDepth: (number | "auto")?, -- default "auto": 8 if opaque with <= 256 colours, else 24 if opaque, else 32 + header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS) or "info" (BI_RGB, as Pillow) } -- ------------------------------------------------------------------------------------------------ constants @@ -129093,7 +127463,6 @@ local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "p local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz --- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) local function whole(r: Bytes.Reader): buffer if r.base == 0 and r.limit == buffer.len(r.buf) then return r.buf @@ -129109,7 +127478,6 @@ function Bmp.sniff(r: Bytes.Reader): number if r:peek(2) ~= "BM" then return 0 end - -- a known header size: a strong match; "BM" alone is weak local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then return 0.9 @@ -129118,7 +127486,6 @@ function Bmp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err local function parseHeader(buf: buffer): (Info?, any) local n = buffer.len(buf) if n < 18 then @@ -129166,13 +127533,11 @@ local function parseHeader(buf: buffer): (Info?, any) return info end --- info(r) -> Info | nil, Err: the header without decoding the pixels function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?) return parseHeader(whole(r)) end --- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate --- the top bits instead, which can differ by 1). m = 0 -> { empty }. +-- v * 255 // m, as Pillow (browsers replicate the top bits, which can differ by 1) local function scaleTable(m: number, empty: number): buffer local t = buffer.create(m + 1) if m == 0 then @@ -129185,7 +127550,7 @@ local function scaleTable(m: number, empty: number): buffer return t end --- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +-- a mask wider than 16 bits keeps its top 16 local function channel(mask: number, empty: number): (number, number, buffer) if mask == 0 then return 0, 0, scaleTable(0, empty) @@ -129205,7 +127570,6 @@ local function channel(mask: number, empty: number): (number, number, buffer) return sh, m, scaleTable(m, empty) end --- decode(r, opts?) -> rgba8 Image | nil, Err function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) local buf = whole(r) local info, herr = parseHeader(buf) @@ -129275,7 +127639,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end - -- palette local entrySize = if hs == 12 then 3 else 4 local declared = if hs >= 36 then readu32(buf, 46) else 0 local palCount = 0 @@ -129373,7 +127736,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- encode(img, opts?) -> buffer | nil, Err function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") @@ -129469,19 +127831,9 @@ return Bmp end __FILES["image/dds"] = function() --- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new --- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / --- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the --- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the --- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six --- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there --- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / --- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by --- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. --- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 --- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the --- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), --- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. +-- image/dds: DirectDraw Surface (Microsoft DDS guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10). Supports: DXGI +-- formats with a pixel layout, legacy FourCC and bit-mask formats, mips, cube maps, arrays, volumes; writes rgba8 / BC1 +-- / BC3 / BC4 / BC5 / rgba16 / rgbaf32. Not supported: planar video (NV12, P010), P8, R1_UNORM, stencil formats. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -129504,18 +127856,17 @@ local Dds = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8) - mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) - surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) - maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface) + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface } type EncodeOptions = { - pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: - -- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones - mips: boolean?, -- write a full mip chain (default false) - dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays) - cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube") - alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128) + pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, + mips: boolean?, -- default false + dx10: boolean?, -- default: when the format needs it, or for arrays + cube: boolean?, -- default: when img.meta.layout == "cube" + alphaThreshold: number?, -- default 128 } -- ------------------------------------------------------------------------------------------------ constants @@ -129571,10 +127922,10 @@ type Info = { height: number, depth: number, mips: number, - format: string, -- the texture format name (codecs/image/Texture) + format: string, layout: string, -- "2d" | "cube" | "array" | "volume" layers: number, - faces: { string }, -- cube faces present (in file order), else { } + faces: { string }, -- in file order srgb: boolean, dxgi: number?, fourcc: string?, @@ -129588,7 +127939,6 @@ local function u32(b: buffer, o: number): number return buffer.readu32(b, o) end --- info(r) -> Info | nil, Err (the headers only) function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) local b, o, n = r.buf, r.base, r.limit - r.base if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then @@ -129698,7 +128048,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) if not d then return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) end - -- the common masks map onto named texel formats (fast paths, sane names) local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) local named = ({ ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", @@ -129735,7 +128084,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- the bytes of one surface of format f local function surfaceSize(info: any, w: number, h: number): number if info.format == "masked" then return (info.masked :: Texel.Desc).bytes * w * h @@ -129829,7 +128177,6 @@ end local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } --- the surface bytes of one image in format f local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?) local w, h, px = img.width, img.height, img.pixels if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then @@ -129918,7 +128265,6 @@ function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if pf ~= needs then return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) end - -- surfaces: the frames (array / cube faces) or the image local images: { Types.Image } = { img } if img.frames and #img.frames > 1 then images = {} @@ -129968,19 +128314,9 @@ return Dds end __FILES["image/exr"] = function() --- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ --- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and --- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts --- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), --- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any --- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image --- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. --- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear --- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) --- for colour, round(clamp(a, 0, 1) * 255) for alpha. --- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only --- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / --- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). +-- image/exr: OpenEXR (openexr.com file layout docs; PIZ after OpenEXR, BSD-3-Clause: licenses/openexr-LICENSE.md). +-- Supports: single / multipart, scanline / tiled (mip / rip level 0, mips), NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT +-- / UINT, subsampling, layers; writes scanlines. Not supported: deep, PXR24 / B44(A) / DWA / HTJ2K / ZSTD. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -130003,17 +128339,17 @@ local Exr = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) - part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1) - layer: string?, -- read .R / .G / .B / .A instead of R / G / B / A - mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + part: (number | string)?, -- 1-based index or name; default 1 + layer: string?, + mips: boolean?, -- default false + maxPixels: number?, -- default 2^26 } type EncodeOptions = { compression: ("none" | "zips" | "zip")?, -- default "zip" pixelType: ("half" | "float")?, -- default "half" - alpha: boolean?, -- write A (default: when some alpha is not 1) - level: number?, -- zlib level 1..9 (default 6) + alpha: boolean?, -- default: when some alpha is not 1 + level: number?, -- 1..9, default 6 } -- ------------------------------------------------------------------------------------------------ constants @@ -130060,7 +128396,6 @@ local function f32(b: buffer, o: number): number return readf32(b, o) end --- one attribute value of a known type local function value(b: buffer, p: number, size: number, typ: string): any if typ == "chlist" then local list: { Channel } = {} @@ -130115,7 +128450,6 @@ local function value(b: buffer, p: number, size: number, typ: string): any return raw end --- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?) local attrs: { [string]: any } = {} local types: { [string]: string } = {} @@ -130148,7 +128482,6 @@ local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, end end --- level sizes of a tiled part local function levelSize(n: number, l: number, roundUp: boolean): number local d = 2 ^ l return math.max(1, if roundUp then math.ceil(n / d) else n // d) @@ -130170,7 +128503,6 @@ local function levelCount(w: number, h: number, mode: number, roundUp: boolean): return count(w), count(h) end --- chunk count of a part (single-part files: computed) local function chunkCount(pt: Part): number local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 if not pt.tiled then @@ -130256,7 +128588,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) if multi then p += 1 end - -- offset tables for _, pt in info.parts do local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0) if n < 0 or n > 2 ^ 24 then @@ -130275,20 +128606,17 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err function Exr.info(r: Bytes.Reader): (Info?, Err.Err?) return parse(r) end --- bytes of a sample kind local SIZE = { [0] = 4, 2, 4 } --- number of multiples of s in [a, b] local function samples(a: number, b: number, s: number): number return b // s - (a - 1) // s end -type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey) +type Target = { [number]: number } local function newPlane(pw: number, ph: number): buffer local px = buffer.create(pw * ph * 16) @@ -130297,7 +128625,6 @@ local function newPlane(pw: number, ph: number): buffer end return px end --- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err? local p = dp for y = y0, y1 do @@ -130342,7 +128669,6 @@ local function block(part: Part, target: Target, data: buffer, dp: number, y0: n return nil end --- the raw bytes of a block (uncompressed size raw) local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?) if size == raw or comp == 0 then if size < raw then @@ -130412,7 +128738,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel -> output component local prefix = if opts and opts.layer then opts.layer .. "." else "" local target: Target = {} local hasRgb = false @@ -130435,7 +128760,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end local multi = info.multipart - -- offsets: single-part tables with holes are rebuilt from the chunk sequence local offsets = part.offsets local bad = false for _, o in offsets do @@ -130481,7 +128805,7 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end - local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local planes: { [number]: buffer } = { [0] = newPlane(w, h) } local tiles = part.tiles local roundUp = tiles ~= nil and tiles[4] == 1 local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 @@ -130653,7 +128977,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "pixelType must be half or float") end local level = opts and opts.level or 6 - -- the float values local n = w * h local fl = buffer.create(n * 16) if img.format == "rgbaf32" then @@ -130679,7 +129002,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local sz = if kind == 1 then 2 else 4 local lpb = LINES[comp] local nblocks = (h + lpb - 1) // lpb - -- header local hw = Bytes.writer(512) hw:string(MAGIC) hw:u32le(2) @@ -130754,9 +129076,7 @@ __FILES["image/exr/Codec"] = @native function() --- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- --- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), --- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +-- image/exr/Codec: OpenEXR RLE / ZIP / ZIPS blocks and sample conversion (after ImfZip / ImfRle, BSD-3-Clause). local Deflate = __include("codecs/compress/Deflate") local Half = __include("codecs/image/Half") @@ -130765,7 +129085,6 @@ local Codec = {} local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 local HALF = Half.TABLE --- undoes the predictor and the interleave of t (n bytes) -> a new buffer @native local function reconstruct(t: buffer, n: number): buffer local prev = if n > 0 then readu8(t, 0) else 0 for i = 1, n - 1 do @@ -130783,7 +129102,6 @@ local HALF = Half.TABLE return out end --- rle(src, p, n, outSize) -> the raw block | nil, message @native function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t = buffer.create(outSize) local o, stop = 0, p + n @@ -130813,7 +129131,6 @@ end return reconstruct(t, outSize), nil end --- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) @native function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t, err = Deflate.zlib(src, p, n, outSize) if not t then @@ -130825,7 +129142,6 @@ end return reconstruct(t, outSize), nil end --- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) @native function Codec.zip(raw: buffer, level: number): buffer local n = buffer.len(raw) local t = buffer.create(n) @@ -130847,8 +129163,6 @@ end return Deflate.zlibCompress(t, { level = level }) :: buffer end --- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into --- dst (f32) at byte offset d, step bytes apart; returns the source offset after them @native function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number if kind == 1 then for i = 0, count - 1 do @@ -130873,10 +129187,7 @@ __FILES["image/exr/Piz"] = @native function() --- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor --- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman --- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit --- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +-- image/exr/Piz: OpenEXR PIZ decompressor (after ImfPizCompressor / ImfHuf / ImfWav, BSD-3-Clause). local Piz = {} local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 @@ -130888,7 +129199,6 @@ local DECBITS = 14 local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 -- ------------------------------------------------------------------------------------------------ Huffman --- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) @native local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? local c, lc = 0, 0 @native local function bits(n: number): number? @@ -130941,7 +129251,6 @@ local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 return p end --- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message @native local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? if n == 0 then return if nRaw == 0 then nil else "empty Huffman data" @@ -131008,7 +129317,6 @@ end end end end - -- decode MSB-first from a zero-padded copy local nbytes = (nBits + 7) // 8 local data = buffer.create(nbytes + 8) buffer.copy(data, 0, src, q, nbytes) @@ -131083,7 +129391,6 @@ end end -- ------------------------------------------------------------------------------------------------ wavelet --- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) @native local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) local w14 = mx < 16384 local n = math.min(nx, ny) @@ -131152,9 +129459,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Chan = { nx: number, ny: number, size: number, ys: number } --- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. --- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and --- ySampling. @native function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) local total = 0 for _, c in chans do @@ -131185,7 +129489,6 @@ type Chan = { nx: number, ny: number, size: number, ys: number } buffer.copy(bitmap, minNZ, src, p, cnt) p += cnt end - -- reverse LUT local lut = buffer.create(USHORT_RANGE * 2) local k = 0 for i = 0, USHORT_RANGE - 1 do @@ -131220,7 +129523,6 @@ type Chan = { nx: number, ny: number, size: number, ys: number } for i = 0, total - 1 do writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) end - -- planes -> scanlines local o = 0 local cursor = table.clone(starts) for y = minY, maxY do @@ -131240,20 +129542,9 @@ return Piz end __FILES["image/gif"] = function() --- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image --- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames --- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / --- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames --- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize --- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with --- alpha < 128 as the transparent index. --- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" --- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). --- --- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every --- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the --- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as --- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). +-- image/gif: GIF87a / GIF89a, from the GIF89a spec (CompuServe 1990). Supports: every image, interlace, LZW code sizes +-- 1..8, transparency, GCE delays / disposal, NETSCAPE2.0 / ANIMEXTS1.0 loops, comments; writes quantized frames. Not +-- supported: the plain text extension, the aspect ratio, the user input flag, blend "source" frames. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -131275,17 +129566,16 @@ local Gif = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) - maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28) - maxFrames: number?, -- stop after this many frames (default: all) + maxPixels: number?, -- default 2^26 + maxTotalPixels: number?, -- default 2^28 + maxFrames: number?, -- default: all } type EncodeOptions = { - maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed) + maxColors: number?, -- 2..256, default 256 method: ("mediancut" | "octree")?, -- default "mediancut" - dither: boolean?, -- Floyd-Steinberg (default false) - loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops) - globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table, - -- each animation frame gets its own local table) + dither: boolean?, -- Floyd-Steinberg, default false + loops: number?, -- 0 = forever, 1..65536; default img.loops + globalPalette: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -131300,7 +129590,6 @@ function Gif.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) local t = buffer.create(1024) local list: { { number } } = table.create(n) :: { { number } } @@ -131351,14 +129640,12 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local comments: { string } = {} local loops: number? = nil local total = 0 - -- the pending Graphic Control Extension local delay, dispose, trans = 0, 0, -1 local truncated = false local interlacedAny = false local localTables = 0 local minCode = 8 local limit = r.limit - -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) local function subBlocks(): (buffer?, number) local p = r.pos local n = 0 @@ -131528,7 +129815,6 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E break end else - -- junk between blocks: stop here, keeping what was read if #frames == 0 then return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) end @@ -131581,7 +129867,6 @@ local function hasTransparency(px: buffer, n: number): boolean return false end --- palette list -> padded table bytes (power of two entries, >= 2) and its size code local function writeTable(w: Bytes.Writer, pal: { { number } }): number local bits = 1 while bit32.lshift(1, bits) < #pal do @@ -131622,7 +129907,6 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "method must be mediancut or octree") end local dither = opts and opts.dither or false - -- the frames to write: { image, x, y, delay, dispose } local list: { Types.Frame } = {} if type(img.frames) == "table" and #(img.frames :: any) > 0 then for i, f in img.frames :: { Types.Frame } do @@ -131643,13 +129927,11 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then return nil, Err.new(Err.ARG, "loops must be 0..65536") end - -- palettes local shared = (opts and opts.globalPalette) or not animated local qopts: Quantize.PaletteOptions = { method = method, dither = dither } local globalPal: { { number } }? = nil local globalTrans = false if shared then - -- every frame's pixels together local npx = 0 for _, f in list do npx += f.image.width * f.image.height @@ -131778,15 +130060,12 @@ __FILES["image/gif/Decode"] = @native function() --- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to --- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every --- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas. local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Decode = {} --- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from --- 2, every 2nd from 1) +-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1 @native local function interlacedRow(fh: number): { number } local map = table.create(fh, 0) local r = 0 @@ -131801,8 +130080,6 @@ local Decode = {} return map end --- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the --- transparent one already alpha 0) @native function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) local rows = if interlaced then interlacedRow(fh) else nil for y = 0, fh - 1 do @@ -131814,7 +130091,6 @@ end end end --- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) @native function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) @@ -131830,7 +130106,6 @@ end end end --- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) @native function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) @@ -131846,14 +130121,9 @@ return Decode end __FILES["image/hdr"] = function() --- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. --- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of --- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution --- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. --- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: --- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a --- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). --- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), from the Radiance file format notes and rgbe.c. Supports: "#?" headers, +-- 32-bit_rle_rgbe, EXPOSURE (kept, not applied), the eight orientations, flat / old / new RLE; writes -Y +X new RLE. +-- Not supported: 32-bit_rle_xyze, PRIMARIES / COLORCORR (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -131873,12 +130143,12 @@ local Hdr = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - rle: boolean?, -- new-style RLE scanlines (default true) - exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1) + rle: boolean?, -- default true + exposure: number?, -- default: meta.exposure when not 1 } -- ------------------------------------------------------------------------------------------------ constants @@ -131904,7 +130174,6 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local maxPixels = opts and opts.maxPixels or 2 ^ 26 local b, limit = r.buf, r.limit local p = r.base - -- header lines up to the first empty one local function line(): string? local s = p while p < limit and buffer.readu8(b, p) ~= 10 do @@ -132034,7 +130303,6 @@ function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local px = img.pixels if bpp == 4 then - -- rgba8 through the inverse of the decoder's display curve local lut = table.create(256, 0) for v = 0, 255 do lut[v + 1] = (v / 255) ^ 2.2 @@ -132084,17 +130352,13 @@ __FILES["image/hdr/Codec"] = @native function() --- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes --- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE --- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then --- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and --- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +-- image/hdr/Codec: Radiance RGBE scanlines (Graphics Gems II; rgbe.c): mantissa * 2^(e - 136), no +0.5, as stb_image. local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 local frexp = math.frexp local Codec = {} --- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +-- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes @native function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then @@ -132178,7 +130442,6 @@ local Codec = {} return p, nil end --- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step @native function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) for i = 0, n - 1 do local q = i * 4 @@ -132198,7 +130461,6 @@ end end end --- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) @native function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) for x = 0, w - 1 do local q = (y * w + x) * 16 @@ -132245,7 +130507,6 @@ end end end --- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 @native function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number writeu8(out, o, 2) writeu8(out, o + 1, 2) @@ -132255,7 +130516,6 @@ end for c = 0, 3 do local cur = 0 while cur < w do - -- find the next run of at least 4 local begRun = cur local runCount = 0 local oldRun = 0 @@ -132270,14 +130530,12 @@ end end end end - -- a short run just before the long one if oldRun > 1 and oldRun == begRun - cur then writeu8(out, o, 128 + oldRun) writeu8(out, o + 1, readu8(row, cur * 4 + c)) o += 2 cur = begRun end - -- raw bytes up to the run while cur < begRun do local n = math.min(begRun - cur, 128) writeu8(out, o, n) @@ -132303,15 +130561,9 @@ return Codec end __FILES["image/icns"] = function() --- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: --- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha --- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any --- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), --- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists --- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns --- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage --- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / --- 48 / 128 with masks. +-- image/icns: Apple icon images (icns resource type). Supports: is32 / il32 / ih32 / it32 (icns RLE) with s8mk / l8mk / +-- h8mk / t8mk masks, ic04 / ic05 ARGB, 1-bit ics# / ICN# / ich# / icm#, PNG entries through opts.decodeImage; writes +-- PNG or RLE entries. Not supported: JPEG 2000 entries, 4 / 8-bit palette entries, nested dark-mode / TOC chunks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -132332,12 +130584,12 @@ local Icns = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) - maxPixels: number?, -- refuse entries larger than this (default 2^22) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^22 } type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) - legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + legacy: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -132362,7 +130614,6 @@ function Icns.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean for _, ch in channels do local i = 0 @@ -132532,7 +130783,6 @@ function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- the icns RLE of one channel (count bytes, step 4 from ch) into w local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number) local i = 0 while i < count do @@ -132642,16 +130892,9 @@ return Icns end __FILES["image/ico"] = function() --- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every --- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or --- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are --- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); --- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png --- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as --- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it --- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. --- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS --- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. +-- image/ico: Windows icons and cursors (ICO / CUR), from Microsoft's ICO documentation. Supports: every entry as a BMP +-- DIB (1..32-bit, AND mask) or PNG (opts.decodeImage), CUR hotspots; writes 32-bit DIB or PNG entries. Not supported: +-- resizing to icon sizes, DIB compression (BI_BITFIELDS read as 5-5-5 / BGRA), 2-colour planes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -132671,13 +130914,13 @@ local Ico = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) - maxPixels: number?, -- refuse larger entries (default 2^26) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) - png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists) - cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + png: boolean?, -- default: only 256-pixel entries + cursor: boolean?, -- default: when the image has meta.hotspot } -- ------------------------------------------------------------------------------------------------ constants @@ -132928,18 +131171,14 @@ __FILES["image/ico/Dib"] = @native function() --- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from --- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit --- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha --- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are --- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +-- image/ico/Dib: ICO / CUR DIBs: XOR bitmap (1..32-bit, bottom-up, 4-byte rows) + 1-bit AND mask (1 = transparent). local Pixels = __include("codecs/image/Pixels") local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} --- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +-- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides @native function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) local stride = ((w * bpp + 31) // 32) * 4 local maskStride = ((w + 31) // 32) * 4 @@ -132988,8 +131227,6 @@ local Dib = {} return true, nil end --- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). --- out needs room for w * h * 4 + maskStride * h bytes. @native function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do @@ -133027,14 +131264,9 @@ return Dib end __FILES["image/ilbm"] = function() --- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks --- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a --- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), --- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or --- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH --- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else --- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer --- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). +-- image/ilbm: IFF ILBM / PBM (EA IFF 85 "ILBM", Amiga ROM Kernel Manual). Supports: 1..8 planes + CMAP, EHB (CAMG +-- 0x80), HAM6 / HAM8 (CAMG 0x800; 4-bit v -> v * 17, ilbmtoppm shifts), 24 / 32 planes, PBM, masking 1 / 2, ByteRun1, +-- NAME / ANNO / AUTH. Not supported: ANIM, RGBN / RGB8 / ACBM / DEEP, SHAM / PCHG (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133056,11 +131288,11 @@ local Ilbm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false) - maxPixels: number?, -- refuse larger images (default 2^26) + adjustColors: boolean?, -- default false + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - compress: boolean?, -- ByteRun1 (default true) + compress: boolean?, -- default true } local readu8, readu16 = buffer.readu8, buffer.readu16 @@ -133120,7 +131352,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham - -- palette local pal = buffer.create(1024) local ncol = 0 if cmap then @@ -133153,7 +131384,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) end end - -- the body, decompressed local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2 local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h local raw = buffer.create(total) @@ -133353,22 +131583,9 @@ return Ilbm end __FILES["image/jpeg"] = function() --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG --- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical --- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the --- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi --- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images --- (coded 4:2:0 from the planes as they are). --- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit --- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt --- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's --- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt --- scans decode as far as they go (meta.truncated = true). --- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or --- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta; --- byte-identical to cjpeg for the same settings. --- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit --- or CMYK encoding. +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81) over codecs/image/Jpeg (from jpeg-luau 1.0, same author; bit-exact with +-- djpeg, byte-identical with cjpeg; IJG parts: licenses/libjpeg-turbo-LICENSE.md). Supports: SOF0/1/2/9/10, 8 / 12-bit, +-- scaled decodes, EXIF / ICC / COM / JFIF density. Not supported: lossless (SOF3), hierarchical, DNL, 2 components. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133388,20 +131605,20 @@ local Jpeg = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) - orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only) - native: boolean?, -- grey files decode to gray8 (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + scale: number?, -- 1 (default), 2, 4 or 8 + orient: boolean?, -- default false + native: boolean?, -- default false + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables - subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420") + quality: number?, -- 1..100, default 90 (libjpeg scaling of the T.81 annex K tables) + subsampling: ("420" | "422" | "444")?, -- default "420" progressive: boolean?, -- default false - optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) - gray: boolean?, -- a one-component file (default: true for gray8 images) - restart: number?, -- restart interval in MCUs (default 0 = none) - jfif: boolean?, -- write the JFIF APP0 header (default true) - meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true) + optimize: boolean?, -- default false; progressive always optimises + gray: boolean?, -- default: true for gray8 images + restart: number?, -- in MCUs, default 0 = none + jfif: boolean?, -- default true + meta: boolean?, -- default true } type Info = Codec.Info @@ -133413,7 +131630,6 @@ function Jpeg.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- info(r) -> Info | nil, Err (reads the headers up to the frame header) function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?) return Codec.info(r.buf, r.base, r.limit - r.base) end @@ -133423,7 +131639,7 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. return nil, Err.new(Err.ARG, "options must be a table") end local o = opts or {} :: DecodeOptions - -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + -- two JPEGs back to back are an image and a preview, as in MPF return Codec.decode(r.buf, r.base, r.limit - r.base, { scale = o.scale, orient = o.orient, @@ -133434,7 +131650,6 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- the APP1 / APP2 / COM segments and the JFIF density from img.meta local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) local segments = {} if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then @@ -133504,17 +131719,9 @@ return Jpeg end __FILES["image/ktx"] = function() --- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL --- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the --- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every --- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip --- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are --- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is --- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. --- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 --- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, --- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and --- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. +-- image/ktx: Khronos KTX 1.1 / KTX 2.0. Supports: KTX1 (GL compressed and uncompressed, big-endian), KTX2 (VkFormat BCn +-- / ETC2 / EAC / uncompressed; Zstd and ZLIB supercompression), mips, cubes, arrays, 3D, KTXorientation; writes +-- uncompressed KTX2. Not supported: Basis Universal (BasisLZ / UASTC), ASTC, PVRTC. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133538,18 +131745,18 @@ local Ktx = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8) - mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) - surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) - maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface } type EncodeOptions = { pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) - srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") - mips: boolean?, -- a full mip chain (box filter; default false) - cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") - zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none) - keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written) + srgb: boolean?, -- default: meta.colorSpace == "srgb" + mips: boolean?, -- default false + cube: boolean?, -- default: meta.layout == "cube" + zlib: number?, -- 1..9, default none + keyValue: { [string]: string }?, -- KTXwriter is always written } -- ------------------------------------------------------------------------------------------------ constants @@ -133623,7 +131830,7 @@ type Info = { layers: number, faces: number, levels: number, - format: string?, -- the texture format name (nil when unsupported: see unsupported) + format: string?, unsupported: string?, srgb: boolean, opaque: boolean, -- BC1 RGB @@ -133794,7 +132001,6 @@ local function info2(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- info(r) -> Info | nil, Err (the headers only) function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) local id = r:peek(12) if id == ID2 then @@ -133805,7 +132011,6 @@ function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) end --- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image local function swapped(b: buffer, p: number, n: number, size: number): buffer local out = buffer.create(n) buffer.copy(out, 0, b, p, n) @@ -133857,7 +132062,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local w, h, d = info.width, info.height, info.depth for level = 0, info.levels - 1 do local want = level == 0 or wantMips - -- the level's data: buf, offset, the image stride and row pitch local lb, lp = b, 0 local rowPitch: number? = nil local imgSize = Texture.size(fmt, w, h) :: number @@ -133997,7 +132201,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- format -> VkFormat, bytes per texel, component bytes, kind local OUT: { [string]: { number } } = { rgba8 = { 37, 4, 1 }, rgba16 = { 91, 8, 2 }, @@ -134087,7 +132290,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then return nil, Err.new(Err.ARG, "zlib level must be 1..9") end - -- level data: the images of every layer / face per level local levelData: { buffer } = {} local raw: { number } = {} local cur = table.clone(images) @@ -134107,7 +132309,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end levelData[lv] = lb end - -- key / value data local kvw = Bytes.writer() local pairs_: { { string } } = { { "KTXwriter", "rosetta" } } if opts and opts.keyValue then @@ -134178,11 +132379,9 @@ return Ktx end __FILES["image/pcx"] = function() --- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit --- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the --- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross --- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as --- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. +-- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 +-- planes (EGA), 2 / 4-bit packed, 8-bit with the 256-colour end palette, 8-bit x 3 / 4 planes, RLE across scan lines, +-- uncompressed, DPI; writes 8-bit palette or 24 / 32-bit planes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -134202,10 +132401,10 @@ local Pcx = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes + palette: boolean?, -- default true; false: always 24 / 32-bit planes } local readu8, readu16 = buffer.readu8, buffer.readu16 @@ -134290,7 +132489,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E p += n truncated = n < total end - -- palettes local pal = buffer.create(1024) local function setPal(i: number, rr: number, gg: number, bb: number) buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) @@ -134362,7 +132560,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- RLE of one plane row into w local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number) local i = 0 while i < n do @@ -134446,16 +132643,9 @@ return Pcx end __FILES["image/png"] = function() --- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. --- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), --- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha --- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). --- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / --- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not --- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode --- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. --- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are --- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every +-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not +-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -134479,14 +132669,13 @@ local Png = { } type DecodeOptions = { - checkCrc: boolean?, -- verify every chunk's CRC-32 (default false) - maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer) + checkCrc: boolean?, -- default false + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - level: number?, -- deflate level 0..9 (default 6) + level: number?, -- 0..9, default 6 colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one - apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when - -- img.frames is a non-empty list + apng: boolean?, -- default: APNG when img.frames is a non-empty list } -- ------------------------------------------------------------------------------------------------ constants @@ -134513,7 +132702,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number } --- the IHDR at r's start: Header | nil, Err local function header(r: Bytes.Reader): (Header?, Err.Err?) local b, o, n = r.buf, r.base, r.limit - r.base if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then @@ -134545,7 +132733,6 @@ local function header(r: Bytes.Reader): (Header?, Err.Err?) return h, nil end --- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) function Png.info(r: Bytes.Reader): (Header?, Err.Err?) return header(r) end @@ -134564,8 +132751,6 @@ type FrameControl = { } local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" } --- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split --- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err? -- the inflated size: every (pass) row has a filter byte local channels = Decode.CHANNELS[ct] @@ -134622,7 +132807,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) end local b, n = r.buf, r.limit - -- chunks local pal = buffer.create(1024) for i = 0, 255 do buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black @@ -134822,7 +133006,6 @@ local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 } local BLEND_CODES: { [string]: number } = { source = 0, over = 1 } --- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds local function delayFraction(delay: number): (number, number) for den = 1, 1000 do local num = math.floor(delay * den + 0.5) @@ -134854,7 +133037,6 @@ local function validImage(im: any): boolean and buffer.len(im.pixels) >= im.width * im.height * 4 end --- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?) local frames = img.frames local mode = if opts then opts.apng else nil @@ -134912,7 +133094,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local want = opts and opts.colorType or "auto" local ctName: string = want if want == "auto" then - -- the smallest colour type that holds the image and every frame local alpha, color = false, false local function scan(im: Types.Image) local c = Encode.pickColorType(im.pixels, im.width, im.height) @@ -135016,8 +133197,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a --- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?) if not validImage(img) then return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") @@ -135046,9 +133225,7 @@ __FILES["image/png/Apng"] = @native function() --- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / --- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the --- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +-- image/png/Apng: APNG 1.0 dispose / blend compositing; "over" uses ffmpeg pngdec.c's integer arithmetic (byte-exact). local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill @@ -135058,7 +133235,6 @@ local Apng = {} return (x + 128) * 257 // 65536 end --- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas @native local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) for y = 0, fh - 1 do local so = y * fw * 4 @@ -135091,7 +133267,6 @@ end end end --- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) @native function Apng.composite(w: number, h: number, frames: { any }): { buffer } local canvas = bcreate(w * h * 4) local saved = bcreate(w * h * 4) @@ -135130,12 +133305,7 @@ __FILES["image/png/Decode"] = @native function() --- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the --- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. --- Absorbed from png-luau src/Png/Decode.luau (same author). --- --- The caller (init) has validated the header and checked that the data holds at least the expected number of --- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +-- image/png/Decode: PNG unfiltering and expansion to RGBA8 (absorbed from png-luau src/Png/Decode.luau, same author). local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcopy = buffer.copy @@ -135157,20 +133327,16 @@ Decode.PASSES = PASSES local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } Decode.CHANNELS = CHANNELS --- bytes per row (without the filter byte) for a pass width @native function Decode.rowBytes(pw: number, channels: number, depth: number): number return (pw * channels * depth + 7) // 8 end --- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per --- complete pixel (at least 1). Returns true, or false + the bad filter type. @native local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) local stride = rb + 1 for r = 0, ph - 1 do local f = readu8(raw, p) local cur = p + 1 if f == 0 then - -- none elseif f == 1 then for i = cur + bpp, cur + rb - 1 do writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) @@ -135180,7 +133346,6 @@ end local i = cur local e4 = cur + rb - 4 while i <= e4 do - -- four bytes at once: add without carries between the byte lanes local x, y = readu32(raw, i), readu32(raw, i - stride) local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) @@ -135241,9 +133406,6 @@ end return true, 0 end --- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. --- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), --- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. @native local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) if ct == 6 then if depth == 8 then @@ -135342,8 +133504,6 @@ end end end --- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). --- Returns true, or false + message. @native function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) local channels = CHANNELS[ct] local bpp = math.max(1, (channels * depth) // 8) @@ -135385,9 +133545,7 @@ __FILES["image/png/Encode"] = @native function() --- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and --- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute --- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +-- image/png/Encode: PNG colour type choice and filtering (per-row minimum sum of |signed residuals|, as libpng). local readu8, writeu8 = buffer.readu8, buffer.writeu8 local bcreate, bcopy = buffer.create, buffer.copy @@ -135395,7 +133553,6 @@ local Encode = {} local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } --- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" @native function Encode.pickColorType(px: buffer, w: number, h: number): string local opaque, gray = true, true for i = 0, w * h - 1 do @@ -135417,7 +133574,6 @@ local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } return "rgb" end --- convert rgba8 to the colour type's packed rows (no filter bytes) @native local function pack(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] if ch == 4 then @@ -135454,8 +133610,6 @@ end return c end --- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); --- the arithmetic is inlined: this runs for every byte @native local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 local p = s - rb @@ -135485,7 +133639,6 @@ end return c0, c1, c2, c3, c4 end --- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) @native local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) writeu8(out, o, f) o += 1 @@ -135514,8 +133667,6 @@ end end end --- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of --- |signed residuals| (the libpng heuristic) @native function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] local src = pack(px, w, h, ct) @@ -135547,14 +133698,9 @@ return Encode end __FILES["image/pnm"] = function() --- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), --- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any --- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). --- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout --- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is --- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel --- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. --- Not supported: multi-image streams (the first image is read), PAM depths above 4. +-- image/pnm: Netpbm, from the Netpbm format pages: PBM (P1 / P4), PGM (P2 / P5), PPM (P3 / P6), PAM (P7, depth 1..4) +-- and PFM (PF / Pf, either byte order, bottom-up rows). Supports: maxval 1..65535, PFM to rgba8 as clamp(v, 0, 1) * +-- 255; writes all seven types. Not supported: multi-image streams, PAM depths above 4. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -135574,15 +133720,14 @@ local Pnm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- keep the source layout (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour - -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default - ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false) - maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it - threshold: number?, -- pbm: grey below this (0..255) is black (default 128) + format: string?, -- default: grey -> pgm, opaque colour -> ppm, alpha -> pam, rgbaf32 -> pfm; "pnm" means the default + ascii: boolean?, -- default false + maxval: number?, -- 1..65535, default 255 (65535 for 16-bit / float sources) + threshold: number?, -- 0..255, default 128 } -- ------------------------------------------------------------------------------------------------ constants @@ -135614,7 +133759,6 @@ local function isSpace(c: number): boolean return c == 32 or (c >= 9 and c <= 13) end --- the next header token from p: token, position after it (nil at the end) local function token(b: buffer, p: number, limit: number): (string?, number) while p < limit do local c = readu8(b, p) @@ -135709,7 +133853,6 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E maxval = int(v) elseif key == "TUPLTYPE" then tupl = v - -- the rest of the line belongs to the value while p < limit and readu8(b, p) ~= 10 do p += 1 end @@ -135732,7 +133875,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E else return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) end - local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil + local w, h, maxval = w :: number, h :: number, maxval :: number if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) end @@ -135935,17 +134078,13 @@ __FILES["image/pnm/Codec"] = @native function() --- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, --- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM --- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. --- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +-- image/pnm/Codec: Netpbm sample loops: P1 digits may run together; PFM either byte order. local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 local byteswap = bit32.byteswap local Codec = {} --- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). -- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) @native function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) if mode == 1 then @@ -135967,7 +134106,6 @@ local Codec = {} end local i = 0 while i < count do - -- skip whitespace and comments while p < limit do local c = readu8(b, p) if c == 35 then -- '#' @@ -136007,7 +134145,6 @@ local Codec = {} return true, nil end --- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values @native function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) local rowBytes = (w + 7) // 8 if p + rowBytes * h > limit then @@ -136023,11 +134160,9 @@ end return true, nil end --- format codes for pack / extract Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 --- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for --- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +-- 8-bit: round(v * 255 / maxval) @native function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) local wide = fmt == 4 or fmt == 5 local top = if wide then 65535 else 255 @@ -136078,7 +134213,6 @@ Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, end end --- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst @native function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) if p + w * h * ch * 4 > limit then return false, "truncated" @@ -136116,8 +134250,7 @@ end return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) end --- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for --- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +-- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000 @native function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer local out = buffer.create(n * ch * 2) local srcWide = fmt == 4 or fmt == 5 @@ -136166,7 +134299,6 @@ end return out end --- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) @native function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number if wide then for i = 0, count - 1 do @@ -136184,7 +134316,6 @@ end return o end --- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) @native function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number for y = 0, h - 1 do local acc, nb = 0, 0 @@ -136205,8 +134336,6 @@ end return o end --- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM --- rows, bottom-to-top @native function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do @@ -136224,10 +134353,8 @@ return Codec end __FILES["image/qoi"] = function() --- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. --- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); --- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. --- Not supported: nothing in the spec is left out. +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). Supports: the whole spec (RGB / RGBA, +-- both colour space tags in meta.source.colorSpace). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -136247,12 +134374,12 @@ local Qoi = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4) - linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear") + channels: number?, -- default: 3 for rgb8 or opaque rgba8, else 4 + linear: boolean?, -- default: meta.source.colorSpace == "linear" } -- ------------------------------------------------------------------------------------------------ sniff @@ -136350,16 +134477,13 @@ __FILES["image/qoi/Codec"] = @native function() --- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). --- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read --- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +-- image/qoi/Codec: QOI op loops, from the QOI specification 1.0 (qoiformat.org). local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 local Codec = {} local index = buffer.create(256) --- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) @native function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) buffer.fill(index, 0, 0, 256) local r, g, bl, a = 0, 0, 0, 255 @@ -136431,7 +134555,6 @@ local index = buffer.create(256) return true, nil end --- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes @native function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number buffer.fill(index, 0, 0, 256) local pr, pg, pb, pa = 0, 0, 0, 255 @@ -136502,12 +134625,9 @@ return Codec end __FILES["image/sgi"] = function() --- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" --- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) --- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 --- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is --- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / --- colour-map files (colormap field 1..3: UNSUPPORTED). +-- image/sgi: Silicon Graphics images (Paul Haeberli's "The SGI Image File Format" 1.00). Supports: verbatim and RLE, 1 +-- / 2 bytes per channel, 1..4 channels, dimension 1..3, bottom-up rows, the image name; writes RGB(A) 8 / 16-bit. Not +-- supported: dithered / screen / colour-map files (colormap 1..3). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -136527,12 +134647,12 @@ local Sgi = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- rgba16 for 2-byte files (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - rle: boolean?, -- RLE storage (default true) - name: string?, -- the image name (up to 79 bytes; default meta.text.name) + rle: boolean?, -- default true + name: string?, -- up to 79 bytes; default meta.text.name } local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 @@ -136582,7 +134702,7 @@ function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel planes as 16-bit samples (8-bit values scaled * 257) + -- 8-bit values scaled * 257 local plane = buffer.create(w * h * z * 2) local truncated = false local function put(c: number, row: number, x: number, v: number) @@ -136790,12 +134910,9 @@ return Sgi end __FILES["image/sunras"] = function() --- image/sunras: Sun Raster (rasterfile(5), SunOS ; new code). Decode: 1-bit (0 = white without a colour --- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, --- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in --- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the --- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), --- raw colour maps (RMT_RAW is ignored). +-- image/sunras: Sun Raster (rasterfile(5), SunOS ). Supports: 1-bit (0 = white without a colour map), +-- 8-bit, 24 / 32-bit BGR / XBGR (RT_STANDARD, RT_OLD, RT_BYTE_ENCODED) or RGB / XRGB (RT_FORMAT_RGB), 0x80 RLE, 16-bit +-- row padding; 32-bit X is alpha unless all zero. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF, RMT_RAW. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -136816,10 +134933,10 @@ local Sunras = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD + rle: boolean?, -- default true; false: RT_STANDARD } local MAGIC = "\89\166\106\149" @@ -137039,15 +135156,9 @@ return Sunras end __FILES["image/tga"] = function() --- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) --- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / --- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, --- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: --- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data --- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. --- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left --- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage --- stamp, ...), which are ignored. +-- image/tga: Truevision TGA (TGA 2.0 specification). Supports: types 1 / 2 / 3 and RLE 9 / 10 / 11, 8..32-bit pixels +-- and colour maps, every origin, descriptor alpha bits (16-bit: only when 1 alpha bit is declared), the image ID, the +-- 2.0 footer. Not supported: the extension area's fields (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137067,14 +135178,14 @@ local Tga = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - rle: boolean?, -- run-length encode (default false) - origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands) - alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255) - id: string?, -- the image ID field (up to 255 bytes; default meta.text.id) + rle: boolean?, -- default false + origin: ("bottom-left" | "top-left")?, -- default "bottom-left" + alpha: boolean?, -- default: 32-bit when any alpha < 255 + id: string?, -- up to 255 bytes; default meta.text.id } -- ------------------------------------------------------------------------------------------------ constants @@ -137119,7 +135230,6 @@ local function header(r: Bytes.Reader): Header? return h end --- plausible(h) -> nil | why not local function implausible(h: Header): string? local t = h.imageType if not TYPES[t] then @@ -137181,7 +135291,6 @@ function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local p = r.base + 18 local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil p += h.idLen - -- colour map local pal = buffer.create(4) local palN = 0 if h.cmapType == 1 and h.cmapLen > 0 then @@ -137319,15 +135428,12 @@ __FILES["image/tga/Codec"] = @native function() --- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 --- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented --- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +-- image/tga/Codec: Truevision TGA 2.0 pixel loops: raw / RLE (packets may cross scanlines on read, never on write). local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local Codec = {} --- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, --- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +-- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 @native local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number if kind == 0 then return readu8(b, p) * 0x10101 + 0xFF000000 @@ -137351,7 +135457,6 @@ local Codec = {} end Codec.pixel = pixel --- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? @native function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) local n = w * h local i = 0 @@ -137403,9 +135508,6 @@ Codec.pixel = pixel return i, false end --- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); --- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. --- out needs room for w * h * (outBpp + 1) bytes. @native function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number @native local function get(q: number): number if srcBpp == 1 then @@ -137476,17 +135578,9 @@ return Codec end __FILES["image/tiff"] = function() --- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. --- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / --- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's --- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), --- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, --- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as --- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard --- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). --- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / --- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. --- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. +-- image/tiff: TIFF 6.0 (+ Adobe technote 3, BigTIFF). Supports: strips, tiles, planar 1 / 2, none / LZW (old-style too) +-- / Deflate (8, 32946) / PackBits / JPEG (7), predictors 2 / 3, int / float samples, CMYK (naive), fill order 2. Not +-- supported: old-style JPEG (6), CCITT (2, 3, 4), YCbCr, CIELab, JBIG. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137509,16 +135603,16 @@ local Tiff = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8 - maxPixels: number?, -- per page (default 2^26) - maxPages: number?, -- pages decoded into img.frames (default 1024) - page: number?, -- decode only this page (1-based) - decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- per page, default 2^26 + maxPages: number?, -- default 1024 + page: number?, -- 1-based + decodeImage: ((buffer) -> (any, any))?, } type EncodeOptions = { compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate" - predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true) - level: number?, -- deflate level 0..9 (default 6) + predictor: boolean?, -- default true + level: number?, -- 0..9, default 6 rowsPerStrip: number?, -- default: about 64 KB per strip } @@ -137567,7 +135661,6 @@ local function off(c: Ctx, at: number): number return if c.big then u64(c, at) else u32(c, at) end --- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many local function values(c: Ctx, e: Entry?, max: number?): { number }? if not e then return nil @@ -137632,7 +135725,6 @@ local function one(c: Ctx, e: Entry?, default: number): number return if v and v[1] then v[1] else default end --- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?) local esize = if c.big then 20 else 12 local hsize = if c.big then 8 else 2 @@ -137680,7 +135772,6 @@ local function bytesOf(c: Ctx, e: Entry?, max: number): buffer? return x end --- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?) if p < c.base or len < 0 or p + len > c.limit then -- a chunk past the end: keep what exists (truncated files) @@ -137785,10 +135876,10 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): if ch > h and not tiled then ch = h end - local pspp = if chunky then spp else 1 -- samples per pixel in one plane + local pspp = if chunky then spp else 1 local nplanes = if chunky then 1 else spp - local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane - local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + local rb = math.ceil(w * pspp * bps / 8) + local crb = math.ceil(cw * pspp * bps / 8) if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") end @@ -137859,7 +135950,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) end - -- into the plane local plane = planes[pl + 1] local x0b = math.floor(tx * cw * pspp * bps / 8) local cols = math.min(cw, w - tx * cw) @@ -137879,7 +135969,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): le = true -- fpAcc leaves the samples little endian end local colorType = PHOTOMETRIC[photo] - -- the output layout local kind = "rgba8" if opts and opts.native and comp ~= 7 then if photo == 3 or photo == 5 then @@ -137983,7 +136072,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): return img, nil end --- pages(r) -> the IFD tables of every page (and the context) | nil, Err local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < 8 then @@ -138028,7 +136116,6 @@ local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } return list, c, nil end --- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?) local list, c, err = pages(r, 1024) if not list or not c then @@ -138094,7 +136181,6 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- layout per pixel format: samples, bits, sample format, photometric, extra samples local LAYOUT = { gray8 = { 1, 8, 1, 1 }, graya8 = { 2, 8, 1, 1 }, @@ -138241,7 +136327,6 @@ function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? if not tags or not strips then return nil, err end - -- strip data first local soffs = {} for i, s in strips do if w:tell() % 2 == 1 then @@ -138322,10 +136407,7 @@ __FILES["image/tiff/Pixels"] = @native function() --- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and --- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's --- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. --- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +-- image/tiff/Pixels: TIFF predictors 2 / 3 (TIFF 6.0 section 14, technote 3; 3 as libtiff fpAcc / fpDiff). local Bytes = __include("core/Bytes") local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 @@ -138336,8 +136418,7 @@ local Pixels = {} local scratch = buffer.create(8) --- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an --- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +-- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads @native local function f32(bits: number): number if band(bits, 0x7F800000) == 0x7F800000 then if band(bits, 0x7FFFFF) ~= 0 then @@ -138380,7 +136461,6 @@ end end -- ------------------------------------------------------------------------------------------------ predictors --- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) @native function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) for r = 0, rows - 1 do local base = off + r * rb @@ -138416,7 +136496,6 @@ end end end --- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) @native function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) for r = 0, rows - 1 do local base = off + r * rb @@ -138433,8 +136512,7 @@ end end end --- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little --- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +-- the samples come out little endian whatever the file's byte order (libtiff fpAcc) @native function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do @@ -138451,7 +136529,6 @@ end end end --- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) @native function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do @@ -138473,7 +136550,7 @@ local half = Bytes.half type Params = { planes: { buffer }, - rb: number, -- bytes per row in each plane + rb: number, chunky: boolean, w: number, h: number, @@ -138482,14 +136559,13 @@ type Params = { sfmt: number, -- 1 uint, 2 int, 3 float le: boolean, photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK - alpha: number, -- sample index of the alpha channel, -1 = none + alpha: number, assoc: boolean, -- premultiplied alpha (undone) cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block) - kind: string, -- the output pixel format + kind: string, out: buffer, } --- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them @native local function fast(P: Params): boolean if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then return false @@ -138539,7 +136615,6 @@ type Params = { return false end --- convert(P): every pixel into P.out in P.kind's layout @native function Pixels.convert(P: Params) if fast(P) then return @@ -138550,7 +136625,6 @@ end local float = sfmt == 3 local signed = sfmt == 2 local cmapN = 2 ^ math.min(bps, 16) - -- raw sample s of pixel x in the row starting at byte ro of its plane @native local function raw(s: number, x: number, row: number): number local b, i if chunky then @@ -138721,15 +136795,9 @@ return Pixels end __FILES["image/tim"] = function() --- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation --- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. --- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit --- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 --- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when --- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. --- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image --- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque --- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. +-- image/tim: PlayStation TIM (magic 0x10), from Sony's PSX "File Formats" documentation. Supports: 4 / 8-bit CLUT, 15 / +-- 24-bit direct; colours are 1-5-5-5 STP-B-G-R, expanded (v << 3) | (v >> 2), 0x0000 transparent as on the hardware, +-- opaque black written as 0x8000. Not supported: mixed mode (pmode 4). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -138748,14 +136816,14 @@ local Tim = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - clut: number?, -- the CLUT row to use for indexed images (0-based, default 0) + clut: number?, -- 0-based, default 0 maxPixels: number?, -- default 2^26 } type EncodeOptions = { bpp: number?, -- 4, 8, 16 (default) or 24 - x: number?, -- VRAM position of the image (default 0, 0) + x: number?, -- default 0, 0 y: number?, - clutX: number?, -- VRAM position of the CLUT (default 0, 480) + clutX: number?, -- default 0, 480 clutY: number?, } @@ -138882,7 +136950,6 @@ function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- rgba8 pixel -> PSX colour local function psx(v: number): number local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216 if a < 128 then @@ -138970,18 +137037,9 @@ return Tim end __FILES["image/vtf"] = function() --- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer --- Community "VTF (Valve Texture Format)" page; no code taken. --- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail --- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image --- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to --- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure --- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, --- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through --- codecs/image/Texel), DXT1 (+ one-bit alpha), --- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, --- texel, reflectivity, bumpScale }. --- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. +-- image/vtf: Valve Texture Format 7.0 - 7.5 (Source engine), from the Valve Developer Community VTF page. Supports: the +-- high-resolution image, mips / faces / slices / frames, uncompressed texels, DXT1 / DXT3 / DXT5, ATI1N / ATI2N (35 / +-- 34 Alien Swarm, 38 / 37 Source 2013). Not supported: P8, Strata / Source 2 formats, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -139002,17 +137060,16 @@ local Vtf = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - mip: number?, -- mip level (0 = full size, default) - face: number?, -- cube map face (0-based, default 0) - slice: number?, -- volume slice (0-based, default 0) - frames: boolean?, -- decode every frame into img.frames (default true) - delay: number?, -- frame delay in seconds (default 0.1) + mip: number?, -- 0 = full size, default + face: number?, -- 0-based, default 0 + slice: number?, -- 0-based, default 0 + frames: boolean?, -- default true + delay: number?, -- seconds, default 0.1 maxPixels: number?, -- default 2^26 } -- ------------------------------------------------------------------------------------------------ constants local M = Texel.masked --- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind local FORMATS: { [number]: any } = { [0] = "rgba8", -- RGBA8888 [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 @@ -139061,7 +137118,6 @@ function Vtf.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- bytes of one w x h image in format f local function imageSize(f: any, w: number, h: number): number if type(f) == "string" and BCN[f] then return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0 @@ -139133,7 +137189,6 @@ function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0 dataAt = headerSize + lowSize end - -- the chain: mips smallest first; per mip: frames, faces, slices local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) @@ -139217,20 +137272,9 @@ return Vtf end __FILES["image/webp"] = function() --- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 --- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the --- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. --- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw --- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the --- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or --- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif --- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and --- metadata). --- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does), --- alpha dithering / premultiplied output. --- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s --- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). --- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. +-- image/webp: WebP (RFC 9649); bitstreams ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +-- Supports: VP8 key frames (bit-exact with dwebp), VP8L, ALPH, VP8X, ANIM / ANMF, ICC / EXIF / XMP; writes VP8L. Not +-- supported: lossy encoding, VP8 scale fields (ignored, as dwebp), alpha dithering. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -139254,21 +137298,19 @@ local Webp = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) - native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8) - upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" = - -- dwebp -nofancy) - coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none", - -- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle) - frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas) + maxPixels: number?, -- default 2^26 + native: boolean?, -- default false: rgba8 + upsampling: ("fancy" | "nearest")?, -- default "fancy" (libwebp's; "nearest" = dwebp -nofancy) + coalesce: boolean?, -- default false: each frame's own rectangle + frames: boolean?, -- default true } type EncodeOptions = { - lossless: boolean?, -- must be true or nil (lossy encoding is not supported) - effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower) - exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed) - loops: number?, -- animations: play count (default img.loops; 0 = forever) - background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0) + lossless: boolean?, -- true or nil + effort: number?, -- 0..9, default 5 + exact: boolean?, -- default false + loops: number?, -- default img.loops; 0 = forever + background: { number }?, -- default meta.background or 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -139285,7 +137327,6 @@ local function corrupt(msg: string, offset: number?): (nil, Err.Err) return nil, Err.new(Err.CORRUPT, msg, offset) end --- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT) local function fromMessage(msg: any, offset: number?): Err.Err if Err.is(msg) then return msg @@ -139321,8 +137362,7 @@ local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?) return out, nil end --- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size --- must fit the data (TRUNCATED) and bytes after it are ignored. +-- as libwebp: the RIFF size must fit the data and bytes after it are ignored local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) local buf, base, limit = r.buf, r.base, r.limit if limit - base < 12 then @@ -139349,7 +137389,6 @@ local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) return list, f end --- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) local n = c.size - 12 return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) @@ -139592,7 +137631,6 @@ function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. return img, nil end --- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err function Webp.info(r: Bytes.Reader): (any, Err.Err?) local chunks, cerr = readChunks(r) if not chunks then @@ -139817,8 +137855,6 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? end -- ------------------------------------------------------------------------------------------------ extras --- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way --- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) function Webp.coalesce(img: Types.Image): { buffer }? if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil @@ -139847,9 +137883,8 @@ end __FILES["image/webp/Alpha"] = @native function() --- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), --- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / --- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). local Vp8L = __include("codecs/image/Vp8L") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -139889,7 +137924,6 @@ local Alpha = {} end end --- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message @native function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) if len <= 1 then return nil, "truncated: ALPH chunk" @@ -139925,11 +137959,8 @@ end __FILES["image/webp/Anim"] = @native function() --- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c, --- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour --- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha --- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the --- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws. +-- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt): the background colour is ignored, as the spec recommends. local band, rshift = bit32.band, bit32.rshift local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill @@ -139937,18 +137968,18 @@ local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill local Anim = {} type Frame = { - rgba: buffer, -- w * h rgba8 + rgba: buffer, x: number, y: number, w: number, h: number, - blend: boolean, -- alpha-blend over the canvas (false: overwrite) - disposeBg: boolean, -- after display, clear the rectangle to transparent - disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only) + blend: boolean, + disposeBg: boolean, + disposePrev: boolean?, -- composite() only hasAlpha: boolean, } --- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult) +-- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult @native local function blendPixel(src: number, dst: number): number local sa = rshift(src, 24) if sa == 0 then @@ -139965,7 +137996,6 @@ type Frame = { end Anim.blendPixel = blendPixel --- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets) @native local function blendRow(cur: buffer, prev: buffer, o: number, n: number) for i = o, o + n - 1 do local s = readu32(cur, i * 4) @@ -139975,7 +138005,6 @@ Anim.blendPixel = blendPixel end end --- draw(canvas, cw, f): copy the frame rectangle into the canvas @native local function draw(canvas: buffer, cw: number, f: Frame) for j = 0, f.h - 1 do bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) @@ -139988,7 +138017,6 @@ end end end --- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them @native function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local out: { buffer } = {} @@ -140047,9 +138075,6 @@ end return out end --- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or --- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle; --- previous: restore) @native function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local canvas = bcreate(size) @@ -140088,10 +138113,8 @@ return Anim end __FILES["image/xbm"] = function() --- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height --- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, --- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below --- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant). Supports: _width / _height / _x_hot / _y_hot +-- defines, char / short arrays in hex, decimal or octal, LSB first, set bits black; writes X11 format. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -140111,12 +138134,12 @@ local Xbm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - transparent: boolean?, -- clear bits transparent (default false: white) - maxPixels: number?, -- refuse larger images (default 2^26) + transparent: boolean?, -- default false: white + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _) - threshold: number?, -- luminance below this is black (default 128) + name: string?, -- default "image" + threshold: number?, -- default 128 } -- ------------------------------------------------------------------------------------------------ sniff @@ -140209,7 +138232,6 @@ function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name @@ -140252,12 +138274,9 @@ return Xbm end __FILES["image/xpm"] = function() --- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: --- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / --- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour --- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in --- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, --- the fewest chars per pixel; opts.name (default "image"). +-- image/xpm: X PixMap (XPM 3 C source and XPM 2 plain; Arnaud Le Hors's "XPM Manual"). Supports: the values line and +-- hotspot, c / g / g4 / m / s keys (c preferred, then g, g4, m), #RGB .. #RRRRGGGGBBBB, None, colour names (unknown: +-- black); writes XPM 3 with hex colours. Not supported: the extensions section (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -140278,10 +138297,10 @@ local Xpm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } type EncodeOptions = { - name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _) + name: string?, -- default "image" } -- the characters of pixel codes (printable ASCII without '"' and '\') @@ -140297,7 +138316,6 @@ function Xpm.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- colour value -> rgba8 u32, or nil for an unknown name local function colour(v: string): number? local l = string.lower(v) if l == "none" or l == "transparent" then @@ -140322,7 +138340,6 @@ local function colour(v: string): number? return if rgb then rgb + 0xFF000000 else nil end --- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) local function strings(s: string): { string } local out = {} if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then @@ -140467,7 +138484,6 @@ function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name @@ -140526,9 +138542,7 @@ return Xpm end __FILES["image/xpm/Names"] = function() --- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's --- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. --- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +-- image/xpm/Names: CSS Color 4 named colours with X11's values where they differ, and grey0 .. grey100. local Names = {} local HEX: { [string]: number } = { @@ -140564,7 +138578,6 @@ local HEX: { [string]: number } = { violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, } --- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) function Names.lookup(name: string): number? local v = HEX[name] if v then @@ -140585,19 +138598,9 @@ return Names end __FILES["layered/aseprite"] = function() --- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, --- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every --- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, --- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to --- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old --- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and --- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, --- delay }. --- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk --- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, --- palette, tags. --- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour --- profiles (sRGB assumed). +-- layered/aseprite: Aseprite .ase / .aseprite (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA / grayscale / +-- indexed, frames, layer tree (groups, blend, opacity), raw / zlib / linked cels, palettes (0x2019, 0x0004 / 0x0011), +-- tags, user data. Not supported: tilemaps / tilesets (meta.skipped), slices, external files, colour profiles (sRGB). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -140616,13 +138619,12 @@ local Aseprite = { } type DecodeOptions = { - maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26) + maxPixels: number?, -- default 2^26 maxFrames: number?, -- default 65535 } type EncodeOptions = { - depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if - -- the pixels fit it, else 32 - level: number?, -- zlib level for the cels (default 6) + depth: number?, -- 32, 16 or 8; default meta.colorDepth if the pixels fit, else 32 + level: number?, -- default 6 } -- ------------------------------------------------------------------------------------------------ constants @@ -140653,7 +138655,6 @@ local function str(r: Bytes.Reader): string return r:string(r:u16le()) end --- cel pixels (depth bytes per pixel) -> rgba8 local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer local out = buffer.create(n * 4) if depth == 32 then @@ -140717,8 +138718,8 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? local tags: { any } = {} local frames: { { cels: { [number]: any }, delay: number } } = {} local skipped = 0 - local lastUser: any = nil -- the object the next user data chunk belongs to - local tagUser = 0 -- tags waiting for their user data chunks + local lastUser: any = nil + local tagUser = 0 for fi = 1, nframes do local fstart = r.pos local fbytes = r:u32le() @@ -140910,10 +138911,9 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? r.pos = fstart + fbytes end local _ = ncolors - -- the layer tree of one frame local function build(fi: number): { Types.Layer } local root: { Types.Layer } = {} - local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level + local stack: { { Types.Layer } } = { root } for li, info in infos do local level = math.min(info.level, #stack - 1) local list = stack[level + 1] @@ -140939,7 +138939,6 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? l.opacity = 1 end table.insert(list, l) - -- deeper layers go into this group for k = #stack, level + 2, -1 do stack[k] = nil end @@ -140978,9 +138977,8 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? end return root end - -- cel images (shared by linked cels) for _, f in frames do - for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + for li, cel in pairs(f.cels) do if cel.raw then local info = infos[li] local img = Types.Image.new(cel.w, cel.h) @@ -141056,7 +139054,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? end local meta: any = if type(layered.meta) == "table" then layered.meta else {} local level = opts and opts.level or 6 - -- frames: the layered frames, or one frame of the layers local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } } local struct: { Node } = {} if not nodes(frameList[1].layers, 0, struct) then @@ -141084,7 +139081,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? end perFrame[fi] = ns end - -- the colour depth: requested, or the source's when every pixel fits local depth = opts and opts.depth or meta.colorDepth or 32 local explicit = opts ~= nil and opts.depth ~= nil if depth ~= 32 and depth ~= 16 and depth ~= 8 then @@ -141200,7 +139196,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? chunk(fw, 0x2020, c) return 1 end - -- where each (layer, frame) cel's image was first written: linked cels local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {} for fi, f in frameList do local fw = Bytes.writer(4096) @@ -141341,15 +139336,9 @@ return Aseprite end __FILES["layered/ora"] = function() --- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with --- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. --- Decode: the stack tree (nested = groups: isolation="auto" is passThrough; name / src / x / y / --- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), --- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: --- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) --- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to --- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the / / --- elements (ignored). +-- layered/ora: OpenRaster 0.0.6 (freedesktop.org; new code): a zip with a stored "mimetype" first, stack.xml, PNG +-- layers, mergedimage.png, Thumbnails/thumbnail.png. Supports: nested stacks (isolation="auto" = passThrough), layer +-- attributes, svg:* ops; PNGs via opts.decodeImage / encodeImage. Not supported: non-PNG sources, / . -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -141371,14 +139360,14 @@ local Ora = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one) - composite: boolean?, -- decode mergedimage.png into meta.composite (default true) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + composite: boolean?, -- default true maxLayers: number?, -- default 10000 } type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one) - composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend) - thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + composite: Types.Image?, -- default: the layers flattened + thumbnail: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -141452,7 +139441,7 @@ function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err end return img, nil end - -- a 's children, top first in the file -> bottom to top + -- stack.xml lists a 's children top first local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?) local out: { Types.Layer } = {} for _, ch in node.children do @@ -141521,7 +139510,6 @@ function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err end -- ------------------------------------------------------------------------------------------------ encode --- nearest-neighbour downscale to fit max x max local function thumbnail(img: Types.Image, max: number): Types.Image local w, h = img.width, img.height local s = math.min(1, max / math.max(w, h)) @@ -141560,7 +139548,6 @@ function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err end return data, nil end - -- layers bottom to top -> xml children top first local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?) local kids = {} for i = #layers, 1, -1 do @@ -141636,17 +139623,9 @@ return Ora end __FILES["layered/psd"] = function() --- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of --- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers --- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, --- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / --- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image --- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. --- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend --- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, --- clipping, opacity / fill, hidden flags and Unicode names. --- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer --- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. +-- layered/psd: Adobe Photoshop PSD / PSB (Photoshop File Formats Specification, 2016). Supports: every colour mode at +-- 1 / 8 / 16 / 32 bits, layers (RLE / ZIP channels, Lr16 / Lr32, iOpa, luni, masks, lsct groups), the merged image, +-- resources; encode: 8-bit RGB. Not supported: adjustment / type / smart-object contents, effects, vector masks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -141667,12 +139646,12 @@ local Psd = { } type DecodeOptions = { - layers: boolean?, -- read the layers (default true; false reads only the merged image) - maxPixels: number?, -- refuse documents / layers larger than this (default 2^26) + layers: boolean?, -- default true (false: the merged image only) + maxPixels: number?, -- default 2^26 maxLayers: number?, -- default 10000 } type EncodeOptions = { - composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend) + composite: Types.Image?, -- default: the layers flattened } -- ------------------------------------------------------------------------------------------------ constants @@ -141738,7 +139717,6 @@ local function utf16be(s: string): string return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) end --- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?) local count = r:i16be() local absAlpha = count < 0 @@ -141862,7 +139840,7 @@ local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Er end end if ch.size < 2 then - continue -- an empty channel + continue end local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) if not plane then @@ -141888,7 +139866,6 @@ local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Er return recs, absAlpha, nil end --- records (bottom to top) -> a layer tree local function tree(recs: { any }): { Types.Layer } local root: { Types.Layer } = {} local stack: { { Types.Layer } } = {} @@ -142104,7 +140081,7 @@ function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err planes[k] = plane end elseif comp == 2 or comp == 3 then - -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + -- Photoshop writes all channels in one zlib stream local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) if not all then return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) @@ -142382,10 +140359,8 @@ end __FILES["layered/psd/Channels"] = @native function() --- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a --- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the --- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". --- Never throws: every read is range-checked first; failures return nil, "message". +-- layered/psd/Channels: PSD / PSB channel data (Photoshop File Formats Specification 2016, "Channel image data" / +-- "Image data section"): raw, PackBits RLE, ZIP, ZIP with prediction; colour modes to rgba8; PackBits rows. local Deflate = __include("codecs/compress/Deflate") local PackBits = __include("codecs/compress/PackBits") @@ -142396,7 +140371,6 @@ local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.wr local floor, min, max = math.floor, math.min, math.max local byteswap = bit32.byteswap --- rowBytes(w, depth) -> bytes per row of one channel @native function Channels.rowBytes(w: number, depth: number): number if depth == 1 then return (w + 7) // 8 @@ -142404,7 +140378,6 @@ local byteswap = bit32.byteswap return w * (depth // 8) end --- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil @native function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) local size = if psb then 4 else 2 if rows < 0 or p + rows * size > limit then @@ -142422,7 +140395,6 @@ end return counts, p end --- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message @native function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) for i = 0, rows - 1 do local c = counts[first + i] or 0 @@ -142439,7 +140411,6 @@ end return p, nil end --- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place @native local function unpredict(plane: buffer, w: number, h: number, depth: number) if depth == 8 then for y = 0, h - 1 do @@ -142483,8 +140454,6 @@ end end end --- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the --- 2-byte compression code and the data of one layer channel. @native function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) local rb = Channels.rowBytes(w, depth) local plane = bcreate(rb * h) @@ -142525,31 +140494,29 @@ end return plane, nil end --- sample8(plane, i, depth) -> sample i as 0..255 @native local function sample8(plane: buffer, i: number, depth: number): number if depth == 8 then return readu8(plane, i) elseif depth == 16 then return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) elseif depth == 32 then - local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + local f = readf32(plane, i * 4) if f ~= f then return 0 end return floor(max(0, min(1, f)) * 255 + 0.5) end - -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + -- 1-bit: 1 = black (whole-byte widths only; toRGBA reads bitmaps itself) return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 end --- swap32(plane): big-endian f32 samples to native order, in place @native function Channels.swap32(plane: buffer) for i = 0, blen(plane) // 4 - 1 do writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) end end --- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +-- PSD Lab (0..255 each) to sRGB, the D50 white approximated by D65 @native local function srgb(c: number): number c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 return floor(max(0, min(1, c)) * 255 + 0.5) @@ -142570,8 +140537,7 @@ end return srgb(r), srgb(g), srgb(bl) end --- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } --- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +-- PSD colour modes: 0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab @native function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer local n = w * h local out = bcreate(n * 4) @@ -142579,7 +140545,6 @@ end local alpha = planes.alpha local bitmapW = (w + 7) // 8 if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then - -- the common case, without a call per sample local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1 local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1 local a8 = if alpha and blen(alpha) >= n then alpha else nil @@ -142632,7 +140597,6 @@ end return out end --- gray8(plane, w, h, depth) -> 1 byte per pixel @native function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer local n = w * h local out = bcreate(n) @@ -142659,7 +140623,6 @@ end end end --- matte(rgba, n) -> a copy matted with white (the writer's merged image) @native function Channels.matte(rgba: buffer, n: number): buffer local out = bcreate(n * 4) bcopy(out, 0, rgba, 0, n * 4) @@ -142677,12 +140640,10 @@ end end -- ------------------------------------------------------------------------------------------------ writer helpers --- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) @native function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number local start = d local i = 0 while i < n do - -- a run of at least 3 equal bytes? local v = readu8(src, o + i) local run = 1 while i + run < n and run < 128 and readu8(src, o + i + run) == v do @@ -142694,7 +140655,6 @@ end d += 2 i += run else - -- literals up to the next run of 3 local j = i while j < n and j - i < 128 do if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then @@ -142712,7 +140672,6 @@ end return d - start end --- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) @native function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) local n = w * h local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) @@ -142729,7 +140688,6 @@ end return r, g, b, a end --- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code @native function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer local cs = if psb then 4 else 2 local out = bcreate(h * cs + h * (w + w // 128 + 2)) @@ -142752,27 +140710,9 @@ return Channels end __FILES["model/3ds"] = function() --- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the --- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference --- for transforms and conventions; no code ported) and lib3ds (layouts only). --- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, --- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and --- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials --- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, --- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as --- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / --- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the --- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), --- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, --- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / --- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from --- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects --- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not --- applied), the keyframer frame range. --- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first --- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural --- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on --- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). +-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3, +-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer. +-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -142794,16 +140734,16 @@ local ThreeDs = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) - flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) - fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) - maxVertices: number?, -- refuse more vertices in total (default 2^24) + normals: boolean?, -- default true + flipV: boolean?, -- default true + fps: number?, -- default 30 (3ds Max's default) + maxVertices: number?, -- default 2^24 } type EncodeOptions = { - flipV: boolean?, -- default true (the inverse of decode) - fps: number?, -- seconds -> keyframer frames (default 30) - name: string?, -- the destination's file name (names textures that have no uri) - files: { [string]: any }?, -- receives the bytes of textures that have data but no uri + flipV: boolean?, -- default true + fps: number?, -- default 30 + name: string?, + files: { [string]: any }?, -- receives the bytes of textures with data but no uri } -- ------------------------------------------------------------------------------------------------ sniff @@ -142827,7 +140767,6 @@ function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, E if not raw then return nil, Err.from(msg, at) end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene = pcall(Build.scene, raw, opts :: any) if not ok then return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) @@ -142854,13 +140793,11 @@ return ThreeDs end __FILES["model/3ds/Build"] = function() --- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world --- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * --- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix --- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key --- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's --- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position --- are averaged; group 0 is flat). Times are frame / fps. +-- model/3ds/Build: Read's chunk tables -> Types.Scene. +-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a +-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix) +-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle +-- deltas from the previous key. Smoothing group 0 is flat. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Read = __include("model/3ds/Read") @@ -142875,7 +140812,6 @@ local sqrt, abs = math.sqrt, math.abs type Options = { normals: boolean?, flipV: boolean?, fps: number? } -- ------------------------------------------------------------------------------------------------ math --- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 local function meshMatrix(m: { number }?): { number } if not m then return Mat4.identity() @@ -142889,7 +140825,6 @@ local function det3(m: { number }): number end Build.det3 = det3 --- q(a) * q(b) local function qmul(a: { number }, b: { number }): { number } local ax, ay, az, aw = a[1], a[2], a[3], a[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] @@ -142902,7 +140837,7 @@ local function qmul(a: { number }, b: { number }): { number } end Build.qmul = qmul --- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +-- 3DS angles turn clockwise local function keyQuat(angle: number, x: number, y: number, z: number): { number } if x == 0 and y == 0 and z == 0 then return { 0, 0, 0, 1 } @@ -142918,7 +140853,7 @@ local function normalize(x: number, y: number, z: number): (number, number, numb return x / l, y / l, z / l, l end --- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +-- -Z looks from pos to target, world up +Z function Build.lookAt(p: { number }, t: { number }, roll: number): { number } local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) if l == 0 then @@ -142928,7 +140863,6 @@ function Build.lookAt(p: { number }, t: { number }, roll: number): { number } if abs(fz) > 0.999999 then ux, uy, uz = 0, 1, 0 end - -- right = forward x up, up = right x forward local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx local a = math.rad(roll) @@ -143018,18 +140952,14 @@ local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number end -- ------------------------------------------------------------------------------------------------ meshes --- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved --- by xf (world -> the node's local space) local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh local nv, nf = m.nv, m.nf local pos, faces = m.positions, m.faces - -- local positions local lp = table.create(nv * 3, 0) for v = 0, nv - 1 do local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z end - -- faces with valid corners, their materials local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) local valid = table.create(nf, false) for f = 0, nf - 1 do @@ -143048,7 +140978,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end local smooth = m.smoothing local doNormals = opts.normals ~= false - -- face normals (area weighted) and the faces around each distinct position local fn = table.create(nf * 3, 0) local around: { [number]: { number } } = {} local group = table.create(nv, 0) @@ -143103,7 +141032,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st local nx, ny, nz = normalize(x, y, z) return nx, ny, nz end - -- primitives in the order their material first appears local order: { number } = {} local byMat: { [number]: { number } } = {} for f = 1, nf do @@ -143176,7 +141104,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end -- ------------------------------------------------------------------------------------------------ tracks --- the value of a track at a frame (linear between keys, clamped at the ends) local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } if not t or #t.frames == 0 then return default @@ -143214,7 +141141,6 @@ local function scaleKey(v: { number }): { number } return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } end --- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys local function rotations(t: Read.Track): ({ number }, { { number } }) local frames, quats = {}, {} local acc: { number }? = nil @@ -143251,7 +141177,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local fps = o.fps or 30 local scene = S.new() local matByName = materials(raw, scene) - -- objects by name local objByName: { [string]: Read.Object } = {} for _, obj in raw.objects do if objByName[obj.name] == nil then @@ -143333,7 +141258,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local kf = raw.keyframer local kfNodes = if kf then kf.nodes else {} - -- targets of cameras / spotlights by name local targets: { [string]: Read.Node } = {} for _, n in kfNodes do if n.kind == "target" or n.kind == "lightTarget" then @@ -143341,7 +141265,7 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end local placedObj: { [Read.Object]: boolean } = {} - local sceneOf: { [number]: number } = {} -- kf id -> scene node + local sceneOf: { [number]: number } = {} local channels: { Types.Channel } = {} local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) for i = 1, #times do @@ -143406,7 +141330,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) end else - -- cameras and lights: position, target, roll local isCam = kind == "camera" local cam = if obj and isCam then obj.camera else nil local lit = if obj and not isCam then obj.light else nil @@ -143436,7 +141359,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end local ni = addNode(node, parent) sceneOf[id] = ni - -- every key time of the position, roll and target tracks local set: { [number]: boolean } = {} local times: { number } = {} for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do @@ -143467,7 +141389,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end end - -- objects the keyframer does not place (or files without one): at their own matrix / position for _, obj in raw.objects do if placedObj[obj] then continue @@ -143519,12 +141440,8 @@ return Build end __FILES["model/3ds/Read"] = function() --- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read --- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their --- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes --- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). --- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is --- clipped to the parent. Never throws on bad data: returns nil, message, offset. +-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables. +-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it. local Read = {} local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 @@ -143548,17 +141465,14 @@ local C = { } Read.C = C --- material map chunks -> their name in Raw materials Read.MAPS = { [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", } --- keyframer node chunks -> kind local NODE_KINDS = { [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", [0xB006] = "lightTarget", [0xB007] = "spot", } --- track chunks -> (field, values per key) local TRACKS: { [number]: { any } } = { [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, @@ -143579,7 +141493,7 @@ type Mesh = { nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers smoothing: buffer?, -- nf u32 - matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) + matrix: { number }?, -- 12 floats: X, Y, Z axes, origin (world space) } type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } type Light = { @@ -143602,13 +141516,12 @@ type Raw = { -- ------------------------------------------------------------------------------------------------ helpers type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } --- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) local b = ctx.b while p + 6 <= stop do local id, size = readu16(b, p), readu32(b, p + 2) if size < 6 then - return nil, nil -- padding or garbage after the last chunk + return nil, nil end local e = p + size if e > ctx.limit then @@ -143623,7 +141536,6 @@ local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, numb return nil, nil end --- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil local function cstring(b: buffer, p: number, stop: number): (string?, number) for q = p, stop - 1 do if readu8(b, q) == 0 then @@ -143637,7 +141549,7 @@ local function vec3(b: buffer, p: number): { number } return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } end --- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +-- colour chunks: the first float or byte colour (the gamma-corrected variants only when nothing else) local function color(ctx: Ctx, p: number, stop: number): { number }? local b = ctx.b local main: { number }?, lin: { number }? = nil, nil @@ -143662,7 +141574,6 @@ local function color(ctx: Ctx, p: number, stop: number): { number }? return main or lin end --- a percentage chunk list -> a fraction 0..1 local function percent(ctx: Ctx, p: number, stop: number): number? local b = ctx.b local v: number? = nil @@ -143992,7 +141903,6 @@ local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) end) end --- parse(b, base, limit, opts) -> Raw | nil, message, offset function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) if limit - base < 6 or readu16(b, base) ~= C.MAIN then return nil, "not a 3DS file (no 0x4D4D main chunk)", base @@ -144003,7 +141913,6 @@ function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, if size < 6 then return nil, "bad main chunk size", base end - -- a main chunk declared longer than the data: truncated if base + size > limit then return nil, "truncated: the main chunk runs past the end of the data", base end @@ -144027,15 +141936,8 @@ return Read end __FILES["model/3ds/Write"] = function() --- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world --- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's --- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 --- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with --- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and --- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in --- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key --- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. --- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does +-- (positive keyframer transform, mirror in the mesh matrix). local Bytes = __include("core/Bytes") local Types = __include("Types") local Sampler = __include("codecs/model/Sampler") @@ -144136,7 +142038,6 @@ local function unit(x: number, y: number, z: number): (number, number, number) return x / l, y / l, z / l end --- a quaternion -> the 3DS (clockwise angle, axis) local function axisAngle(q: { number }): (number, number, number, number) local x, y, z, w = q[1], q[2], q[3], q[4] local n = sqrt(x * x + y * y + z * z + w * w) @@ -144156,7 +142057,6 @@ local function conj(q: { number }): { number } return { -q[1], -q[2], -q[3], q[4] } end --- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) local function sample(ch: Types.Channel, t: number): { number } local f = Sampler.channel(ch) if not f then @@ -144219,7 +142119,6 @@ local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [n if x.wire then leaf(w, C.MAT_WIRE, function() end) end - -- maps: the PBR texture refs first, then the other kinds model/3ds read local maps: { [string]: any } = {} local function fromRef(ref: Types.TextureRef?, saved: any): any if not ref or not files[ref.texture] then @@ -144274,7 +142173,6 @@ end -- ------------------------------------------------------------------------------------------------ meshes type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } --- the mesh as 3DS parts (local space), or nil, message local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean return n == "TEXCOORD_0" or n == "NORMAL" @@ -144288,7 +142186,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, local tv, tc = if T then T.values else nil, if T then T.components else 0 local flipV = opts.flipV ~= false local corners = merged.corners - -- per face: material, smoothing group local nf = #corners // 3 local fmat, fsg = table.create(nf, 0), table.create(nf, 1) for _, part in merged.parts do @@ -144300,7 +142197,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, if savedOk then fsg[f] = saved[f - part.firstFace] elseif N then - -- flat when every corner normal is the face normal local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } @@ -144426,7 +142322,6 @@ local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: end -- ------------------------------------------------------------------------------------------------ cameras / lights --- the eye, target and roll of a node's world matrix (looking down -Z, Y up) local function aim(m: { number }, dist: number): ({ number }, { number }, number) local p = { m[13], m[14], m[15] } local fx, fy, fz = unit(-m[9], -m[10], -m[11]) @@ -144434,7 +142329,6 @@ local function aim(m: { number }, dist: number): ({ number }, { number }, number fx, fy, fz = 0, 0, -1 end local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } - -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis local q0 = Build.lookAt(p, t, 0) local m0 = Mat4.fromQuat(q0) local ux, uy, uz = unit(m[5], m[6], m[7]) @@ -144518,11 +142412,10 @@ local function writeTrack(w: W, id: number, frames: { number }, values: { number end type KfNode = { - chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + chunk: number, name: string, instance: string?, parent: number, -- kf index or -1 frames: { [string]: { number } }, values: { [string]: { number } }, } --- frames (rounded, strictly increasing) and the indices of the channel keys they keep local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) local IN = S.reader(ch.input) :: any local frames, keep = {}, {} @@ -144586,7 +142479,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MESH_VERSION, function() w:u32le(3) end) - -- materials (unique names) local files = textureFiles(scene, o) local matNames: { [number]: string } = {} local used: { [string]: boolean } = {} @@ -144606,7 +142498,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MASTER_SCALE, function() w:f32le(1) end) - -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) used = {} local firstNode: { [number]: number } = {} for _, i in order do @@ -144636,7 +142527,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) writeMesh(w, part, M, matNames) end end - -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors local KW: { [number]: { number } } = {} for _, i in order do local n = scene.nodes[i] @@ -144673,7 +142563,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } table.insert(kfs, kn) local idx = #kfs - -- animated root cameras / lights: position, target and roll at the key times local chs: any = if p == 0 then byNode[i] else nil local targetFrames, targetVals = { 0 }, tgt if chs and (chs.translation or chs.rotation) then @@ -144735,7 +142624,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end if onlyThis and idx then kfOf[i] = idx - -- the node's frame in the keyframer: the camera / light pose local kn = kfs[idx] local pos = kn.values.pos local m: { number } = W[i] @@ -144752,7 +142640,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(true) continue end - -- an object node (or a dummy) with the node's transform relative to its keyframer parent local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY local inv = Mat4.inverse(pkw) or Mat4.identity() local L = S.mul(inv, KW[i]) @@ -144761,7 +142648,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local objName = if plist then plist[1].name else "$$$DUMMY" local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } - -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) local chs = byNode[i] if chs then local own = S.nodeMatrix(n) @@ -144802,7 +142688,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(false) end close(w, ed) - -- the keyframer local kf = open(w, C.KEYFRAMER) leaf(w, C.KF_HDR, function() w:u16le(5) @@ -144856,23 +142741,9 @@ return Write end __FILES["model/3mf"] = function() --- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, --- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts --- (codecs/text/Xml). --- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from --- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices --- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata --- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours --- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to --- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it --- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first --- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices --- are split where a vertex's corners carry different colours / texture coordinates. --- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a --- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, --- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). --- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are --- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). +-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path). +-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups. +-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -144894,13 +142765,13 @@ local ThreeMf = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25) - maxNodes: number?, -- refuse more object instances (default 2^20) + maxVertices: number?, -- default 2^25 + maxNodes: number?, -- default 2^20 } type EncodeOptions = { unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else - -- millimeter); positions are scaled through the build transforms when meta.unit differs - level: number?, -- deflate level for the XML parts (default 6; 0 stores them) + -- millimeter) + level: number?, -- default 6; 0 stores } -- ------------------------------------------------------------------------------------------------ sniff @@ -144908,7 +142779,6 @@ function ThreeMf.sniff(r: Bytes.Reader): number if r:peek(4) ~= "PK\3\4" then return 0 end - -- the central directory sits at the end: look for the model part's name there, then at the start local n = r:size() local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then @@ -144953,13 +142823,8 @@ return ThreeMf end __FILES["model/3mf/Read"] = function() --- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first --- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), --- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension --- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, --- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. --- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and --- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under +-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -144975,7 +142840,6 @@ local MAX_DEPTH = 64 local localName = Xml.localName --- an attribute by local name (namespaced attributes such as p:path) local function attr(node: any, name: string): string? local a = node.attrs local v = a[name] @@ -144998,7 +142862,7 @@ local function int(s: string?): number? return nil end --- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +-- "#RRGGBB" / "#RRGGBBAA", sRGB local function hexColor(s: string?): { number }? if type(s) ~= "string" then return nil @@ -145022,7 +142886,7 @@ function Read.toLinear(c: number): number end local toLinear = Read.toLinear --- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention local function transform(s: string?): ({ number }?, boolean) if not s then return nil, true @@ -145053,7 +142917,6 @@ local function normPath(p: string): string return p end --- one model part parsed into its resources and build type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? } local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?) @@ -145207,7 +143070,6 @@ local function parseModel(text: string, path: string, opts: any): (Model?, Err.E return model, nil end --- the root model part's path local function rootPath(zip: any): string? local rels = zip:readString("_rels/.rels") if rels then @@ -145267,7 +143129,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) scene.meta.metadata = root.metadata scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } - -- textures and materials (shared across model parts by part path + resource id) local texCache: { [string]: number } = {} local function texture(model: Model, id: number): number? local key = model.path .. "#" .. id @@ -145313,7 +143174,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return m end - -- property of one corner -> (group key, material index?, kind, resource, index) local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number) local r = model.res[pid] if not r or p < 0 then @@ -145383,7 +143243,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return "none", nil, "none", nil, 0 end - -- one Scene mesh per (part, object) with a mesh local meshCache: { [string]: number } = {} local function buildMesh(model: Model, o: any): number? local key = model.path .. "#" .. o.id @@ -145486,7 +143345,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return #scene.meshes end - -- nodes: one per object instance (build items and components) local nodeCount = 0 local maxNodes = opts.maxNodes or 2 ^ 20 local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?) @@ -145553,12 +143411,7 @@ return Read end __FILES["model/3mf/Write"] = function() --- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, --- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the --- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), --- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has --- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). --- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -145602,7 +143455,6 @@ local function hex(r: number, g: number, b: number, a: number): string return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) end --- the triangle corner list of a primitive (0-based vertex indices) or nil local function triangles(prim: any): { number }? local pos = prim.attributes and prim.attributes.POSITION if type(pos) ~= "table" then @@ -145682,10 +143534,9 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) nextId += 1 return nextId end - local res: { string } = {} -- resource XML chunks, in definition order + local res: { string } = {} local files: { { name: string, data: buffer, mime: string } } = {} - -- unit local unitName: string, scale: number = "millimeter", 1 local mu: any = scene.meta and scene.meta.unit if type(o.unit) == "string" and UNITS[o.unit] then @@ -145706,16 +143557,14 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) end end - -- base materials: one group with every Scene material local baseId: number? = nil local nmat = #scene.materials - local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local defaultBase = nmat local needDefault = false if nmat > 0 then baseId = id() end - -- textures used as base colour textures local texRes: { [number]: number } = {} local function textureId(ti: number): number? if texRes[ti] ~= nil then @@ -145740,7 +143589,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) return rid end - -- objects local objectOf: { [number]: number } = {} local objChunks: { string } = {} for mi, mesh in scene.meshes do @@ -145749,7 +143597,7 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) local base = 0 local objPid: number?, objP: number? = nil, nil local anyNone = false - local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + local triList: { { number } } = {} for _, prim in mesh.primitives do local corners = triangles(prim) if not corners or #corners == 0 then @@ -145764,7 +143612,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) for v = 0, n - 1 do table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0))) end - -- properties: texture group, colour group, base material, none local pid, kind = -1, "none" local mat = prim.material and scene.materials[prim.material] local uv = prim.attributes.TEXCOORD_0 @@ -145850,7 +143697,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) table.insert(res, objChunks[#objChunks]) end - -- the base material group goes first (its id was taken first) if baseId then local parts = { fmt('\t\t\n', baseId) } for _, m in scene.materials do @@ -145864,7 +143710,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) table.insert(res, 1, table.concat(parts)) end - -- build items: every node with a mesh, at its world matrix local items: { string } = {} local seen: { [number]: boolean } = {} for _, pl in Types.Scene.flatten(scene) do @@ -145896,7 +143741,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) end end - -- metadata local meta: { string } = {} local md = scene.meta and scene.meta.metadata if type(md) == "table" then @@ -145972,23 +143816,9 @@ return Write end __FILES["model/b3d"] = function() --- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description --- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. --- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, --- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> --- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is --- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree --- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / --- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the --- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights --- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the --- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, --- default 60) -> one animation of LINEAR channels at frame / fps seconds. --- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding --- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their --- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. --- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the --- extras; texture coordinate sets of 3 / 4 components keep their first two. +-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp). +-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored. +-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -146008,10 +143838,10 @@ local B3d = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the files by name + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, maxVertices: number?, -- default 2^24 - maxDepth: number?, -- node nesting (default 256) + maxDepth: number?, -- default 256 } -- ------------------------------------------------------------------------------------------------ sniff @@ -146027,7 +143857,6 @@ function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if r:peek(4) ~= "BB3D" then return nil, Err.new(Err.CORRUPT, "no BB3D chunk") end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, r, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) @@ -146042,10 +143871,7 @@ return B3d end __FILES["model/b3d/Read"] = function() --- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are --- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes --- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene. local Bytes = __include("core/Bytes") local Types = __include("Types") local Chunks = __include("containers/Chunks") @@ -146069,8 +143895,8 @@ type MeshRec = { mesh: number, node: number, count: number, joints: { { number } type Bone = { node: number, target: MeshRec?, list: { number } } type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } --- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated --- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse +-- rotation, as assimp reads them) then mirrored local function vec(r: Bytes.Reader): { number } local x, y, z = r:f32le(), r:f32le(), r:f32le() return { x, y, -z } @@ -146097,7 +143923,6 @@ local function fetcher(opts: Options?): (string) -> buffer? end end --- scene(r, opts) -> Scene | nil, message, kind function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) local buf = src.buf local maxVertices = opts and opts.maxVertices or 2 ^ 24 @@ -146120,7 +143945,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, local scene = Types.Scene.new() local texs: { TexInfo } = {} local brushes: { Brush } = {} - local materialOf: { [number]: number } = {} -- brush index (0-based) -> material + local materialOf: { [number]: number } = {} local meshes: { MeshRec } = {} local bones: { Bone } = {} local nodeKeys: { [number]: Keys } = {} @@ -146184,7 +144009,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end - -- the material of brush id (0-based) | nil for -1 / out of range local function material(id: number): number? if id < 0 or id >= #brushes then return nil @@ -146333,7 +144157,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, fail(string.format("triangle %d: vertex index out of range", i)) return nil end - -- mirrored z: reverse the winding to keep the faces front-facing writeu32(idx, i * 12, a) writeu32(idx, i * 12 + 4, cc) writeu32(idx, i * 12 + 8, b) @@ -146345,7 +144168,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end if not attrs then - return nil -- a mesh without vertices: the node stays a pivot + return nil end if #mesh.primitives == 0 then table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) @@ -146515,7 +144338,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end end - local self: number? = nil -- the mesh node as a joint, for vertices no bone moves + local self: number? = nil local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) for v = 0, nv - 1 do local e = inf[v + 1] @@ -146527,7 +144350,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, buffer.writeu16(jb, v * 8, self :: number) buffer.writef32(wb, v * 16, 1) else - -- the 4 strongest, normalised local order = {} for k = 1, #e, 2 do table.insert(order, k) @@ -146611,7 +144433,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, brushes = #brushes, frames = if anim then anim.frames else nil, fps = if anim then anim.fps else nil, - handedness = "left", -- converted: z mirrored, winding reversed + handedness = "left", } return scene, nil, nil end @@ -146620,13 +144442,8 @@ return Read end __FILES["model/bsp"] = function() --- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) --- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a --- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III --- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as --- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not --- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. --- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW +-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. -- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -146649,10 +144466,10 @@ local Bsp = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - palette: (buffer | string)?, -- Quake 1: the 768-byte palette + palette: (buffer | string)?, -- Quake 1: 768 bytes resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - patchLevel: number?, -- Quake III patch subdivisions (default 4) + patchLevel: number?, -- default 4 maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -146676,7 +144493,6 @@ function Bsp.sniff(r: Bytes.Reader): number return if v == 38 or v == 46 or v == 47 then 1 else 0.3 end if v == 29 or v == 30 then - -- no magic: check that the lump directory fits the file local size = r:remaining() for i = 0, 14 do local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) @@ -146690,7 +144506,6 @@ function Bsp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the entities text -> { { key = value } } local function entities(text: string): { { [string]: string } } local out: { { [string]: string } } = {} for block in string.gmatch(text, "%b{}") do @@ -146772,15 +144587,9 @@ return Bsp end __FILES["model/bsp/Brush"] = function() --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex --- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture --- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the --- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / --- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the --- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from --- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). --- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. --- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the +-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture +-- size. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") @@ -146793,7 +144602,7 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 type Lump = { at: number, size: number } type Options = { palette: buffer?, - wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size) + wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) maxPixels: number?, maxVertices: number?, } @@ -146805,7 +144614,6 @@ local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- miptex lump (Quake / Half-Life) -> textures local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) local out: { Tex } = {} if l.size < 4 then @@ -146853,9 +144661,6 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer return out, nil end --- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message --- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, --- models, miptex (q1 / hl) function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) local q2 = variant == "q2" local maxPixels = opts and opts.maxPixels or 2 ^ 24 @@ -146868,9 +144673,8 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if nF > (opts and opts.maxVertices or 2 ^ 24) then return nil, "limit: too many faces" end - -- textures local texs: { Tex } = {} - local texOf: { number } = {} -- texinfo -> texture index (1-based) + local texOf: { number } = {} if q2 then local byName: { [string]: number } = {} for i = 0, nTI - 1 do @@ -146899,7 +144703,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 end end - -- faces of each model local scene = Scene.new() scene.meta.up = "z" local faceModel: { number } = {} @@ -146933,7 +144736,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian skipped += 1 continue end - -- the polygon local poly: { number } = {} local ok = true for k = 0, numEdges - 1 do @@ -146962,7 +144764,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if side ~= 0 then nx, ny, nz = -nx, -ny, -nz end - -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + -- Newell's normal of the polygon as stored local n = #poly // 3 local ax, ay, az = 0, 0, 0 for k = 0, n - 1 do @@ -147012,7 +144814,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian end end end - -- textures, materials for i, t in texs do local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } table.insert(scene.textures, tex) @@ -147023,7 +144824,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any table.insert(scene.materials, mat) end - -- meshes and nodes local root: Types.Node = { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 @@ -147065,13 +144865,8 @@ return Brush end __FILES["model/bsp/Quake3"] = function() --- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a --- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches --- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap --- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 --- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as --- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. --- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. local Types = __include("Types") local Quake3 = {} @@ -147083,19 +144878,18 @@ local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.wri type Lump = { at: number, size: number } type Options = { patchLevel: number?, maxVertices: number? } -type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices) +type Batch = { shader: number, lightmap: number, verts: { number } } -- indices into the vertex lump, or -1 - k for patch vertices local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- decode(b, base, lumps, opts) -> Scene | nil, message function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) local maxV = opts and opts.maxVertices or 2 ^ 24 - -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + -- patch vertices: 12 floats + 4 colour bytes each local extra: { number } = {} local function vertex(i: number): { number } local o = base + VX.at + i * 44 @@ -147158,7 +144952,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: local L = level for py = 0, (h - 1) // 2 - 1 do for px = 0, (w - 1) // 2 - 1 do - -- the 3x3 control points of this sub-patch local ctrl: { { number } } = {} for j = 0, 2 do for i = 0, 2 do @@ -147193,7 +144986,7 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: for gx = 0, L - 1 do local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- counter-clockwise for Quake's clockwise-front control grids + -- Quake's control grids are clockwise-front for _, v in { a, d, c2, c2, d, e } do table.insert(tris, v) end @@ -147232,7 +145025,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: end local scene = Scene.new() scene.meta.up = "z" - -- shaders, lightmaps for i = 0, nT - 1 do local name = cstr(b, base + T.at + i * 72, 64) table.insert(scene.textures, { name = name, uri = name }) @@ -147328,28 +145120,10 @@ return Quake3 end __FILES["model/dae"] = function() --- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its --- manifest.xml and the images). New code. --- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input --- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), --- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / --- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> --- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), --- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix / --- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances --- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under --- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph --- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; --- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as --- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE --- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, --- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" --- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left --- origin (opts.flipV = false keeps Collada's). --- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. --- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves --- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than --- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, +-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations. +-- Not supported: / , polygon holes (), Bezier / Hermite curves (sampled linearly), non-transform +-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -147372,17 +145146,17 @@ local Dae = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths - files: { [string]: any }?, -- or: the files by uri / base name - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention) - maxVertices: number?, -- refuse more output vertices / array values (default 2^25) + resolve: ((uri: string) -> any)?, -- image files (buffer or string) + files: { [string]: any }?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + maxVertices: number?, -- default 2^25 } type EncodeOptions = { - files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri) - name: string?, -- the destination's file name (names the image files) - flipV: boolean?, -- default true (the inverse of decode) - format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension + files: { [string]: any }?, -- receives the texture images (else data: URIs or their uri) + name: string?, + flipV: boolean?, -- default true + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images) } -- ------------------------------------------------------------------------------------------------ sniff @@ -147436,7 +145210,7 @@ local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch end end --- the main .dae of a .zae: manifest.xml's , else the first .dae entry +-- a .zae's main .dae: manifest.xml's , else the first .dae entry local function zae(r: Bytes.Reader): (any, string?, Err.Err?) local zip, err = Zip.open(r) if not zip then @@ -147503,7 +145277,6 @@ function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err return nil, Err.new(Err.ARG, "needs a Scene") end if opts and opts.format == "zae" then - -- a zip: manifest.xml, the .dae and its images local files = {} local o = table.clone(opts) o.files = files @@ -147536,8 +145309,7 @@ return Dae end __FILES["model/dae/Math"] = function() --- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices, --- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +-- model/dae/Math: the Collada transform elements and ; matrices are flat column-major arrays of 16. local Mat4 = __include("codecs/model/Mat4") local DaeMath = {} @@ -147555,7 +145327,7 @@ local function norm(a: { number }): { number } return { a[1] / l, a[2] / l, a[3] / l } end --- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +-- : an object at eye whose -Z looks at interest function DaeMath.lookat(v: { number }): { number } local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) @@ -147564,14 +145336,14 @@ function DaeMath.lookat(v: { number }): { number } return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } end --- skew(angle, rotation axis, translation axis) (RenderMan's skew) +-- (RenderMan's skew) function DaeMath.skew(v: { number }): { number } local a = rad(v[1] or 0) local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) local s = math.tan(a) local m = Mat4.identity() - -- M = I + s * t * r^T (column-major: m[col*4 + row]) + -- M = I + s * t * r^T for row = 0, 2 do for col = 0, 2 do m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] @@ -147584,15 +145356,7 @@ return DaeMath end __FILES["model/dae/Read"] = function() --- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / --- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile --- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, --- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / --- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin --- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as --- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform --- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS --- channels; one animation per animation clip, else one for the file). +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -147685,8 +145449,8 @@ type Ctx = { meshes: { [string]: number }, skins: { [string]: number }, posIndex: { [any]: { number } }, - nodeOf: { [string]: { number } }, -- collada node id -> scene nodes - info: { [number]: any }, -- scene node -> { el, xf, sid, cid } + nodeOf: { [string]: { number } }, + info: { [number]: any }, pendingSkins: { any }, skipped: { [string]: number }, err: string?, @@ -147698,7 +145462,6 @@ local function skip(C: Ctx, what: string) end -- ------------------------------------------------------------------------------------------------ sources --- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) local function readSource(C: Ctx, el: any): any local cached = C.sources[el] if cached ~= nil then @@ -147864,7 +145627,6 @@ local function image(C: Ctx, id: string): any return img end --- the effect's newparams by sid (this level and the profile's) local function newparams(effect: any, profile: any, technique: any): { [string]: any } local out = {} for _, scope in { effect, profile, technique } do @@ -147880,7 +145642,6 @@ local function newparams(effect: any, profile: any, technique: any): { [string]: return out end --- texture(effect params, sampler sid) -> scene texture index local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? local np = params[samplerSid] local imageId: string? = nil @@ -147949,7 +145710,6 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n return idx end --- one colour-or-texture parameter of a common technique local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) if not el then return nil, nil @@ -148059,7 +145819,7 @@ local function material(C: Ctx, id: string, uvsets: { [string]: number }): numbe if type(shininess) == "number" then mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) end - -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then local mode = attr(transparentEl, "opaque") or "A_ONE" local tv = if type(transparency) == "number" then transparency else 1 @@ -148116,7 +145876,6 @@ end -- ------------------------------------------------------------------------------------------------ geometry type Input = { semantic: string, source: any, offset: number, set: number } --- the inputs of a primitive element (VERTEX expanded into the inputs) local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) local out: { Input } = {} local stride = 0 @@ -148148,7 +145907,6 @@ local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) return out, math.max(stride, 1) end --- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) local p: { number } = {} local faces: { number } = {} @@ -148255,7 +146013,6 @@ local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } --- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? local ins, stride = inputs(C, prim, verticesEl) local p, faces, starts, mode = corners(C, prim, kind, stride) @@ -148273,7 +146030,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil skip(C, "primitives without positions") return nil end - -- attribute names local named: { { input: Input, name: string, comps: number } } = {} local texSets: { number } = {} local texInputs: { Input } = {} @@ -148310,10 +146066,9 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) end end - -- de-index local np = #p local keyOf: { [any]: number } = {} - local tuples: { number } = {} -- the first p index of each output vertex's tuple + local tuples: { number } = {} local corner = table.create(#starts) :: { number } local count = 0 for ci, s in starts do @@ -148388,7 +146143,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil if allTri then mode = "triangles" elseif C.triangulate then - -- fan triangulation local tri: { number } = {} local at = 0 for _, f in faces do @@ -148417,7 +146171,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } end --- geometry(el) -> the built primitives (cached per geometry element) local function geometry(C: Ctx, el: any): { Built }? local cached = C.posIndex[el] if cached then @@ -148448,7 +146201,6 @@ local function geometry(C: Ctx, el: any): { Built }? return out end --- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) local syms: { [string]: string } = {} local sets: { [string]: { [string]: number } } = {} @@ -148479,7 +146231,6 @@ local function copyAccessor(a: Types.Accessor): Types.Accessor return Scene.accessor(b, a.type, a.components, a.count) end --- mesh(geometry element, instance element, skin?) -> scene mesh index local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) local syms, sets = bindings(inst) local parts = { key } @@ -148500,7 +146251,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { for _, b in built do local prim = b.prim if bindShape then - -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) local attrs = table.clone(prim.attributes) local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do @@ -148546,7 +146296,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { end end if target then - -- texcoord semantic -> TEXCOORD_n index among this primitive's sets local uv: { [string]: number } = {} for sem, set in (sym and sets[sym]) or {} do uv[sem] = (table.find(b.texSets, set) or 1) - 1 @@ -148561,7 +146310,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { return idx, built end --- morph controller -> mesh with targets (deltas) local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? local base = C.ids[urlId(attr(morph, "source")) or ""] if not base or lname(base) ~= "geometry" then @@ -148667,7 +146415,6 @@ local function camera(C: Ctx, el: any): number? return #C.scene.cameras end --- light(el) -> light index, or nil and the ambient colour local function light(C: Ctx, el: any): (number?, { number }?) local tc = child(el, "technique_common") if not tc then @@ -148709,7 +146456,6 @@ end -- ------------------------------------------------------------------------------------------------ nodes local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } --- the matrix of one transform element's values local function xfMatrix(kind: string, v: { number }): { number } if kind == "matrix" then return Mat4.fromRows(v) @@ -148767,7 +146513,7 @@ local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number return idx end --- the instances of a node: the first of each kind on the node itself, the rest on child nodes +-- extra instances of a node go on child nodes local function instances(C: Ctx, el: any, node: Types.Node, idx: number) local function slot(kind: string, name: string?): (Types.Node, number) local n: any = node @@ -148907,7 +146653,7 @@ visitNode = function(C: Ctx, el: any): number? end -- ------------------------------------------------------------------------------------------------ skins --- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +-- joints: by sid below the skeleton roots, else by sid / id / name anywhere local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? local nodes = C.scene.nodes local function search(i: number, depth: number): number? @@ -148995,7 +146741,7 @@ local function resolveSkins(C: Ctx) local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } if ps.bind then local sk: any = skin - sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + sk.extras = { dae = { bindShapeMatrix = ps.bind } } end if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) @@ -149017,7 +146763,6 @@ local function resolveSkins(C: Ctx) cache[key] = si end C.scene.nodes[ps.node].skin = si - -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) local mesh = C.scene.meshes[ps.mesh] if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then continue @@ -149042,7 +146787,7 @@ local function resolveSkins(C: Ctx) local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} local wdata = wSrc and wSrc.data or {} - local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local per: { { number } } = {} local at = 0 for pi, c in vcount do local list = {} @@ -149140,9 +146885,9 @@ local function sample(c: Curve, t: number): { number } return a end --- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +-- "id/sid/sid.member" or "id/sid(i)(j)" local function target(C: Ctx, s: string): ({ number }?, any, number?) - -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" local id, sids = match(s, "^([^/]*)/(.*)$") if not id then return nil, nil, nil @@ -149192,7 +146937,6 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?) return nodes, xf, member end --- the channels of one (recursively) -> curves grouped by node local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) if depth > 64 then return @@ -149282,7 +147026,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) local prev: { number }? = nil for i, t in times do - -- this time's values of each animated element local xf = {} for k, x in info.xf do xf[k] = { kind = x.kind, values = table.clone(x.values) } @@ -149323,7 +147066,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) - -- the node is now TRS-driven local node = C.scene.nodes[ni] if node.matrix then setTransform(node, node.matrix) @@ -149406,12 +147148,11 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? } for _, el in Xml.descendants(root) do local id = el.attrs.id - -- duplicate ids: the first one, unless it is empty (some exporters write before the real one) + -- duplicate ids: the first, unless empty (some exporters write before the real one) if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then C.ids[id] = el end end - -- asset: up axis, unit local asset = child(root, "asset") local up = asset and child(asset, "up_axis") local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" @@ -149419,7 +147160,6 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? local unit = asset and child(asset, "unit") local meter = unit and attr(unit, "meter") scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 - -- the instanced visual scene (else the first one) local vsId: string? = nil local sceneEl = child(root, "scene") local ivs = sceneEl and child(sceneEl, "instance_visual_scene") @@ -149466,11 +147206,8 @@ return Read end __FILES["model/dae/Write"] = function() --- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips --- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n --- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its --- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras; --- lights. Not written: skins, morph targets, animations. +-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major . +-- Not written: skins, morph targets, animations. local Types = __include("Types") local Xml = __include("codecs/text/Xml") local Base64 = __include("core/Base64") @@ -149505,7 +147242,6 @@ local function nameAttr(s: string?): string return if s then ' name="' .. esc(s) .. '"' else "" end --- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?) local n = prim.attributes.POSITION.count local idx: { number } = {} @@ -149627,7 +147363,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? local meta: { [string]: any } = scene.meta or {} local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" w(format('rosetta1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up)) - -- images local imageId: { [number]: string } = {} if #scene.textures > 0 then w("\n") @@ -149651,12 +147386,11 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- effects + materials if #scene.materials > 0 then w("\n") for i, mat in scene.materials do local ph: any = mat.extras and mat.extras.phong or {} - local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys + local params: { [any]: any } = {} local function texParam(ref: Types.TextureRef?): (string?, number?) if not ref or not imageId[ref.texture] then return nil, nil @@ -149703,7 +147437,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- geometries: one per primitive local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} w("\n") for mi, mesh in scene.meshes do @@ -149756,7 +147489,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end end w("\n") - -- cameras / lights if #scene.cameras > 0 then w("\n") for i, cam in scene.cameras do @@ -149783,7 +147515,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- the node tree w('\n') local seen: { [number]: boolean } = {} local function node(i: number, depth: number) @@ -149844,26 +147575,9 @@ return Write end __FILES["model/fbx"] = function() --- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays --- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and --- assimp's FBX importer, and the FBX SDK's documentation of the transform model. --- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl --- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms --- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, --- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference --- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR --- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins --- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets --- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and --- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for --- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). --- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives --- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), --- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + --- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler --- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). --- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered --- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). +-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs. +-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras. +-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -149886,21 +147600,21 @@ local Fbx = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention) - sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only) - resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the files by name - maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30) - maxVertices: number?, -- refuse more polygon corners (default 2^25) + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + sampleRate: number?, -- samples per second (default: the keys only) + resolve: ((uri: string) -> any)?, -- external texture files + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of arrays + maxVertices: number?, -- default 2^25 polygon corners } type EncodeOptions = { - ascii: boolean?, -- write ASCII FBX (default binary) + ascii: boolean?, -- default binary version: number?, -- 7400 (default) or 7500 (64-bit records) - flipV: boolean?, -- default true (the inverse of decode) - embedTextures: boolean?, -- embed texture.data as Video content (default true) - compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger) - name: string?, -- the destination's file name (names textures without a uri) + flipV: boolean?, -- default true + embedTextures: boolean?, -- default true + compress: boolean?, -- arrays over 32 elements (default true) + name: string?, creator: string?, } @@ -149945,8 +147659,6 @@ end local toErr = Err.from --- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. --- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?) if r:peek(21) == MAGIC then local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) @@ -149974,7 +147686,6 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if not root then return nil, version end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) @@ -150012,9 +147723,8 @@ return Fbx end __FILES["model/fbx/Ascii"] = function() --- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' --- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary --- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays, +-- " in strings); integers longer than 15 digits stay strings so ids are exact. local Base64 = __include("core/Base64") local Ascii = {} @@ -150028,7 +147738,6 @@ local function isNameStart(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end --- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local n = #text @@ -150049,7 +147758,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n end end - -- at i: a name followed by ':'? -> name, the index after ':' local function nameAt(): (string?, number) local c = sbyte(text, i) if not c or not isNameStart(c) then @@ -150074,7 +147782,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n return nil, i end - -- the values of one node (after the ':'), up to a new name, '{' or '}' local function values(): ({ any }?, string?) local props: { any } = {} while true do @@ -150176,7 +147883,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n return e end end - -- "*N { a: v, v, ... }" -> an Array local p1 = props[1] if #props == 1 and type(p1) == "table" and p1.star then local a = node.children[1] @@ -150226,7 +147932,6 @@ local function fmt(v: number): string return string.format("%.17g", v) end --- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) function Ascii.write(root: any, version: number?): string local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } local function node(nd: any, indent: string) @@ -150249,7 +147954,7 @@ function Ascii.write(root: any, version: number?): string elseif tv == "table" and v.array then arr = v elseif tv == "buffer" then - -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + -- raw bytes (Video Content): base64 split into lines as the FBX SDK writes them local b64 = Base64.encode(v) local chunks = {} for k = 1, #b64, 2048 do @@ -150289,11 +147994,8 @@ end __FILES["model/fbx/Binary"] = @native function() --- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit --- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's --- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array --- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become --- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset). +-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by +-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L" so ids stay exact. local Deflate = __include("codecs/compress/Deflate") local Binary = {} @@ -150310,7 +148012,7 @@ local MAX_DEPTH = 128 local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 local writef64 = buffer.writef64 --- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +-- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>" @native local function i64(b: buffer, p: number, asString: boolean): any local lo, hi = readu32(b, p), readu32(b, p + 4) if hi >= 0x80000000 then @@ -150329,7 +148031,6 @@ Binary.i64 = i64 local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } --- the elements of a raw array (n elements of type t at p) as f64s @native local function toF64(t: string, src: buffer, p: number, n: number): buffer local out = buffer.create(n * 8) if t == "d" then @@ -150355,7 +148056,6 @@ local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } return out end --- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset @native function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then @@ -150447,7 +148147,6 @@ end return out, p end - -- one node record at p: node | false (the null record), next offset | nil, message, offset @native local function node(p: number, stop: number, depth: number): (any, any, number?) if p + head > stop then return nil, "truncated node record", p @@ -150519,10 +148218,8 @@ end end -- ------------------------------------------------------------------------------------------------ writer --- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit --- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint --- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their --- type (compressed with zlib when longer than 32 elements, unless compress = false). +-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per +-- property; arrays over 32 elements are zlib-compressed type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } @native local function sizeHint(n: WNode): number @@ -150751,17 +148448,8 @@ return Binary end __FILES["model/fbx/Read"] = function() --- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> --- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric --- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in --- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one --- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the --- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file --- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind --- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's --- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or --- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node --- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, +-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. local Err = __include("core/Err") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -150802,7 +148490,7 @@ local function isArray(v: any): boolean return type(v) == "table" and v.array == true end --- the array under n. (or inline numbers: old ASCII files) +-- old ASCII files have inline numbers local function array(n: Node?, name: string): Array? local c = child(n, name) if not c then @@ -150839,7 +148527,7 @@ local function at(a: Array, i: number): number return buffer.readf64(a.data, i * 8) end --- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) local function objectName(s: any): string if type(s) ~= "string" then return "" @@ -150856,7 +148544,7 @@ local function objectName(s: any): string end Read.objectName = objectName --- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +-- Properties70: P: name, type, label, flags, values... local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } local out = into or {} local p70 = child(n, "Properties70") @@ -150907,7 +148595,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local maxVertices = opts and opts.maxVertices or 2 ^ 25 local scene = Types.Scene.new() - -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + -- Definitions/ObjectType/PropertyTemplate local templates: { [string]: { [string]: { any } } } = {} local defs = child(root, "Definitions") if defs then @@ -150921,7 +148609,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- objects local objects: { [any]: Obj } = {} local order: { Obj } = {} local objs = child(root, "Objects") @@ -150939,7 +148626,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- connections: children (sources) of each parent, parents of each child, in file order local kids: { [any]: { Conn } } = {} local parents: { [any]: { Conn } } = {} local conns = child(root, "Connections") @@ -150988,7 +148674,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return out end - -- global settings local gs = properties(child(root, "GlobalSettings")) local upAxis = pnum(gs, "UpAxis", 1) local unitScale = pnum(gs, "UnitScaleFactor", 1) @@ -151032,7 +148717,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return p end end - -- ASCII: base64 strings (possibly split into several) + -- ASCII: base64, possibly split into several strings local parts = {} for _, p in c.props do if type(p) == "string" then @@ -151136,7 +148821,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if opacity < 1 then m.alphaMode = "blend" end - -- 3ds Max Physical / PBR materials local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] if pbr then local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" @@ -151256,7 +148940,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ nd.scale = s end nd.extras = { fbx = { type = o.sub, id = o.id } } - -- parent local parentModel: Obj? = nil for _, t2 in targets(o.id, "Model") do parentModel = t2.obj @@ -151269,7 +148952,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.insert(scene.roots, ni) end end - -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + -- break parent cycles: cut children already placed do local placed: { [number]: boolean } = {} local function visit(i: number) @@ -151289,13 +148972,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end for i in scene.nodes do if not placed[i] then - -- part of a parent cycle: make it a root table.insert(scene.roots, i) visit(i) end end end - -- world matrices (rest pose) local worldM: { [number]: Mat4.M4 } = {} local function world(i: number, parent: Mat4.M4) worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) @@ -151311,7 +148992,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ -- ------------------------------------------------------------------------------------------ meshes local corners = 0 - -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) local skin = sources(geo.id, "Deformer", "Skin")[1] if not skin then @@ -151397,7 +149077,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end local meshCache: { [string]: number } = {} - local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves) + local shapeChannels: { [number]: { Obj } } = {} local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} @@ -151414,7 +149094,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if corners > maxVertices or ncp > maxVertices then return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") end - -- polygons: corner -> control point, polygon of each corner, polygon starts local cp = table.create(nc, 0) local polyOf = table.create(nc, 0) local starts: { number } = { 0 } @@ -151440,7 +149119,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ np += 1 starts[np + 1] = nc end - -- layer elements type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } local out: { Elem } = {} @@ -151463,7 +149141,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end) return out end - -- the data element of a corner (c 0-based), or -1 local function lookup(e: Elem, c: number): number local m = e.mapping local i @@ -151494,7 +149171,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] - -- the normals index name varies ("NormalsIndex" / "NormalIndex") + -- "NormalsIndex" / "NormalIndex" for _, e in normals do if not e.index then local c = nil @@ -151510,7 +149187,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- polygons by material slot local groups: { [number]: { number } } = {} local slots: { number } = {} for p = 0, np - 1 do @@ -151537,7 +149213,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) + local N3: Mat4.M4? = nil -- inverse transpose of G if G then local inv = Mat4.inverse(G) if inv then @@ -151756,12 +149432,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] - -- materials of the model, in connection order local mats: { number } = {} for _, m in sources(o.id, "Material") do table.insert(mats, material(m)) end - -- geometric transform (not inherited: baked into the mesh) + -- geometric transform: not inherited, baked into the mesh local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) @@ -151799,7 +149474,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis for _, a in sources(o.id, "NodeAttribute") do local p = a.props if a.sub == "Camera" then @@ -151872,7 +149547,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ times[k + 1] = at(kt, k) / TICKS values[k + 1] = at(kv, k) end - -- per-key attribute flags (expanded through KeyAttrRefCount) + -- expanded through KeyAttrRefCount local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") local flags = table.create(n, 4) local slopes: { { number } } = {} @@ -151975,11 +149650,10 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, stack in order do if stack.class == "AnimationStack" then local anim: Types.Animation = { name = stack.name, channels = {} } - -- model id -> { T/R/S -> { axis -> curve } , defaults } type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } local tracks: { [any]: Track } = {} local trackOrder: { any } = {} - local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve + local morph: { [any]: Curve } = {} local layers = sources(stack.id, "AnimationLayer") for _, layer in layers do for _, cn in sources(layer.id, "AnimationCurveNode") do @@ -152080,7 +149754,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- morph target weights: every node whose mesh has an animated blend shape channel if next(morph) then for ni, nd in scene.nodes do local chans = nd.mesh and shapeChannels[nd.mesh] @@ -152137,13 +149810,8 @@ return Read end __FILES["model/fbx/Write"] = function() --- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types --- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). --- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one --- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals --- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; --- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> --- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +-- model/fbx/Write: Scene -> an FBX 7.4 node tree. Property types follow what Blender's and the FBX SDK's readers check +-- (ids L, ints I, doubles D, KTime L, arrays d / i / l / f); rotations as Euler XYZ degrees. local Err = __include("core/Err") local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -152166,7 +149834,7 @@ local function arr(t: string, list: { number }): any end return { array = true, type = t, count = n, data = d } end --- P: name, type, label, flags, values (vt: one type character per value) +-- P: name, type, label, flags, values local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } end @@ -152202,7 +149870,6 @@ local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> return Types.Scene.reader(acc) end --- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) local function faces(prim: Types.Primitive): { { number } }? local pos = prim.attributes.POSITION if not pos then @@ -152373,7 +150040,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) link(m.baseColorTexture, "DiffuseColor") link(m.normalTexture, "NormalMap") link(m.emissiveTexture, "EmissiveColor") - -- the other textures the FBX material had (specular, metalness, ... maps), under their property names local linked = { [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, [m.normalTexture and m.normalTexture.texture or -1] = true, @@ -152398,7 +150064,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ models local modelIds: { [number]: number } = {} local skip: { [number]: boolean } = {} - local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) + local attrHost: { [number]: number } = {} local parentOf: { [number]: number } = {} for i, nd in nodes do for _, c in nd.children or {} do @@ -152421,7 +150087,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) attrHost[i] = p end end - -- world matrices (rest pose) for clusters and the bind pose local worldM: { [number]: Mat4.M4 } = {} local visiting: { [number]: boolean } = {} local function world(i: number): Mat4.M4 @@ -152528,7 +150193,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local euler = Mat4.eulerXYZ(r) local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" - -- an orientation child folded into this node gives it its attribute local folded: number? = nil for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) if host == i then @@ -152568,9 +150232,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ geometry local geoIds: { [number]: number } = {} - local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot + local geoSlots: { [number]: { number } } = {} local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} - local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) + local geoChannels: any = {} local geoCount: { [number]: number } = {} local function geometry(mi: number): number? if geoIds[mi] then @@ -152763,7 +150427,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) geoSlots[mi] = if anyMat then slots else {} geoVerts[mi] = layout geoCount[mi] = offset - -- morph targets local prims = mesh.primitives local ntargets = 0 for _, l in layout do @@ -152855,7 +150518,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) OO(pm, mid) end end - -- skin: one Skin per (geometry, skin) local skin = nd.skin and scene.skins[nd.skin] local key = tostring(gid) .. ":" .. tostring(nd.skin) if skin and not skinned[key] then @@ -152866,7 +150528,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local meshWorld = world(i) pose(mid, meshWorld) local ibm = accessorReader(skin.inverseBindMatrices) - -- per joint: control points and weights local perJoint: { { idx: { number }, w: { number } } } = {} for j in skin.joints do perJoint[j] = { idx = {}, w = {} } @@ -153016,7 +150677,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) else - -- weights: one DeformPercent curve per blend shape channel of the node's mesh local nd = nodes[ch.node] local gc: any = geoChannels local chans = nd.mesh and gc[nd.mesh] @@ -153135,9 +150795,8 @@ return Write end __FILES["model/fbx/Xform"] = function() --- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model --- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The --- matrix / quaternion arithmetic is codecs/model/Mat4. +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): +-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1 local Mat4 = __include("codecs/model/Mat4") local Xform = {} @@ -153148,7 +150807,6 @@ function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") end --- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers type Props = { T: { number }, R: { number }, S: { number }, Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number }, @@ -153164,7 +150822,6 @@ function Xform.localMatrix(p: Props): Mat4.M4 end m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - -- the inverse of a rotation is its transpose m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) @@ -153179,24 +150836,9 @@ return Xform end __FILES["model/gltf"] = function() --- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and --- binary (.glb). New code. --- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every --- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR --- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, --- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, --- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, --- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, --- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a --- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. --- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). --- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes .bin and the --- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). --- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the --- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back --- uncompressed (the extension is dropped). --- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels --- (skipped and counted in the animation's extras). +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*, +-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed). +-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -153220,16 +150862,16 @@ local Gltf = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths - files: { [string]: any }?, -- or: the files by uri - maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30) + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string) + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of buffers / accessors } type EncodeOptions = { - binary: boolean?, -- write GLB (default: when opts.format is "glb") - format: string?, -- "glb" -> binary (set by the api from the destination's extension) - external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs) + binary: boolean?, -- default: when opts.format is "glb" + format: string?, + external: boolean?, -- default false: data: URIs files: { [string]: any }?, -- receives .bin and images with external = true - name: string?, -- the destination's file name (names the external files) + name: string?, embedImages: boolean?, -- default true (false with external = true) } @@ -153278,7 +150920,6 @@ local function fetcher(opts: DecodeOptions?): Read.Fetch end end --- the JSON text and BIN chunk of a GLB local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) local magic, version, length = r:u32le(), r:u32le(), r:u32le() if r.err then @@ -153358,7 +150999,6 @@ function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er local doc = out.doc local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local files = opts and opts.files - -- images: data: URIs, or files if doc.images then local n = 0 for _, im in doc.images do @@ -153434,16 +151074,12 @@ end __FILES["model/gltf/Pack"] = @native function() --- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene --- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range --- first (offsets, strides and counts against the buffer lengths); nothing here throws. +-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers +-- check every range first. glTF pads matrix columns to 4 bytes. local Pack = {} local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 --- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is --- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = --- cols * colBytes bytes each) @native function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -153464,7 +151100,6 @@ local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu end end --- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) @native function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -153485,8 +151120,6 @@ end end end --- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element --- idx[k] of dst becomes value k (values packed, elem bytes each) @native function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean for k = 0, n - 1 do local i @@ -153509,12 +151142,8 @@ return Pack end __FILES["model/gltf/Read"] = function() --- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type --- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, --- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the --- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the --- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, --- scenes. glTF extras and unhandled extensions are kept in .extras.gltf = { extras, extensions }. +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are +-- kept in .extras.gltf = { extras, extensions }. local Err = __include("core/Err") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -153537,7 +151166,7 @@ local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } --- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +-- the extensions this reader understands (any other required one -> UNSUPPORTED) local KNOWN = { KHR_lights_punctual = true, KHR_mesh_quantization = true, @@ -153593,7 +151222,6 @@ local function numbers(v: any, n: number): { number }? return table.move(v, 1, n, 1, {} :: { number }) end --- extras.gltf: the JSON extras and the extensions not turned into Scene fields local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? local extras = obj.extras local ext: { [string]: any }? = nil @@ -153612,8 +151240,7 @@ local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any return { gltf = { extras = extras, extensions = ext } } end --- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value --- by value: normalized integers <-> floats, ints widened or narrowed) +-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value local DRACO_HANDLED = { KHR_draco_mesh_compression = true } local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } @@ -153681,7 +151308,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end local scene = Types.Scene.new() - -- buffers local buffers: { buffer } = {} local total = 0 for i, b in arr(doc.buffers) do @@ -153738,7 +151364,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end views[i] = { buf = b, offset = off, length = len, stride = stride } end - -- accessors local accessors: { Types.Accessor } = {} for i, a in arr(doc.accessors) do local label = "accessor " .. (i - 1) @@ -153805,7 +151430,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if io + n * isz > iv.length or vo + n * elem > vv.length then return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") end - -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + -- sparse values are tightly packed (matrices: padded columns) local vals, valOff = vv.buf, vv.offset + vo if cols > 1 and colBytes ~= colStride then vals = buffer.create(n * elem) @@ -153827,7 +151452,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc local k = int(v) return if k then accessors[k + 1] else nil end - -- images (kept encoded), samplers, textures local images: { Img } = {} for i, im in arr(doc.images) do if type(im) ~= "table" then @@ -153913,7 +151537,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.textures, tex) end - -- materials local function texRef(info: any): Types.TextureRef? if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then return nil @@ -153925,7 +151548,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end return r end - -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + -- a textureInfo: a table with an index, under a key ending in Texture local function convertExt(v: any): any if type(v) ~= "table" then return v @@ -153975,7 +151598,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc mat.extras = kept table.insert(scene.materials, mat) end - -- meshes for i, m in arr(doc.meshes) do if type(m) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) @@ -154044,7 +151666,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then return nil, Err.new(Err.CORRUPT, "bad indices accessor") end - -- indices must reference existing vertices local get = Types.Scene.reader(ind :: Types.Accessor) :: any for q = 0, ind.count - 1 do if get(q, 0) >= count then @@ -154073,7 +151694,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.meshes, mesh) end - -- cameras, lights for _, c in arr(doc.cameras) do if type(c) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad camera") @@ -154101,7 +151721,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc }) end end - -- nodes local nodes = arr(doc.nodes) for i, n in nodes do if type(n) ~= "table" then @@ -154157,7 +151776,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc p = parent[p] end end - -- skins for _, s in arr(doc.skins) do if type(s) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad skin") @@ -154171,7 +151789,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) end - -- animations for _, a in arr(doc.animations) do if type(a) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad animation") @@ -154208,7 +151825,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.animations, anim) end - -- scenes local scenes = arr(doc.scenes) local list = {} for _, s in scenes do @@ -154230,7 +151846,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end end - -- root extensions other than the lights, asset info local rootExt = nil if type(doc.extensions) == "table" then for k, v in doc.extensions do @@ -154258,13 +151873,8 @@ return Read end __FILES["model/gltf/Write"] = function() --- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex --- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), --- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), --- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, --- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their --- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first --- for concave faces). +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. Vertex attributes 4-byte aligned per +-- element, matrix columns padded, f64 / i32 data converted (glTF has neither), POSITION and animation input min / max. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -154348,7 +151958,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return #views - 1 end - -- accessor(acc, usage, attribute?) -> the glTF index (0-based) local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number local known = accIndex[acc] if known then @@ -154407,7 +152016,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return 0 end if attribute == "POSITION" or usage == "input" then - -- min / max of the raw component values local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) local get = Types.Scene.reader(raw) :: (number, number) -> number local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) @@ -154432,7 +152040,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return index end - -- extras.gltf -> extras / extensions fields of a glTF object local function restore(g: any, extras: any) local saved = type(extras) == "table" and extras.gltf if type(saved) ~= "table" then @@ -154452,7 +152059,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end end - -- images, samplers, textures local images: { any } = {} local imageOut: { { data: buffer, mime: string?, name: string } } = {} local imageIndex: { [any]: number } = {} @@ -154471,7 +152077,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) im.bufferView = view(data, buffer.len(data), nil, nil) im.mimeType = mime or "image/png" elseif embedImages then - im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI / a file name by the caller im.mimeType = mime table.insert(imageOut, { data = data, mime = mime, name = im.uri }) else @@ -154575,7 +152181,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end return out end - -- materials local materials: { any } = {} for i, m in scene.materials or {} do if type(m) ~= "table" then @@ -154629,7 +152234,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, m.extras) table.insert(materials, g) end - -- meshes local meshes: { any } = {} for i, mesh in scene.meshes or {} do if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then @@ -154655,7 +152259,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) local mode = p.mode or "triangles" local indices = p.indices if mode == "polygons" then - -- fan-triangulate local faces = p.faces local getf = faces and Types.Scene.reader(faces) local n = if indices then indices.count else p.attributes.POSITION.count @@ -154718,7 +152321,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, mesh.extras) table.insert(meshes, g) end - -- cameras, lights local cameras: { any } = {} for _, c in scene.cameras or {} do local g = object() @@ -154757,7 +152359,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(lights, g) end - -- nodes local nodes: { any } = {} local nodeCount = #(scene.nodes or {}) for i, n in scene.nodes or {} do @@ -154808,7 +152409,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, n.extras) table.insert(nodes, g) end - -- skins local skins: { any } = {} for _, s in scene.skins or {} do local g = object() @@ -154829,7 +152429,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(skins, g) end - -- animations local animations: { any } = {} for _, a in scene.animations or {} do local g = object() @@ -154861,7 +152460,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) if failure then return nil, failure end - -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + -- scenes: the original list (meta.gltf.scenes), else the roots local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {} local mg = type(meta.gltf) == "table" and meta.gltf or {} local scenes = {} @@ -154878,7 +152477,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, s.extras) table.insert(scenes, g) end - -- the current roots replace the default scene's list local which = mg.scene or 1 if scenes[which] then scenes[which].nodes = {} @@ -154905,7 +152503,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) asset.extras = mg.asset.extras end doc.asset = asset - -- root extensions kept from the source (variants, ...), the lights if type(mg.extensions) == "table" then doc.extensions = object() for k, v in mg.extensions do @@ -154956,17 +152553,9 @@ return Write end __FILES["model/iqm"] = function() --- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / --- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). --- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as --- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as --- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints --- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels --- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in --- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's --- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). --- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and --- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). +-- model/iqm: Inter-Quake Model (IQM version 2; iqm.txt / iqm.h of Lee Salzman's IQM SDK, public domain; checked against +-- assimp). Supports: meshes, every vertex array format, joints / skin, poses + anims, bounds. IQM is z-up, clockwise. +-- Not supported: IQM version 1, adjacency and extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -154987,11 +152576,11 @@ local Iqm = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxVertices: number?, -- refuse more vertices or triangles (default 2^25) + maxVertices: number?, -- default 2^25 } type EncodeOptions = { - framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) - comment: string?, -- stored in the comment block + framerate: number?, -- default: the key spacing when uniform, else 30 per second + comment: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -155040,9 +152629,7 @@ return Iqm end __FILES["model/iqm/Read"] = function() --- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and --- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). --- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. Every header range is checked before it is read. local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -155073,7 +152660,7 @@ local function half(h: number): number return s * (1 + m / 1024) * 2 ^ (e - 15) end --- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +-- normalized: integer formats scaled to 0..1 / -1..1 local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } local out = table.create(n) :: { number } local size = Read.SIZES[format] @@ -155118,7 +152705,6 @@ end local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } --- scene(b, base, limit, opts) -> Scene | nil, message function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) local size = limit - base local H: { [string]: number } = {} @@ -155169,7 +152755,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if H.num_comment > 0 then source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") end - -- vertex arrays (the whole model's vertices; meshes are ranges of them) local nv = H.num_vertexes type Array = { kind: string, name: string, format: number, comps: number, offset: number } local arrays: { Array } = {} @@ -155188,7 +152773,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) end - -- joints -> nodes + a skin local jointNodes: { number } = {} local skin: number? = nil if H.num_joints > 0 then @@ -155207,7 +152791,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: end jointNodes, skin = Rig.skeleton(scene, joints, "local") end - -- materials: one per distinct material string (IQM names its texture there) + -- materials: one per distinct material string (IQM tools name the texture there) local matOf: { [string]: number } = {} local function material(name: string): number? if name == "" then @@ -155226,7 +152810,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: matOf[name] = #scene.materials return #scene.materials end - -- meshes for m = 0, H.num_meshes - 1 do local p = base + H.ofs_meshes + m * 24 local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) @@ -155283,7 +152866,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if not attributes.POSITION then return nil, "no position array" end - -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + -- IQM's front faces are clockwise: corners 2 and 3 swap local ib = buffer.create(ct * 12) for k = 0, ct - 1 do local q = base + H.ofs_triangles + (ft + k) * 12 @@ -155304,7 +152887,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + -- frames hold the masked pose channels (offset + value * scale), in pose order if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then local np = H.num_poses local poses: { { mask: number, offset: { number }, scale: { number } } } = {} @@ -155401,16 +152984,8 @@ return Read end __FILES["model/iqm/Write"] = function() --- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines --- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights --- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins --- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse --- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world --- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are --- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), --- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. --- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). --- Plain code (the caller wraps it in pcall). +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). Blend weights are u8 summing to 255; the skeleton +-- is the union of the scene's skins, parents first; animations quantized per pose channel to 16 bits. local Types = __include("Types") local Bytes = __include("core/Bytes") local Mat4 = __include("codecs/model/Mat4") @@ -155423,7 +152998,6 @@ local Scene = Types.Scene type M4 = { number } -- ------------------------------------------------------------------------------------------------ scene walk --- world matrices (rest pose, or with a pose's overrides) and the parent of every node local function parents(scene: Types.Scene): { [number]: number } local parent: { [number]: number } = {} for i, n in scene.nodes do @@ -155472,7 +153046,6 @@ local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sa end -- ------------------------------------------------------------------------------------------------ geometry --- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points local function triangles(prim: Types.Primitive): { number }? local mode = prim.mode or "triangles" local nv = prim.attributes.POSITION.count @@ -155545,7 +153118,7 @@ local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: return out end --- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +-- the 4 strongest, u8 weights summing to 255 local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } local pairs_: { { number } } = {} for c = 1, 4 do @@ -155581,7 +153154,6 @@ local function influences(skin: Types.Skin, jointIndex: { [number]: number }, jo return list end --- appends a flat influence list to the blend index / weight arrays (4 slots) local function push4(bi: { number }, bw: { number }, list: { number }) local n = #bi for c = 1, 4 do @@ -155596,7 +153168,6 @@ type MeshOut = { name: string, material: string, first: number, count: number, t function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) local parent = parents(scene) local rest = worlds(scene, parent, nil) - -- the skeleton: every skin joint, parents first local isJoint: { [number]: boolean } = {} local ibmOf: { [number]: M4 } = {} for _, skin in scene.skins do @@ -155614,9 +153185,9 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + -- IQM wants parents first local jointList: { number } = {} - local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local jointIndex: { [number]: number } = {} local function add(n: number, depth: number) if jointIndex[n] or depth > #scene.nodes then return @@ -155673,7 +153244,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end return Mat4.decompose(m) end - -- the meshes local nodeOfMesh: { [number]: number } = {} local placed: { { node: number, mesh: number } } = {} local seen: { [number]: boolean } = {} @@ -155713,7 +153283,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri local hasTC, hasN, hasTG, hasC = false, false, false, false local tris: { number } = {} local meshes: { MeshOut } = {} - -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds local skinOf: { { number } } = {} local nvTotal = 0 for _, pl in placed do @@ -155794,7 +153363,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri else table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) end - -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + -- the 4 strongest, u8 weights summing to 255 local list: { number } if joints and weights and skinned then list = influences(skinned, jointIndex, joints, weights, v) @@ -155806,7 +153375,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri push4(BI, BW, list) skinOf[#skinOf + 1] = list end - -- triangles back to IQM's clockwise order + -- IQM's clockwise order local tfirst = #tris // 3 for k = 1, #tri, 3 do table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) @@ -155830,7 +153399,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #meshes == 0 then return nil, "nothing to write: no triangle primitives" end - -- animation frames local frames: { { { number } } } = {} -- frames[f][joint] = 10 values local anims: { { name: string, first: number, count: number, rate: number } } = {} local frameWorld: { { [number]: M4 } } = {} @@ -155840,7 +153408,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #keys > 0 then local rate = opts and opts.framerate if not rate then - -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second local dt = if #keys > 1 then keys[2] - keys[1] else 0 local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 for k = 2, #keys do @@ -155877,7 +153444,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- quantization per pose channel local masks, offsets, scales = {}, {}, {} local numChannels = 0 for j = 1, #jointList do @@ -155902,7 +153468,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end masks[j], offsets[j], scales[j] = mask, off, sc end - -- text local text = { "\0" } local textLen = 1 local textAt: { [string]: number } = { [""] = 0 } @@ -155929,7 +153494,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri str(a.name) end local comment = opts and opts.comment - -- layout local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) local H: { [string]: number } = {} local function at(): number @@ -155951,7 +153515,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri w:u32le(v) end end - -- vertex arrays: headers, then data type Arr = { typ: number, format: number, comps: number, data: { number } } local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } if hasTC then @@ -156050,7 +153613,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri while at() % 4 ~= 0 do w:u8(0) end - -- bounds of the skinned vertices per frame H.ofs_bounds = at() local skinM = table.create(#jointList) :: { M4 } for f, world in frameWorld do @@ -156109,35 +153671,9 @@ return Write end __FILES["model/ldraw"] = function() --- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and --- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked --- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. --- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + --- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines --- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at --- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried --- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing --- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). --- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without --- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main --- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = --- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one --- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines --- = false drops them); no normals, no indices (each triangle has its own three vertices). --- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise --- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or --- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. --- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge --- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig --- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered --- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> --- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). --- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node --- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = --- false leaves it out (meta.up = nil, meta.source.up = "-y"). --- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. --- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta --- commands (ignored); BFC in model files' references (models place parts as certified). +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read; File Format spec 1.0.2 with the MPD, BFC and !COLOUR extensions +-- (ldraw.org). Supports: line types 0-5, sub-files, BFC, LDConfig colours. -Y up, 1 LDU = 0.4 mm (a root node turns +-- it). Not supported: writing; !TEXMAP and !DATA; LDCad / MLCad / LPub meta commands; BFC in model files' references. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -156159,15 +153695,15 @@ local Ldraw = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths) - files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...) + resolve: ((uri: string) -> any)?, -- sub-files by library path + files: { [string]: any }?, -- or by library path ("parts/3001.dat", "p/stud.dat", ...) ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours - color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour") - upright: boolean?, -- add the root node turning -Y up into Y up (default true) - flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false) - lines: boolean?, -- type 2 edge lines as "lines" primitives (default true) - optionalLines: boolean?, -- type 5 optional lines too (default false) - maxDepth: number?, -- sub-file nesting (default 64) + color: number?, -- default 16 ("Main_Colour") + upright: boolean?, -- default true + flatten: boolean?, -- default false + lines: boolean?, -- default true + optionalLines: boolean?, -- default false + maxDepth: number?, -- default 64 maxTriangles: number?, -- default 2^24 maxNodes: number?, -- default 2^20 } @@ -156190,7 +153726,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, text, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) @@ -156202,8 +153737,6 @@ function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err end -- ------------------------------------------------------------------------------------------------ extras --- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, --- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added function Ldraw.colors(ldconfig: string?): { [number]: any } local t = Colors.builtin() if ldconfig then @@ -156216,9 +153749,8 @@ return Ldraw end __FILES["model/ldraw/Colors"] = function() --- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from --- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see --- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- model/ldraw/Colors: the LDraw colour table, parsed from !COLOUR lines. The built-in table is LDraw.org's LDConfig.ldr +-- (UPDATE 2025-05-20; CC BY 2.0, see licenses/LDRAW_COLOURS.txt), without the "0 !COLOUR " prefix and with MATERIAL cut -- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. local Colors = {} @@ -156227,7 +153759,7 @@ type Table = { [number]: Colour } local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } --- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +-- "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." function Colors.entry(rest: string): (number?, Colour?) local words: { string } = {} for w in string.gmatch(rest, "%S+") do @@ -156268,7 +153800,6 @@ function Colors.entry(rest: string): (number?, Colour?) return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } end --- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added function Colors.parse(text: string, into: Table?): Table local t: Table = into or {} for line in string.gmatch(text, "[^\n]+") do @@ -156514,7 +154045,6 @@ Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 ]] local cache: Table? = nil --- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) function Colors.builtin(): Table if not cache then local t: Table = {} @@ -156537,10 +154067,9 @@ return Colors end __FILES["model/ldraw/Read"] = function() --- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command --- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into --- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/ldraw/Read: LDraw text -> Types.Scene. Sub-files are tried as written (backslashes as slashes), then lower +-- case, under "", "parts/", "p/", "parts/s/" and "models/"; faces are written counter-clockwise after the matrices' +-- mirroring. local Types = __include("Types") local Colors = __include("model/ldraw/Colors") @@ -156560,7 +154089,7 @@ type Options = { maxNodes: number?, } --- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +-- k = 0 (a BFC state change), 1 (a reference: v = x y z a b c d e f g h i), 2..5 type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } type File = { name: string, @@ -156590,7 +154119,6 @@ local function srgbToLinear(v: number): number return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 end --- parse(text, name) -> File (colour definitions go into colours as they are met) local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } local cmds = f.cmds @@ -156634,7 +154162,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { elseif w1 == "Author:" then f.author = rest elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then - -- (headers) elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) end @@ -156690,7 +154217,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { return f end --- scene(text, opts) -> Scene | nil, message, kind function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) local o: Options = opts or {} local colours = Colors.builtin() @@ -156867,7 +154393,7 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin end end - -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + -- m is a 3x4 row-major matrix local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) if failure then return @@ -156977,7 +154503,6 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin return Types.Scene.accessor(b, "f32", 3, count) end - -- the mesh of a file baked at the identity (nil when it has no geometry) local meshOf: { [string]: number | false } = {} local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") @@ -157119,21 +154644,9 @@ return Read end __FILES["model/lwo"] = function() --- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from --- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. --- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / --- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and --- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: --- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the --- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has --- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces --- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> --- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, --- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: --- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding --- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. --- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / --- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). +-- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against +-- assimp. Supports: layers, polygons, VMAP / VMAD, surfaces, clips. Left-handed: z negated, winding reversed. Not +-- supported: LWO3, envelopes, procedural / gradient textures, planar / cylindrical / spherical projections, smoothing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -157154,8 +154667,8 @@ local Lwo = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - maxVertices: number?, -- refuse more points / polygon corners (default 2^25) + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 } -- ------------------------------------------------------------------------------------------------ constants @@ -157207,13 +154720,8 @@ return Lwo end __FILES["model/lwo/Build"] = function() --- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z --- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's --- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its --- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), --- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, --- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. --- Plain code (the caller wraps it in pcall). +-- model/lwo/Build: a parsed LightWave object -> Types.Scene. LightWave is left-handed (y up, clockwise front faces): z +-- is negated and the winding reversed, as assimp does. Vertices are split where a VMAD gives a corner its own value. local Types = __include("Types") local Parse = __include("model/lwo/Parse") @@ -157222,7 +154730,7 @@ local Build = {} local Scene = Types.Scene local writef32, writeu32 = buffer.writef32, buffer.writeu32 -type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" +type Group = { material: number, class: string, polys: { number } } -- "poly" / "patch" / "line" / "point" local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } @@ -157326,7 +154834,6 @@ local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { return groups end --- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners: { number }): { number } local n = #corners local out = table.create(n) :: { number } @@ -157342,8 +154849,8 @@ type Attr = { map: Parse.Map, name: string, comps: number } local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive local pts, pivot = layer.pts, layer.pivot local vertOf: { [number]: number } = {} - local srcPoint: { number } = {} -- vertex (1-based) -> point - local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local srcPoint: { number } = {} + local srcPoly: { number } = {} -- -1: none local indices: { number } = {} local faces: { number } = {} local madMaps: { Parse.Map } = {} @@ -157412,7 +154919,6 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) end local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } - -- the value of map m for vertex v (1-based), or nil local function value(m: Parse.Map, v: number): ({ number }?, number?) local f = srcPoly[v] if f >= 0 then @@ -157514,7 +155020,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S local scene = Scene.new() scene.meta.up = "y" scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } - -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + -- every TXUV map name, in order of first appearance, gets one TEXCOORD_n index local uvSets: { [string]: number } = {} local nuv = 0 for _, layer in m.layers do @@ -157525,7 +155031,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- materials: one per surface, then one per tag without a surface, then a default one local texCache: { [string]: number } = {} local bySurfName: { [string]: number } = {} for i, surf in m.surfaces do @@ -157567,7 +155072,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end return default :: number end - -- nodes and meshes local nodeOf: { [number]: number } = {} local layerOfNode: { Parse.Layer } = {} for _, layer in m.layers do @@ -157642,7 +155146,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + -- a parent link that would close a cycle is dropped local parentOf: { [number]: number } = {} for ni, layer in layerOfNode do local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil @@ -157678,17 +155182,9 @@ return Build end __FILES["model/lwo/Parse"] = function() --- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build --- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave --- 5.x), checked against what assimp's LWO importer reads (no code taken). --- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are --- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS --- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo --- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural --- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). --- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, --- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. --- Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/lwo/Parse: LightWave object chunks -> plain tables. From the LWO2 specification (LightWave 6 "Object Files", +-- Ernie Wright) and the LWOB one (LightWave 5.x), checked against assimp (no code taken). Several PNTS per layer: later +-- POLS / VMAP indices are relative to the latest. Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. local Bytes = __include("core/Bytes") local Chunks = __include("containers/Chunks") @@ -157698,17 +155194,17 @@ type Map = { kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" name: string, dims: number, - vals: { number }, -- per point: vals[point * dims + c + 1] + vals: { number }, -- vals[point * dims + c + 1] has: { [number]: boolean }, mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values } -type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +type Poly = { kind: string, surf: number?, corners: { number } } -- 0-based point indices type Layer = { index: number, name: string?, parent: number?, pivot: { number }, - pts: { number }, -- x, y, z flat + pts: { number }, polys: { Poly }, maps: { Map }, implicit: boolean?, -- the layer before any LAYR @@ -157729,7 +155225,7 @@ type Block = { } type Surface = { name: string, - values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + values: { [string]: number }, color: { number }, side: number, vcol: { name: string, kind: string, intensity: number }?, @@ -157741,7 +155237,7 @@ type Model = { tags: { string }, layers: { Layer }, surfaces: { Surface }, - clips: { [number]: string }, -- clip index -> path + clips: { [number]: string }, skipped: { [string]: number }, corners: number, } @@ -157758,7 +155254,7 @@ local MAP_KINDS: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ primitives --- S0: a NUL-terminated string padded to an even length +-- S0: NUL-terminated, padded to an even length local function s0(r: Bytes.Reader): string local start = r.pos local s = r:cstring() @@ -157768,7 +155264,7 @@ local function s0(r: Bytes.Reader): string return s end --- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +-- VX: 2 bytes, or 4 bytes after an 0xFF byte local function vx(r: Bytes.Reader): number if r:peekU8() == 0xFF then return r:u32be() - 0xFF000000 @@ -157781,7 +155277,7 @@ local function id4(r: Bytes.Reader): string return (string.gsub(s, " +$", "")) end --- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +-- LWO2 sub-chunks: 4-byte id, 2-byte size, padded to even local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) while p + 6 <= e do local id = buffer.readstring(buf, p, 4) @@ -157812,7 +155308,6 @@ local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? return nil end --- POLS (LWO2): returns nil or an error local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? local polys = layer.polys local npts = #layer.pts // 3 @@ -157960,7 +155455,7 @@ end local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } local function readBlock(r: Bytes.Reader, surf: Surface) - -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + -- IMAP / PROC / GRAD / SHDR header: ordinal string, header sub-chunks if r:remaining() < 6 then return end @@ -158143,7 +155638,6 @@ local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [n end -- ------------------------------------------------------------------------------------------------ the file --- parse(buf, from, limit, opts) -> Model | nil, message function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) local version = buffer.readstring(buf, from + 8, 4) local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) @@ -158195,7 +155689,7 @@ function Parse.model(buf: buffer, from: number, limit: number, maxCorners: numbe if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then err = readPolys(r, layer, kind, ptBase, budget) else - -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + -- PTAG / VMAD refer to the polygon numbering: keep it, skip the geometry local before = #layer.polys err = readPolys(r, layer, kind, ptBase, budget) model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before @@ -158231,19 +155725,9 @@ return Parse end __FILES["model/mca"] = function() --- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft --- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads --- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over --- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, --- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). --- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks --- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with --- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its --- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, --- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header --- and one chunk's NBT without building voxels. --- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the --- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). +-- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, +-- LZ4 (lz4-java blocks, 24w04a+) and stored chunks, external .mcc chunks, every chunk layout back to pre-1.13. +-- Not supported: writing; custom (127) compression; LZ4 checksums; the separate 1.17+ entities/ region files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -158267,19 +155751,19 @@ local Mca = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) - area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) - maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) - maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) - keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) - region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files - name: string?, -- the file name (the api fills it in) - resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc + chunks: { { number } }?, -- local coordinates 0 .. 31 (default all) + area: { number }?, -- world coordinates, inclusive + maxCells: number?, -- default 2^25 + maxBytes: number?, -- default 2^26 + keepNbt: boolean?, -- default true + region: { number }?, -- default: from opts.name "r...mca" + name: string?, + resolve: ((string) -> buffer?)?, -- external chunks c...mcc } type Entry = { - x: number, -- local chunk coordinates 0 .. 31 + x: number, -- 0 .. 31 z: number, - sector: number, -- 4 KiB sector of the chunk + sector: number, -- 4 KiB sectors sectors: number, timestamp: number, -- seconds since 1970 } @@ -158319,7 +155803,6 @@ function Mca.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) local n = r.limit - r.base if n < 8192 then @@ -158354,7 +155837,6 @@ local function regionCoords(o: DecodeOptions): (number?, number?) return nil, nil end --- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) local p = r.base + e.sector * 4096 if p + 5 > r.limit then @@ -158407,7 +155889,6 @@ local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, a return out, comp end --- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) local o: DecodeOptions = opts or {} if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then @@ -158475,7 +155956,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, c in chunks do lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) @@ -158505,7 +155985,7 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end if lo[2] == math.huge then - lo[2], hi[2] = 0, -1 -- no blocks at all + lo[2], hi[2] = 0, -1 end if #chunks == 0 then lo, hi = { 0, 0, 0 }, { -1, -1, -1 } @@ -158515,7 +155995,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if n > (o.maxCells or 2 ^ 25) then return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) end - -- one palette for the grid (air first), each section copied in through a remap table local states = { "minecraft:air" } local index: { [string]: number } = { ["minecraft:air"] = 0 } local grid = buffer.create(n * 2) @@ -158588,11 +156067,9 @@ return Mca end __FILES["model/mca/Chunk"] = function() --- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three --- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least --- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = --- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through --- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +-- model/mca/Chunk: an Anvil chunk's blocks (Minecraft wiki "Chunk format"): 1.18+ sections[] block_states +-- (non-spanning, >= 4 bits); 1.13 - 1.17 Level.Sections[] Palette + BlockStates (spanning before DataVersion 2529 = +-- 20w17a); pre-1.13 Blocks / Add / Data nibble arrays. A section is 16 x 16 x 16 cells, x then z then y. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -158601,14 +156078,14 @@ local Chunk = {} local Packed = Mc.Packed -type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order +type Section = { y: number, states: { string }, cells: buffer } -- u16 per cell, 4096, x-z-y order type Blocks = { - x: number, -- chunk coordinates (xPos / zPos) + x: number, -- xPos / zPos z: number, dataVersion: number?, sections: { Section }, - blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z) - entities: { any }, -- entities stored in the chunk (before 1.17) + blockEntities: { any }, -- absolute x, y, z + entities: { any }, -- before 1.17 } local function int(v: any): number? @@ -158620,7 +156097,6 @@ local function list(v: any): { any } return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} end --- a palette section (1.13+): states from the palette compounds, cells from the packed array local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) local states = table.create(#palette) :: { string } for i, c in palette do @@ -158647,7 +156123,6 @@ local function paletted(y: number, palette: { any }, data: any, minBits: number, return { y = y, states = states, cells = cells }, nil end --- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk function Chunk.blocks(root: any): (Blocks?, string?) if type(root) ~= "table" or not Types.isObject(root) then return nil, "chunk NBT is not a compound" @@ -158725,17 +156200,15 @@ return Chunk end __FILES["model/mca/Lz4Block"] = function() --- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 --- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | --- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the --- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +-- model/mca/Lz4Block: lz4-java LZ4BlockOutputStream framing (Minecraft 24w04a+, compression type 4): "LZ4Block", token +-- (0x10 raw / 0x20 LZ4 | level), compressed and decompressed lengths, XXH32 (LE i32s; not verified), then the block; +-- blocks are independent and an empty block ends the stream. local Lz4 = __include("codecs/compress/Lz4") local Lz4Block = {} local MAGIC = "LZ4Block" --- decode(buf, offset, length, maxBytes) -> buffer | nil, message function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) local p, e = offset, offset + length local parts, total = {}, 0 @@ -158797,17 +156270,9 @@ return Lz4Block end __FILES["model/md2"] = function() --- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the --- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. --- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, --- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), --- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored --- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not --- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one --- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture --- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. --- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. --- Not supported: the GL command list (the triangles carry the same geometry), writing. +-- model/md2: Quake II MD2 ("IDP2" v8), from qfiles.h dmdl_t and David Henry's "MD2 file format"; no code taken. +-- Supports: clockwise faces reversed, frames as morph targets, animations per frame-name group (10 fps), skin URIs. +-- Not supported: the GL command list, writing; Quake's normal table (not redistributable: normals are computed). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -158828,10 +156293,10 @@ local Md2 = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - frame: number?, -- the frame used as the base POSITION (1-based, default 1) - morph: boolean?, -- every frame as a morph target + the animations (default true) - fps: number?, -- animation frame rate (default 10) - maxVertices: number?, -- frames x vertices (default 2^24) + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 10 + maxVertices: number?, -- default 2^24 } -- ------------------------------------------------------------------------------------------------ constants @@ -158847,7 +156312,6 @@ function Md2.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- group frame names by their name without trailing digits, in file order local function groups(names: { string }, fps: number): { Rig.Range } local out: { Rig.Range } = {} for i, n in names do @@ -158897,13 +156361,11 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E return nil, Err.new(Err.CORRUPT, "frame size too small", 16) end local b, base = r.buf, r.base - -- skins local skins: { string } = {} for i = 0, nSkins - 1 do local s = buffer.readstring(b, base + oSkins + i * 64, 64) table.insert(skins, (string.match(s, "^[^%z]*")) :: string) end - -- weld (xyz, st) pairs local key: { [number]: number } = {} local vx: { number }, vst: { number } = {}, {} local indices: { number } = {} @@ -158938,7 +156400,6 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) end end - -- frames local frames: { buffer } = {} local normals: { buffer } = {} local names: { string } = {} @@ -159008,16 +156469,9 @@ return Md2 end __FILES["model/md3"] = function() --- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format --- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" --- notes (PhaethonH); no code taken. --- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame --- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left --- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all --- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes --- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). --- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. --- Not supported: writing. +-- model/md3: Quake III MD3 ("IDP3" v15), from qfiles.h md3Header_t / md3Surface_t and PhaethonH's "MD3 file format"; +-- no code taken. Supports: surfaces as primitives, positions in 1/64 units, lat / long normals, frames as morph +-- targets, tags as child nodes with channels. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159039,10 +156493,10 @@ local Md3 = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1) - morph: boolean?, -- every frame as a morph target + the animation (default true) - fps: number?, -- animation frame rate (default 15) - maxVertices: number?, -- frames x vertices over all surfaces (default 2^24) + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 15 + maxVertices: number?, -- default 2^24 } -- ------------------------------------------------------------------------------------------------ constants @@ -159184,7 +156638,6 @@ function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E table.insert(mesh.primitives, prim) so += oEnd end - -- frames and tags local frameNames: { string } = {} for f = 0, nFrames - 1 do frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) @@ -159244,12 +156697,8 @@ return Md3 end __FILES["model/md5"] = function() --- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim --- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from --- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by --- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless --- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom --- units, z up. Not supported: writing, .md5camera. +-- model/md5: Doom 3 / Quake 4 MD5 (MD5Version 10 text): .md5mesh and .md5anim (model/md5/Read); a mesh loads +-- opts.anims, joints matched by name. Not supported: writing, .md5camera. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159271,11 +156720,11 @@ local Md5 = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - anims: { string }?, -- .md5anim files to load with a .md5mesh + anims: { string }?, resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED) - name: string?, -- the file name (names a standalone animation) + skipMissing: boolean?, -- default false: UNSUPPORTED + name: string?, maxVertices: number?, -- default 2^24 } @@ -159329,13 +156778,8 @@ return Md5 end __FILES["model/md5/Read"] = function() --- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: --- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive --- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed --- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: --- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at --- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding --- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +-- model/md5/Read: MD5Version 10 text, from modwiki "MD5 (file format)" and David Henry's "The MD5 Mesh and Animation +-- Formats"; no code taken. The bind pose is model space, the baseframe parent-relative. local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -159423,7 +156867,7 @@ local function vec(L: Lexer, n: number): { number } return v end --- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +-- w = -sqrt(1 - x² - y² - z²) (w <= 0, as id's tools store it) local function quat(x: number, y: number, z: number): { number } local t = 1 - x * x - y * y - z * z return { x, y, z, if t < 0 then 0 else -math.sqrt(t) } @@ -159439,7 +156883,6 @@ end -- ------------------------------------------------------------------------------------------------ md5mesh type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } } --- mesh(text, opts) -> Scene, joint node indices by name | nil, message function Read.mesh(text: string, opts: Options?): (Types.Scene?, any) local L: Lexer = { text = text, pos = 1, err = nil } local joints: { MeshJoint } = {} @@ -159607,7 +157050,6 @@ type Anim = { tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame } --- anim(text) -> Anim | nil, message function Read.anim(text: string): (Anim?, string?) local L: Lexer = { text = text, pos = 1, err = nil } local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } @@ -159726,7 +157168,6 @@ function Read.anim(text: string): (Anim?, string?) return a, nil end --- addAnim(scene, nodes by joint name, anim, name) -> channels added function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number local nodes: { number } = {} local tracks: { [number]: Rig.Track } = {} @@ -159746,7 +157187,6 @@ function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, return #scene.animations[ai].channels end --- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation function Read.animScene(a: Anim, name: string): Types.Scene local scene = Scene.new() scene.meta.up = "z" @@ -159771,12 +157211,8 @@ return Read end __FILES["model/mdl"] = function() --- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: --- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the --- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), --- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = --- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx --- files) is UNSUPPORTED. +-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins +-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159798,14 +157234,14 @@ local Mdl = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey) + palette: (buffer | string)?, -- default: resolved gfx/palette.lmp, else grey resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - frame: number?, -- Quake: the frame used as the base POSITION (default 1) - morph: boolean?, -- Quake: frames as morph targets + animations (default true) - fps: number?, -- Quake: animation frame rate (default 10) - bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1) - textures: (buffer | string)?, -- Half-Life: the "t.mdl" texture file of a model without textures + frame: number?, -- Quake; default 1 + morph: boolean?, -- Quake; default true + fps: number?, -- Quake; default 10 + bodies: { number }?, -- Half-Life; 1-based, default 1 + textures: (buffer | string)?, maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -159857,16 +157293,9 @@ return Mdl end __FILES["model/mdl/HalfLife"] = function() --- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h --- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. --- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> --- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans --- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = --- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> --- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). --- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone --- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "t.mdl" (pass it --- as opts.textures = that file's bytes). +-- model/mdl/HalfLife: GoldSrc studio models ("IDST" v10), from the Half-Life SDK studio.h and HLMV / Crowbar notes; no +-- code taken. Not supported: sequence groups in other files, bone controllers, hitboxes / attachments / events, blends +-- past the first. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Pixels = __include("codecs/image/Pixels") @@ -159885,7 +157314,6 @@ local function str(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) local n, at = readi32(b, base + 180), readi32(b, base + 184) if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then @@ -159910,7 +157338,7 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number return out, names end --- one animation value: bone default + stored value * scale (frame f, 0-based) +-- bone default + stored value * scale local function animValue(b: buffer, at: number, limit: number, f: number): number? local p = at local k = f @@ -159935,7 +157363,6 @@ local function animValue(b: buffer, at: number, limit: number, f: number): numbe return nil end --- decode(b, base, size, opts) -> Scene | nil, message function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) if size < 244 then return nil, "truncated header" @@ -159964,7 +157391,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): local maxPixels = opts and opts.maxPixels or 2 ^ 24 local scene = Scene.new() scene.meta.up = "z" - -- bones local bones: { Bone } = {} local joints: { Rig.Joint } = {} for i = 0, nBones - 1 do @@ -159982,7 +157408,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): table.insert(scene.nodes, root) scene.roots[1] = 1 local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) - -- textures and skins local texSrc, texBase, texSize = b, base, size if nTex == 0 and opts and opts.textures then texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) @@ -160009,7 +157434,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 end end - -- body parts local totalVerts = 0 for part = 0, nParts - 1 do local po = base + oParts + part * 76 @@ -160031,7 +157455,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): local tex = skinMap[skinref + 1] or (skinref + 1) local img = images[tex] local tw, th = if img then img.width else 1, if img then img.height else 1 - -- triangle commands local weld: { [string]: number } = {} local corners: { { number } } = {} local indices: { number } = {} @@ -160143,7 +157566,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): table.insert(root.children, #scene.nodes) end end - -- sequences local seqs: { any } = {} for s = 0, nSeq - 1 do local so = base + oSeq + s * 176 @@ -160199,11 +157621,8 @@ return HalfLife end __FILES["model/mdl/Quake"] = function() --- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et --- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. --- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; --- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per --- side); simple and grouped frames become morph targets with one animation per frame-name group. +-- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam +-- texture coordinates of back-facing triangles move half a skin width; a skin group shows its first picture. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") local Rig = __include("codecs/model/Rig") @@ -160219,7 +157638,6 @@ local function name16(b: buffer, at: number): string return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string end --- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) if size < 84 then return nil, "truncated header" @@ -160241,7 +157659,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o local function need(n: number): boolean return n >= 0 and p + n <= size end - -- skins local pal = if palette then Pixels.palette(palette, 0, 256) else nil local skins: { Types.Image } = {} local px = sw * sh @@ -160279,7 +157696,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o table.insert(skins, img) p += count * px end - -- texture coordinates and triangles if not need(nVerts * 12 + nTris * 16) then return nil, "truncated vertices / triangles" end @@ -160317,7 +157733,7 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o table.insert(indices, c[1]) end p += nTris * 16 - -- frames: simple (type 0) or groups of simple frames + -- frames: simple (type 0) or groups local frameAt: { number } = {} local names: { string } = {} local fsize = 24 + nVerts * 4 @@ -160423,20 +157839,9 @@ return Quake end __FILES["model/ms3d"] = function() --- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of --- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested --- against (no code ported). --- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and --- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in --- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; --- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use --- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse --- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes --- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, --- the model comment / fps / frames / joint size in meta.source. meta.up = "y". --- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), --- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 --- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). +-- model/ms3d: MilkShape 3D 1.8 (.ms3d v3 / v4), from ms3dspec.h, tested against assimp's MS3D importer (no code +-- ported). Supports: groups, materials, joints, a skin, keyframes, comments and the extra blocks, read + write. Not +-- supported: scale keys (MilkShape has none), a second skin; writes at most 65535 vertices, 255 groups, 127 joints. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -160457,12 +157862,12 @@ local Ms3d = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxVertices: number?, -- refuse more triangle corners (default 2^20) + maxVertices: number?, -- default 2^20 } type EncodeOptions = { - fps: number?, -- the animation's frames per second (default: the source's, else 24) - name: string?, -- the destination's file name (names textures that have no uri) - files: { [string]: any }?, -- receives the bytes of textures that have data but no uri + fps: number?, -- default: the source's, else 24 + name: string?, + files: { [string]: any }?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -160477,7 +157882,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) @@ -160507,17 +157911,9 @@ return Ms3d end __FILES["model/ms3d/Read"] = function() --- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h --- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a --- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess --- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and --- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds --- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), --- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), --- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). --- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices --- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + --- key positions). Never throws on bad data: returns nil, message, offset. +-- model/ms3d/Read: the ms3dspec.h layout: vertices, triangles, groups, materials (shininess 0..128), the animation +-- header, joints (local Euler XYZ radians, keys in seconds relative to the rest pose), then the sub-versioned comments, +-- vertex extras (weights in percent, subversion 1-3), joint extras (colours) and model extras. Never throws. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -160570,7 +157966,6 @@ type Joint = { rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, } --- scene(b, base, limit, opts) -> Scene | nil, message, offset function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) local p = base local function need(n: number): boolean @@ -160585,7 +157980,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty end p += 14 local maxV = opts and opts.maxVertices or 2 ^ 20 - -- vertices if not need(2) then return nil, "truncated vertex count", p end @@ -160600,7 +157994,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } end p += nv * 15 - -- triangles if not need(2) then return nil, "truncated triangle count", p end @@ -160614,7 +158007,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty end local triAt = p p += nt * 70 - -- groups if not need(2) then return nil, "truncated group count", p end @@ -160643,7 +158035,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty p += 1 table.insert(groups, g) end - -- materials if not need(2) then return nil, "truncated material count", p end @@ -160662,7 +158053,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty }) end p += nm * 361 - -- animation header and joints (version 3 files may end here) + -- version 3 files may end here local fps, current, frames = 24, 0, 0 local joints: { Joint } = {} if need(12) then @@ -160697,7 +158088,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty table.insert(joints, j) end end - -- sub-versioned blocks local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } local function comments(list: { any }): string? if not need(4) then @@ -160791,7 +158181,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } local scene = S.new() scene.meta.up = "y" scene.meta.source = source :: any - -- materials, textures for _, m in mats do local mat = S.material(m.name) local d = m.diffuse @@ -160813,7 +158202,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } } table.insert(scene.materials, mat) end - -- joints: nodes, rest pose, skin local nj = #joints local jointNode: { [number]: number } = {} local byName: { [string]: number } = {} @@ -160863,7 +158251,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } end scene.skins[1] = { joints = list, inverseBindMatrices = ibm } end - -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner local nv = #verts for gi, g in groups do local remap: { [string]: number } = {} @@ -160873,7 +158260,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } local count = 0 for _, ti in g.tris do local q = triAt + ti * 70 - -- a triangle with an out-of-range vertex is dropped if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then continue end @@ -160890,7 +158276,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } table.move(v.pos, 1, 3, o * 3 + 1, P) N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) - -- influences: the valid bones, weights normalized local sum = 0 for c = 1, 4 do if v.bones[c] >= 0 then @@ -160937,7 +158322,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- the animation: rest * key rotations, rest + key positions local channels: { Types.Channel } = {} for i, j in joints do if #j.rotKeys > 0 then @@ -160973,15 +158357,8 @@ return Read end __FILES["model/ms3d/Write"] = function() --- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, --- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first --- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); --- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each --- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's --- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: --- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and --- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), --- joint colours and model extras are written in their sub-versioned blocks. +-- model/ms3d/Write: Scene -> MilkShape 3D v4: a group per placed primitive, the first skin's joints (rest pose from +-- the inverse bind matrices, keys relative to it), vertex extras subversion 2 (weights in percent). local Bytes = __include("core/Bytes") local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -161031,14 +158408,11 @@ end -- ------------------------------------------------------------------------------------------------ joints type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } --- the rigid part (rotation and translation) of a matrix local function rigid(m: { number }): { number } local t, r = Mat4.decompose(m) return Mat4.compose(t, r, nil) end --- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; --- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) local skin = scene.skins[1] local anim = scene.animations[1] @@ -161059,7 +158433,6 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num table.insert(chans[ch.node], ch) end end - -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix local B = S.IDENTITY local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil if skin and IBM and tr.world[skin.joints[1]] then @@ -161078,8 +158451,7 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num while p ~= 0 and byNode[p] == nil do p = tr.parent[p] end - -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the - -- joint and its joint parent (C) carry over to the keys + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() local gp = tr.parent[ni] local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) @@ -161132,7 +158504,6 @@ type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { n type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } --- every placed primitive as a group: vertices, triangles; or nil, message local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} for _, pl in S.flatten(scene) do @@ -161149,7 +158520,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number continue end local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil - -- a rigid mesh follows its nearest joint local rigid = -1 if not skinned then local p = pl.node @@ -161231,7 +158601,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number b, c = c, b end local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } - -- the face normal for primitives without normals local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z @@ -161317,7 +158686,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end w:i8(g.material % 256) end - -- materials w:u16le(#scene.materials) local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" for i, m in scene.materials do @@ -161349,7 +158717,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) fixedString(w, file, 128) fixedString(w, msg(x.alphamap), 128) end - -- the animation header and joints local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) local last = 0 for _, j in js do @@ -161386,7 +158753,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end end end - -- comments w:u32le(1) local function comments(list: { any }, get: (any) -> string?) local found = {} @@ -161439,7 +158805,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end w:u32le(0) end - -- joint colours, model extras w:u32le(1) for _, j in js do local x: any = scene.nodes[j.node].extras @@ -161461,19 +158826,9 @@ return Write end __FILES["model/obj"] = function() --- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp --- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form --- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR --- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line --- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", --- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false --- keeps OBJ's). --- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. --- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. --- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups --- (s: kept per node in extras.obj.smoothing, not used to compute normals). --- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to --- opts.files[.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. +-- model/obj: Wavefront OBJ + MTL (Paul Bourke's specs, as Blender / Maya / assimp write them). Supports: v (with +-- "v x y z r g b"), vt, vn, f in every index form, l, p, o / g, usemtl / mtllib, continuations; TEXCOORD_0 flipped to +-- top-left. Not supported: free-form geometry (curv, surf: skipped), smoothing groups (kept in extras.obj.smoothing). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -161493,21 +158848,21 @@ local Obj = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) - mtl: (string | buffer)?, -- the material library text, when not found through resolve / files - resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the other files by name + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + mtl: (string | buffer)?, + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) } type EncodeOptions = { - name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl") - mtlName: string?, -- the .mtl file name (overrides name) - files: { [string]: any }?, -- receives the .mtl and embedded textures + name: string?, -- default "model.mtl" + mtlName: string?, + files: { [string]: any }?, flipV: boolean?, -- default true (the inverse of decode) - normals: boolean?, -- write vn (default true when the primitives have NORMAL) - texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0) - colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists) + normals: boolean?, -- default true when the primitives have NORMAL + texcoords: boolean?, -- default true when the primitives have TEXCOORD_0 + colors: boolean?, -- default true when COLOR_0 exists } -- ------------------------------------------------------------------------------------------------ sniff @@ -161608,7 +158963,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end return p end - -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil local function corner(tok: string): (number?, number, number) local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") local vi = tonumber(a) @@ -161642,7 +158996,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local line = string.sub(text, pos, e - 1) pos = e + 1 lineNo += 1 - -- continuation lines while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do line = string.gsub(line, "\\\r?$", " ") local e2 = string.find(text, "\n", pos, true) or (len + 1) @@ -161654,7 +159007,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if key == nil or string.sub(key, 1, 1) == "#" then continue end - local rest: string = rest :: string -- both captures match together + local rest: string = rest :: string local hash = string.find(rest, "#", 1, true) if hash then rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") @@ -161728,7 +159081,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end if mode == "triangles" and k > 3 then - -- fan: rewrite the k corners as (k - 2) triangles local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 2, k - 1 do @@ -161738,7 +159090,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end elseif mode == "lines" then - -- a polyline -> segments local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 1, k - 1 do @@ -161771,7 +159122,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E skipped += 1 end end - -- materials local scene = Types.Scene.new() local matIndex: { [string]: number } = {} local texIndex: { [string]: number } = {} @@ -161816,7 +159166,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- materials named by usemtl but not defined anywhere: a default one with the name + -- usemtl of an undefined material: a default one with that name for _, s in sections do for _, p in s.prims do if p.material and not matIndex[p.material] then @@ -161826,7 +159176,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- vertices: one per distinct (v, vt, vn) in each primitive local f32 = buffer.writef32 local KT, KN = nt + 1, nn + 1 local numericKeys = np * KT * KN < 2 ^ 52 @@ -161896,7 +159245,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end return out end - -- nodes: objects at the root, their groups as children; without objects every group is a root local objectNode: { [string]: number } = {} for _, s in sections do if #s.prims > 0 then @@ -161925,7 +159273,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E objectNode[s.object] = #scene.nodes table.insert(scene.roots, #scene.nodes) elseif hasObjects and s.object and objectNode[s.object] then - -- the object's own faces after its groups: a child too table.insert(scene.nodes, node) table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) else @@ -161950,7 +159297,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- the shortest decimal that reads back as the same f32 local probe = buffer.create(4) local function f32str(v: number): string if v ~= v or v == math.huge or v == -math.huge then @@ -161989,7 +159335,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local placed = Types.Scene.flatten(scene) local out = { "# written by rosetta" } local mats = scene.materials or {} - -- material names (unique), texture file names local names: { string } = {} local used: { [string]: boolean } = {} for i, m in mats do @@ -162057,7 +159402,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") end end - -- the normal matrix (inverse transpose) for baked normals local nm: { number }? = nil if Nr and not ident then local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] @@ -162109,7 +159453,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end return s end - -- the corner list local ind = prim.indices local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil local count = if ind then ind.count else n @@ -162205,7 +159548,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end -- ------------------------------------------------------------------------------------------------ extras --- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) if type(scene) ~= "table" or type(scene.materials) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") @@ -162226,10 +159568,8 @@ return Obj end __FILES["model/obj/Mtl"] = function() --- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, --- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping --- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the --- reverse (from extras.obj when present, else from the PBR fields). +-- model/obj/Mtl: Wavefront .mtl (Paul Bourke's MTL spec + the PBR extension: Pr, Pm, Ps, Pc, Pcr, aniso, anisor, Ke, +-- map_Pr, map_Pm, map_Ke, norm); Phong values are kept in extras.obj. local Types = __include("Types") local Mtl = {} @@ -162262,7 +159602,6 @@ local function parseMap(args: { string }): Map end end else - -- -o / -s / -t: up to three numbers while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do table.insert(vals, args[i]) i += 1 @@ -162275,7 +159614,6 @@ local function parseMap(args: { string }): Map return { file = file, options = opts } end --- parse(text) -> { Entry } in file order function Mtl.parse(text: string): { Entry } local out: { Entry } = {} local cur: Entry? = nil @@ -162323,7 +159661,6 @@ function Mtl.mime(file: string): string? return if ext then MIME[string.lower(ext)] else nil end --- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material local m = Types.Scene.material(e.name) local v = e.values @@ -162371,7 +159708,6 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material if m.emissiveTexture and not ke then m.emissive = { 1, 1, 1 } end - -- everything else as it was, for the writer and for Phong renderers local extra: { [string]: any } = {} for k, vals in v do extra[k] = vals @@ -162398,7 +159734,6 @@ local function num(v: number): string end Mtl.num = num --- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string local out = { "# written by rosetta" } for i, m in materials do @@ -162417,7 +159752,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile end order = table.clone(saved.order or {}) end - -- the PBR fields win over the saved Phong values they map to local bc = m.baseColor or { 1, 1, 1, 1 } values.Kd = { bc[1], bc[2], bc[3] } if (bc[4] or 1) < 1 or values.d then @@ -162462,7 +159796,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile setMap("norm", m.normalTexture) end setMap("map_ORM", m.metallicRoughnessTexture) - -- the saved order first, then the rest sorted local keys = {} local seen = {} for _, k in order do @@ -162522,23 +159855,9 @@ return Mtl end __FILES["model/off"] = function() --- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description --- (geomview.org/docs/html/OFF.html). --- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the --- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; --- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 --- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). --- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; --- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are --- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or --- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single --- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". --- meta.source = { format, keyword, vertices, faces, edges }. --- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes --- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons --- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are --- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF --- (UNSUPPORTED). +-- model/off: Geomview OFF text (geomview.org/docs/html/OFF.html), read + write. Supports: [ST][C][N]OFF, face colours +-- (prim.extras.faceColors), n-gons (fan-triangulated or "polygons"), point clouds; floats as %.9g (f32-exact). +-- Not supported: 4OFF / nOFF, binary OFF; colormap-index face colours are ignored. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -162558,15 +159877,15 @@ local Off = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + triangulate: boolean?, -- default true maxVertices: number?, -- default 2^24 maxFaces: number?, -- default 2^25 } type EncodeOptions = { - colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true) - normals: boolean?, -- write NORMAL (NOFF) when present (default true) - texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true) - comment: string?, -- a "# ..." line after the header keyword + colors: boolean?, -- default true + normals: boolean?, -- default true + texcoords: boolean?, -- default true + comment: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -162575,7 +159894,7 @@ local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writ -- ------------------------------------------------------------------------------------------------ sniff function Off.sniff(r: Bytes.Reader): number local head = r:peek(512) - for _ = 1, 16 do -- leading comment lines + for _ = 1, 16 do local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") if not rest then break @@ -162590,14 +159909,13 @@ function Off.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +-- unorm8 when every value is an integer and some value is above 1, else f32 type ColorSet = { values: { number }, float: boolean, max: number } local function colorType(c: ColorSet): string return if not c.float and c.max > 1 then "unorm8" else "f32" end --- the colour accessor for count entries of 4 values (nan = absent: opaque white) local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) local t = colorType(c) local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) @@ -162632,7 +159950,7 @@ local function addColor(c: ColorSet, toks: { string }, from: number, n: number) c.max = v end else - table.insert(vals, 0 / 0) -- absent: full (opaque white) + table.insert(vals, 0 / 0) end end end @@ -162645,7 +159963,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local maxVertices = opts and opts.maxVertices or 2 ^ 24 local maxFaces = opts and opts.maxFaces or 2 ^ 25 local text = buffer.readstring(r.buf, r.base, r.limit - r.base) - -- the next non-empty line's tokens (comments stripped) local at = 1 local lineNo = 0 local function line(): { string }? @@ -162711,7 +160028,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if nf > maxFaces then return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) end - -- every vertex / face line takes at least 6 / 2 bytes if nv * 6 + nf * 2 > #text - at + 2 then return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") end @@ -162796,7 +160112,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E addColor(fcol, t, 1, 0) end end - -- the primitive local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } if nrm then attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) @@ -162890,7 +160205,6 @@ local function fnum(v: number): string? return string.format("%.9g", v) end --- a colour attribute's 4 components of entry i (0-based) as text local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string local out = table.create(4) for c = 1, 4 do @@ -162952,7 +160266,6 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end table.insert(out, s) end - -- face colours of a single primitive (per file face, or through faceOfTriangle) local fc: Flatten.Attr? = nil local fcMap: { number }? = nil if wantC and #m.parts == 1 and nf > 0 then @@ -163004,26 +160317,9 @@ return Off end __FILES["model/ply"] = function() --- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, --- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). --- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> --- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u --- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> --- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's --- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are --- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are --- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", --- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face --- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after --- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, --- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments --- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and --- types. meta.source = { format, encoding, vertices, faces }. --- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, --- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces --- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when --- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. --- Not supported: list properties in the vertex element (UNSUPPORTED). +-- model/ply: Stanford PLY (Greg Turk 1994; paulbourke.net/dataformats/ply, rply / plyfile behaviour), ascii and +-- binary either endian, read + write. Supports: every property type, faces (fan-triangulated or "polygons"), point +-- clouds; other elements, comments, obj_info and property order round-trip. Not supported: vertex list properties. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -163044,13 +160340,13 @@ local Ply = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + triangulate: boolean?, -- default true maxVertices: number?, -- default 2^24 maxFaces: number?, -- faces, and rows of any other element (default 2^25) } type EncodeOptions = { format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" - comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) + comments: { string }?, } type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } @@ -163120,7 +160416,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) if first then first = false -- "ply" elseif kw == nil then - -- blank line elseif kw == "end_header" then h.dataStart = base + at - 1 break @@ -163180,7 +160475,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) return h, nil end --- the reading plan of one element: per property, where its values go type Plan = { code: { number }, isList: { boolean }, @@ -163218,7 +160512,6 @@ local function newPlan(e: Elem): Plan return pl end --- unset scalar destinations get their own native buffer local function ownBuffers(e: Elem, pl: Plan) for k, p in e.props do if not p.list and pl.dst[k] == nil then @@ -163227,7 +160520,6 @@ local function ownBuffers(e: Elem, pl: Plan) end end --- read one element's rows (binary) into the plan; returns the next offset or nil, Err local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) local b, limit, n, np = r.buf, r.limit, e.count, #e.props local hasList, rowSize = false, 0 @@ -163272,7 +160564,6 @@ local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boo return q, nil end --- a token as a value of type code, or nil local function value(tok: string?, code: number): number? if tok == nil then return nil @@ -163288,7 +160579,6 @@ local function value(tok: string?, code: number): number? return v end --- read one element's rows (ascii) from the token stream local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? ownBuffers(e, pl) local n = e.count @@ -163357,7 +160647,6 @@ local function propIndex(e: Elem, name: string): number? return nil end --- vertex element -> attributes: sets the plan's destinations, returns the attribute table local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) local nv = e.count local attrs: { [string]: Types.Accessor } = {} @@ -163367,7 +160656,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") end end - -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) local ks: { [number]: number } = {} local codes = {} @@ -163413,7 +160701,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er end group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) - -- colours: one type class for all channels do local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") if rk and gk and bk then @@ -163452,7 +160739,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er return attrs, nil end --- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) local nt = 0 for f = 0, nf - 1 do @@ -163518,7 +160804,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end if ascii then local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) - -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating local need = 0 for _, e in h.elems do need += e.count * #e.props @@ -163532,7 +160817,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local attrs: { [string]: Types.Accessor } = {} local p = h.dataStart if not ascii then - -- every row takes at least its scalar sizes and list counts: bound the counts before allocating local need = 0 for _, e in h.elems do local row = 0 @@ -163571,7 +160855,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E p = q end end - -- the primitive local prim: Types.Primitive = { attributes = attrs, mode = "points" } local nf = 0 local extras: { [string]: any } = {} @@ -163635,7 +160918,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if next(extras) then prim.extras = extras end - -- raw elements, element order, property order local elements: { any } = {} local order: { string } = {} for i, e in h.elems do @@ -163667,7 +160949,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } @@ -163675,7 +160956,6 @@ local function keep(name: string): boolean return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" end --- the spelling `want` from the source file when it means the same type as code, else the classic name local function spell(want: string?, code: number): string if want and CODES[want] == code then return want @@ -163694,7 +160974,6 @@ local function toInt(v: number, code: number): number return v end --- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } local function rowsAscii(out: { string }, n: number, cols: { Row }) @@ -163767,7 +161046,6 @@ local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean w.pos = o end --- numbers of a raw element column (buffer of a ply type) local function bufNumbers(b: any, code: number, count: number): { number }? if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then return nil @@ -163779,7 +161057,6 @@ local function bufNumbers(b: any, code: number, count: number): { number }? return out end --- the list count type for a maximum count local function countCodeFor(maxCount: number): number return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 end @@ -163796,7 +161073,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} local nv = m.count - -- source property spellings / order local srcType: { [string]: string } = {} local srcOrder: { [string]: number } = {} if type(meta.vertexProperties) == "table" then @@ -163827,7 +161103,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if C then local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 if C.raw and code == 7 then - -- another normalized type: as floats local vals = table.create(#C.values) local scale = if C.type == "snorm8" then 127 else 32767 for i, v in C.values do @@ -163893,7 +161168,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- the source order first (stable for the rest) local rank: { [Column]: number } = {} for i, c in cols do rank[c] = (srcOrder[c.name] or (1000000 + i)) @@ -163901,7 +161175,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err table.sort(cols, function(a: Column, b: Column): boolean return rank[a] < rank[b] end) - -- faces local faceRows: { Row }? = nil local nf = 0 if m.sizes then @@ -163934,7 +161207,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local rows: { Row } = { { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, } - -- per-face data of a single primitive if #m.parts == 1 then local ex = m.parts[1].prim.extras local fot: { number }? = nil @@ -163989,7 +161261,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- the source order, then the rest by name local placed: { [string]: boolean } = { [idxName] = true } local ordered: { Row } = {} for _, fp in fprops do @@ -164019,7 +161290,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end faceRows = rows end - -- raw elements type Raw = { name: string, count: number, rows: { Row } } local raws: { [string]: Raw } = {} local rawOrder: { string } = {} @@ -164062,7 +161332,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- element order: the source's, then vertex, face, the rest local order: { string } = {} local seen: { [string]: boolean } = {} local function want(name: string) @@ -164086,7 +161355,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err for _, name in rawOrder do want(name) end - -- header local vrows: { Row } = {} for _, c in cols do table.insert(vrows, { kind = "s" :: "s", col = c }) @@ -164156,11 +161424,8 @@ __FILES["model/ply/Binary"] = @native function() --- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, --- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of --- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the --- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list --- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +-- model/ply/Binary: PLY element data loops; type codes 1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, 7 f32, 8 f64, either +-- byte order. Never throws: the caller bounds every row first. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64 = buffer.readf32, buffer.readf64 local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 @@ -164177,7 +161442,6 @@ local scratch = buffer.create(8) return rshift(v, 8) + band(v, 255) * 256 end --- rd(b, q, code, be) -> the value at q @native local function rd(b: buffer, q: number, code: number, be: boolean): number if not be then if code == 7 then @@ -164218,7 +161482,6 @@ end end Binary.rd = rd --- wr(d, o, code, v): v as code, little endian @native local function wr(d: buffer, o: number, code: number, v: number) if code == 7 then writef32(d, o, v) @@ -164240,7 +161503,6 @@ Binary.rd = rd end Binary.wr = wr --- put(d, o, code, v, be): v as code in either byte order (the writer) @native function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) if not be or code <= 2 then wr(d, o, code, v) @@ -164257,7 +161519,6 @@ Binary.wr = wr end end --- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p @native function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) for k = 1, np do local sc, dc, d = code[k], dCode[k], dst[k] @@ -164290,8 +161551,6 @@ end end end --- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, --- or -1, message (truncated rows, a negative / fractional count) @native function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) local totals = table.create(np, 0) local q = p @@ -164323,10 +161582,6 @@ end return q, totals end --- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. --- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their --- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows --- must have passed scan() with the same arguments. @native function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) local at = table.create(np, 0) local q = p @@ -164368,19 +161623,9 @@ return Binary end __FILES["model/pmx"] = function() --- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD --- format, as documented by the MMD community). New code, no third-party code. --- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / --- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / --- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one --- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, --- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon --- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; --- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), --- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras --- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the --- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). --- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. +-- model/pmx: MikuMikuDance PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (MMD community notes); no +-- third-party code. Supports: every deform type, materials, bones and IK, vertex morphs as morph targets, the other +-- morphs, frames, rigid bodies and joints as extras. Not supported: writing, 2.1 soft bodies, VMD / VPD. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -164402,11 +161647,11 @@ local Pmx = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) - resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) - morphs: boolean?, -- vertex morphs as morph targets (default true) + files: { [string]: any }?, -- "/" or "\" separators, or the base name + resolve: ((uri: string) -> any)?, + morphs: boolean?, -- default true maxVertices: number?, -- default 2^24 - maxBytes: number?, -- morph target bytes (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -164447,13 +161692,8 @@ return Pmx end __FILES["model/pmx/Build"] = function() --- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, --- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed --- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with --- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as --- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex --- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative --- translation each) and one skin with translation-only inverse bind matrices. +-- model/pmx/Build: the PMX / PMD model table to a Scene. MMD is left-handed (y up, x right, z forward): z is negated +-- and every winding reversed; UVs are already top-left. local Types = __include("Types") local Build = {} @@ -164465,7 +161705,6 @@ local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } --- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve local function fetcher(opts: any): (string) -> buffer? return function(uri: string): buffer? if not opts then @@ -164488,7 +161727,6 @@ local function lh(v: { number }?): { number }? return if v then { v[1], v[2], -v[3] } else nil end --- the scene index of a file texture index (0-based, -1 = none) local function texIndex(m: any, i: number?): number? return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil end @@ -164521,7 +161759,6 @@ local function material(m: any, mat: any): Types.Material return out end --- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root local function parents(bones: { any }): { number } local nb = #bones local par = table.create(nb, 0) @@ -164546,7 +161783,6 @@ local function parents(bones: { any }): { number } return par end --- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive local map: { [number]: number } = {} local verts: { number } = {} @@ -164598,7 +161834,6 @@ local function primitive(m: any, first: number, n: number, morphs: { any }, sdef for a, acc in uvas do buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) end - -- weights: invalid bones get weight 0, the rest is normalized local sum = 0 local js, ws = table.create(4, 0), table.create(4, 0) for c = 0, 3 do @@ -164665,7 +161900,6 @@ function Build.scene(m: any, opts: any): (any, ...any) scene.materials[i] = material(m, mat) end - -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) local vmorphs, names, others = {}, {}, {} local wantMorphs = not (opts and opts.morphs == false) for _, mo in m.morphs do @@ -164701,7 +161935,6 @@ function Build.scene(m: any, opts: any): (any, ...any) first += n end if first < m.indexCount then - -- faces no material covers table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) end mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } @@ -164710,7 +161943,6 @@ function Build.scene(m: any, opts: any): (any, ...any) end scene.meshes[1] = mesh - -- nodes: 1 = the model, 2 = the mesh, then one per bone scene.nodes[1] = { name = m.name, children = { 2 } } scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } scene.roots[1] = 1 @@ -164756,13 +161988,8 @@ return Build end __FILES["model/pmx/Pmd"] = function() --- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as --- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community --- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, --- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to --- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in --- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in --- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +-- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are +-- Shift-JIS: kept when ASCII, else the English name, else the raw bytes (`nameSjis`). Never throws. local Bytes = __include("core/Bytes") local Pmd = {} @@ -164853,7 +162080,7 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a r.pos += ni * 2 m.indexCount, m.indices = ni, ind - -- materials: 70 bytes each; texture names collected into the texture list + -- materials: 70 bytes each local nm = r:u32le() ok, e = counted(r, nm, 70, "materials") if r.err or not ok then @@ -164916,7 +162143,6 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a m.bones[i] = b end - -- IK chains local nik = r:u16le() for _ = 1, nik do local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() @@ -165097,13 +162323,8 @@ return Pmd end __FILES["model/pmx/Read"] = function() --- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that --- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. --- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices --- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, --- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, --- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). --- Never throws: returns nil, message[, kind]. +-- model/pmx/Read: PMX 2.0 / 2.1, from the specification notes that ship with PmxEditor; values as in the file +-- (left-handed, 0-based indices); 2.1 soft bodies are counted, not parsed. Never throws. local Bytes = __include("core/Bytes") local Text = __include("codecs/text/Text") @@ -165131,7 +162352,7 @@ local function vec(r: Bytes.Reader, n: number): { number } return v end --- a count field: i32 >= 0 and at most remaining / minSize records +-- a count field: i32 >= 0 local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) local n = r:i32le() if r.err then @@ -165304,7 +162525,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... r.pos = p + ni * vsize m.indexCount, m.indices = ni, ind - -- textures local nt nt, e, k = count(r, 4, "textures") if not nt then @@ -165315,7 +162535,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.textures[i] = text() end - -- materials local nm nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") if not nm then @@ -165340,7 +162559,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.materials[i] = mat end - -- bones local nb nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") if not nb then @@ -165388,7 +162606,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.bones[i] = b end - -- morphs local nmo nmo, e, k = count(r, 8 + 2 + 4, "morphs") if not nmo then @@ -165409,7 +162626,7 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... return nil, e, k end if t == 1 then - -- vertex morphs: packed (index list + deltas), they become morph targets + -- vertex morphs: packed (index list + deltas) local vi, d = table.create(no), buffer.create(no * 12) for o = 1, no do local x = vidx() @@ -165510,17 +162727,9 @@ return Read end __FILES["model/qb"] = function() --- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the --- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA --- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 --- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. --- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as --- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view --- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and --- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). --- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; --- options default to the source file's settings. --- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. +-- model/qb: Qubicle Binary (.qb 1.1.0.0, minddesk.com "Qubicle Binary"), read + write. Supports: RGBA / BGRA, left- or +-- right-handed z, plain or RLE matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 per z slice), the alpha visibility mask, named +-- matrices with a position. Not supported: Qubicle Exchange (.qbt / .qbcl). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -165539,13 +162748,13 @@ local Qb = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) + maxCells: number?, -- default 2^27 } type EncodeOptions = { - compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) + compressed: boolean?, -- default: the source's, else true colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" - rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) - visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) + rightHanded: boolean?, -- default: the source's, else true + visibilityMask: boolean?, -- default: the source's, else false } -- ------------------------------------------------------------------------------------------------ constants @@ -165567,7 +162776,6 @@ function Qb.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them local function indexed(v: Types.Voxels, colors: buffer, n: number) local count: { [number]: number } = {} for i = 0, n - 1 do @@ -165848,7 +163056,6 @@ function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 end - -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked local function value(x: number, y: number, z: number): number local zz = if right then z else sz - 1 - z local c = cellColor(v, x + sx * (y + sy * zz)) @@ -165913,17 +163120,9 @@ return Qb end __FILES["model/rbxm"] = function() --- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, " "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +-- an INST chunk that marks services makes a place function Rbxm.variant(r: Bytes.Reader): string? local b, p, e = r.buf, r.base + 32, r.limit if r:peek(14) ~= MAGIC then @@ -165997,7 +163196,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Class = { id: number, name: string, refs: { number }, service: boolean } --- a length-prefixed string at p of b (limit e): string, next | nil local function str(b: buffer, p: number, e: number): (string?, number) if p + 4 > e then return nil, p @@ -166206,7 +163404,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) end parented[child] = true - -- refuse cycles: the parent may not be a descendant of the child local up: Rbx.Instance? = parent while up do if up == child then @@ -166225,7 +163422,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err if not ended then return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) end - -- instances PRNT does not mention are roots for _, inst in order do if not parented[inst] then table.insert(tree.roots, inst) @@ -166243,7 +163439,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err end -- ------------------------------------------------------------------------------------------------ encode --- the binary type of a property over a class's instances: type id, type name | nil, message local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?) local id, tname = nil, nil for _, inst in insts do @@ -166295,7 +163490,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local compress = o.compression ~= "none" local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true - -- every instance depth first; referents in that order local insts: { Rbx.Instance } = {} local refOf: { [any]: number } = {} local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {} @@ -166323,7 +163517,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, e end end - -- classes by name local byClass: { [string]: { Rbx.Instance } } = {} local names = {} for _, inst in insts do @@ -166336,7 +163529,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(list, inst) end table.sort(names) - -- shared strings, in order of first use local sharedIdx: { [string]: number } = {} local sharedList: { string } = {} local ctx: Binary.Ctx = { @@ -166411,7 +163603,7 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) putStr(pw, pn) local tid = t :: number if tid == -1 then - -- Raw: the column read from a file, written back only when this class still has exactly its instances + -- Raw: written back only when this class still has exactly its instances local first = list[1].properties[pn] local raw = first and first.value local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" @@ -166520,20 +163712,10 @@ return Rbxm end __FILES["model/rbxmx"] = function() --- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, ``), read + write, to and from --- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). --- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. --- Decode: , with of every type codecs/model/Rbx lists (string, BinaryString --- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), --- token, BrickColor (as rbx-dom: an ; read back as BrickColor for the BrickColor properties of a short --- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, --- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, --- PhysicalProperties, Ref, SharedString (+ ), UniqueId, Font, SecurityCapabilities); unknown property --- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. --- tree.place is true when a root is a Workspace (rbxlx). --- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, --- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control --- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. +-- model/rbxmx: Roblox XML model / place (.rbxmx / .rbxlx, ``) to and from a codecs/model/Rbx +-- RbxTree, from the rbx-dom notes (docs/xml.md), checked against rojo 7.7 and lune 0.11. Supports: every type +-- codecs/model/Rbx lists; unknown tags round-trip as "XmlRaw". Encode follows rbx-dom's layout. +-- Not supported: writing "Raw" values. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -166555,17 +163737,16 @@ local Rbxmx = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxDepth: number?, -- XML nesting limit (default 10000) + maxDepth: number?, -- default 10000 } type EncodeOptions = { - indent: (number | string)?, -- default 2 spaces; 0 for none + indent: (number | string)?, -- default 2; 0 for none } -- ------------------------------------------------------------------------------------------------ constants local XmlNode = Xml.element local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch --- tag name -> type name for the simple (text) types local SCALAR_TAGS: { [string]: string } = { string = "String", ProtectedString = "ProtectedString", @@ -166602,7 +163783,7 @@ function Rbxmx.sniff(r: Bytes.Reader): number return 0 end --- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +-- a Workspace item makes a place function Rbxmx.variant(r: Bytes.Reader): string? local text = buffer.readstring(r.buf, r.base, r.limit - r.base) return if find(text, ' type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs --- come back as { pending = referent }) local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) local tag = node.name local scalar = SCALAR_TAGS[tag] @@ -166819,7 +163998,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end local tree = Rbx.tree() tree.meta.source = { format = "rbxmx", version = root.attrs.version } - -- shared strings first (properties name them by key) local shared: { [string]: string } = {} for _, ss in Xml.children(root, "SharedStrings") do for _, s in Xml.children(ss, "SharedString") do @@ -166831,7 +164009,7 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end end local byRef: { [string]: Rbx.Instance } = {} - local pending: { { any } } = {} -- { value table, field, referent } + local pending: { { any } } = {} local function item(node: Xml.Node, parent: any): Err.Err? local cls = node.attrs.class if type(cls) ~= "string" then @@ -166902,7 +164080,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end -- ------------------------------------------------------------------------------------------------ encode --- the shortest text that reads back as the same float (single: f32 values; else f64) local function fmt(v: any, single: boolean?): string if type(v) ~= "number" then v = 0 @@ -166956,7 +164133,6 @@ local function xmlSafe(s: string): boolean return utf8.len(s) ~= nil end --- a property -> its element, or nil to skip local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node? local t, x = v.type, v.value local a = { name = name } @@ -167189,24 +164365,9 @@ return Rbxmx end __FILES["model/robloxmesh"] = function() --- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh --- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. --- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, --- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown --- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes --- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC --- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed --- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in --- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' --- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes --- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw --- (meta.source.facs). meta.up = "y"; units are studs. --- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every --- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes --- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to --- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). --- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing --- 3.00 / 5.00+ / FACS. +-- model/robloxmesh: Roblox FileMesh (.mesh), from MaximumADHD's "Roblox Mesh Format" (devforum.roblox.com/t/326114); no +-- port. Supports: reading 1.00 - 7.00 (Draco COREMESH v2 through codecs/model/Draco), writing 2.00 and 4.00. Not +-- supported: writing 3.00 / 5.00+ / FACS; FACS and HSRAVIS are kept raw. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -167259,7 +164420,6 @@ local function indices(r: Parse.Record, from: number, to: number): Types.Accesso return accessor(d, "u32", 1, n * 3) end --- a Draco-compressed COREMESH body -> the record's vertex / face fields local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?) -- the stream follows a u32 byte count (accepted without it too) if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then @@ -167285,7 +164445,6 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str if not pos or pos.components < 3 then return nil, "corrupt: Draco COREMESH without positions" end - -- an attribute's values as numbers (normalized integers as -1..1 / 0..1) local function getter(a: Draco.Attribute): (number, number) -> number local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) @@ -167353,7 +164512,7 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str }, nil end --- Parse is native: nothing may throw through it, so the callback never does +-- Parse is native: nothing may throw through it local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?) local ok, c, err = pcall(dracoCore, b, off, len) if not ok then @@ -167389,7 +164548,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene if r.col then attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) end - -- LOD ranges (offsets clamped to the faces) local offs = {} for _, o in r.lods do table.insert(offs, math.clamp(o, 0, nf)) @@ -167410,7 +164568,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene scene.meshes[1] = mesh scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } scene.roots[1] = 1 - -- bones and skinning local nb = #r.bones if nb > 0 then local world: { { number } } = table.create(nb) :: any @@ -167496,7 +164653,6 @@ local function num(attr: any, i: number, c: number, default: number): number return attr.values[i * attr.components + c + 1] end --- area-weighted vertex normals local function normals(pos: buffer, nv: number, corners: { number }): buffer local acc = table.create(nv * 3, 0) for f = 0, #corners // 3 - 1 do @@ -167526,7 +164682,6 @@ local function normals(pos: buffer, nv: number, corners: { number }): buffer return out end --- world matrices of every node (parents through children lists) local function worlds(scene: any): { [number]: { number } } local out: { [number]: { number } } = {} local parent: { [number]: number } = {} @@ -167553,7 +164708,6 @@ local function worlds(scene: any): { [number]: { number } } return out end --- the bones of a skin: Parse.Bone list, or nil, message local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) local joints = skin.joints if type(joints) ~= "table" or #joints == 0 then @@ -167600,7 +164754,6 @@ local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) return out, nil end --- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) local nv = #order local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) @@ -167692,7 +164845,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, if src and type(src.lodType) == "number" then r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 end - -- normals when the scene has none local nrm: buffer? = nil if not m.attrs.NORMAL then local pb = buffer.create(nv0 * 12) @@ -167703,7 +164855,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end nrm = normals(pb, nv0, corners) end - -- the skin (4.00): the first node with a mesh and a skin local skin = nil if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then for _, n in scene.nodes or {} do @@ -167723,7 +164874,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 local wscale = if W.raw then 1 / 255 else 1 local nb = #bones - -- per vertex: up to 4 (joint, weight) pairs with weight > 0 local influences: { { { number } } } = table.create(nv0) :: any for v = 0, nv0 - 1 do local list = {} @@ -167736,7 +164886,7 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end influences[v + 1] = list end - -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + -- subsets: a new subset when a face's joints do not fit in 26 local faceIdx = buffer.create(nf * 12) local order: { number } = {} local s: any = nil @@ -167836,7 +164986,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end r.faces = faces r.lods = { 0, nf } - -- extra LODs of a single untransformed primitive local part = m.parts[1] local mesh = part and part.mesh local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil @@ -167877,10 +165026,8 @@ __FILES["model/robloxmesh/Parse"] = @native function() --- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version: --- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the --- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core --- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data. +-- model/robloxmesh/Parse: FileMesh bytes to a flat record, little endian, 1.00 - 7.00 (MaximumADHD's "Roblox Mesh +-- Format", devforum 326114); a Draco COREMESH v2 goes through the lim.core callback. Never throws. local Parse = {} local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring @@ -167910,8 +165057,6 @@ type Record = { coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed } --- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record --- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco) type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer } type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? } @@ -167992,7 +165137,7 @@ end end -- ------------------------------------------------------------------------------------------------ binary parts --- vertices of size vs (36 / 40) at p +-- vertices of 36 / 40 bytes @native local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) local col = if vs >= 40 then buffer.create(n * 4) else nil @@ -168299,7 +165444,6 @@ end return r, nil end --- parse(b, p, e, lim) -> Record | nil, message @native function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) if e - p < 13 then return nil, "truncated: no version line" @@ -168324,7 +165468,7 @@ end return nil, "unsupported: version " .. version end --- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +-- packed tangent: signed bytes / 127 @native local function snorm(v: number): number local x = if v >= 128 then v - 256 else v return math.clamp(x / 127, -1, 1) @@ -168339,9 +165483,8 @@ __FILES["model/robloxmesh/Write"] = @native function() --- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: --- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning --- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +-- model/robloxmesh/Write: a flat record to FileMesh 2.00 (header, 36- or 40-byte vertices, faces) or 4.00 (24-byte +-- header, 40-byte vertices, skinning, faces, LOD offsets, bones, bone names, subsets). Never throws. local Parse = __include("model/robloxmesh/Parse") local Bytes = __include("core/Bytes") @@ -168368,7 +165511,6 @@ local Write = {} w.pos = p + (if colors then 40 else 36) end --- write(r, version) -> buffer ("2.00" | "4.00") @native function Write.write(r: Parse.Record, version: string): buffer local nv, nf = r.numVerts, r.numFaces local w = Bytes.writer(64 + nv * 48 + nf * 12) @@ -168448,21 +165590,9 @@ return Write end __FILES["model/schematic"] = function() --- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: --- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and --- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, --- Sponge, Litematic. --- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic --- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as --- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = --- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the --- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). --- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) --- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, --- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the --- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. --- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with --- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). +-- model/schematic: Minecraft schematics, read + write: MCEdit / WorldEdit .schematic (pre-1.13), Sponge .schem v1-3 +-- (WorldEdit 7+) and Litematica .litematic. Not supported: block properties to pre-1.13 data values, Sponge biome +-- conversion between versions, rotated nodes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -168487,18 +165617,18 @@ local Schematic = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxCells: number?, -- refuse schematics with more cells in total (default 2^26) - maxBytes: number?, -- refuse NBT that inflates past this (default 2^28) + maxCells: number?, -- default 2^26 + maxBytes: number?, -- default 2^28 } type EncodeOptions = { variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" - version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's) - dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21) - name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name - title: string?, -- .litematic Metadata.Name + version: number?, -- Sponge default 3, Litematica default 6 (or the source's) + dataVersion: number?, -- default the source's, else 3953 = 1.21 + name: string?, + title: string?, compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them - level: number?, -- deflate level - format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...) + level: number?, + format: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -168528,7 +165658,6 @@ function Schematic.sniff(r: Bytes.Reader): number return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 end --- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) function Schematic.variant(r: Bytes.Reader): string? local p = Nbt.peek(r.buf, r.base, r.limit - r.base) if not p then @@ -168547,7 +165676,6 @@ function Schematic.variant(r: Bytes.Reader): string? end -- ------------------------------------------------------------------------------------------------ decode --- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil local function variantOf(root: any): (string?, any) if type(root) ~= "table" or not Types.isObject(root) then return nil, nil @@ -168682,7 +165810,6 @@ local function regionsOf(value: any): ({ Common.Region }?, string?) return out, nil end --- merge(regions) -> one region covering them all (air where none is) local function merge(regions: { Common.Region }): Common.Region if #regions == 1 then return regions[1] @@ -168784,30 +165911,27 @@ return Schematic end __FILES["model/schematic/Common"] = function() --- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, --- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, --- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +-- model/schematic/Common: shared region record, NBT access and block entities as Sponge v3's { pos = { x, y, z }, id, +-- data } (MCEdit / Litematica use flat { x, y, z, id, ... }, Sponge v2 { Pos, Id, ... }). local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") local Common = {} --- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +-- a block region: u16 indices per cell in Types.Voxels order (x fastest, then y, then z) into states type Region = { name: string?, - size: { number }, -- x, y, z cells - position: { number }, -- the minimum corner relative to the schematic origin + size: { number }, + position: { number }, -- relative to the schematic origin states: { string }, indices: buffer, blockEntities: { any }, entities: { any }, } --- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil Common.int = Mc.int --- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) local x, y, z = Common.int(a), Common.int(b), Common.int(c) if not x or not y or not z then @@ -168822,14 +165946,11 @@ function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number return x, y, z end --- ints(v) -> the numbers of an intArray tag or a list of numbers | nil Common.ints = Mc.ints --- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) Common.blockEntity = Mc.blockEntity Common.flatBlockEntity = Mc.flatBlockEntity --- list(v) -> v when it is an NBT list (array), else an empty list function Common.list(v: any): { any } if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then return v @@ -168837,7 +165958,6 @@ function Common.list(v: any): { any } return {} end --- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) function Common.compound(fields: { { any } }): { [string]: any } local o, keys = {}, {} for _, kv in fields do @@ -168849,8 +165969,6 @@ function Common.compound(fields: { { any } }): { [string]: any } return Types.object(o, keys) end --- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key --- order (a decoded source compound: its other keys are kept, except those in drop), new keys after function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } if type(base) ~= "table" or not Types.isObject(base) then return Common.compound(fields) @@ -168883,7 +166001,6 @@ function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean return Common.compound(out) end --- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) local first: { [string]: number } = {} local remap: { number } = {} @@ -168914,11 +166031,9 @@ return Common end __FILES["model/schematic/Litematic"] = function() --- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, --- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, --- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state --- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative --- to the region's minimum corner), Entities and pending ticks (kept as they are). +-- model/schematic/Litematic: .litematic, from LitematicaSchematic / LitematicaBitArray as documented by litemapy: +-- Metadata, named Regions (Position, Size may be negative), palette (0 = air), BlockStates spanning longs (>= 2 bits), +-- TileEntities relative to the region's minimum corner, Entities and pending ticks. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -168943,7 +166058,6 @@ local function vec(v: { number }): any return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) end --- read(root, maxCells) -> { Region }, extra | nil, message function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) if not Types.isObject(root.Regions) then return nil, "no Regions" @@ -169021,8 +166135,6 @@ function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) } end --- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root --- (Metadata fields and each region's Position / Size signs and pending ticks are kept) function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil local regs, order = {}, {} @@ -169078,7 +166190,6 @@ function Litematic.write(regions: { Common.Region }, version: number, dataVersio local b = if baseRegions then baseRegions[name] else nil local bsize = if type(b) == "table" then xyz(b.Size) else nil if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then - -- keep the source's corner and signs for k = 1, 3 do if bsize[k] < 0 then size[k] = bsize[k] @@ -169131,12 +166242,9 @@ return Litematic end __FILES["model/schematic/Mcedit"] = function() --- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki --- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high --- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name --- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft --- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block --- nearest in colour). +-- model/schematic/Mcedit: MCEdit / WorldEdit .schematic (pre-1.13; Minecraft wiki "Schematic file format"): Width / +-- Height / Length, Blocks + Data (+ AddBlocks high nibbles, high nibble first), Materials = "Alpha", TileEntities, +-- Entities, WEOffset*, and the SchematicaMapping / BlockIDs name tables of Schematica and MCEdit-Unified. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -169146,7 +166254,6 @@ local Mcedit = {} local Packed = Mc.Packed --- read(root, maxCells) -> { Region }, extra | nil, message function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) local blocks = root.Blocks if type(blocks) ~= "buffer" then @@ -169284,15 +166391,12 @@ local function nearest(state: string): (number, number) return bid, bd end --- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other --- fields are kept function Mcedit.write(r: Common.Region, base: any): (any, string?) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then return nil, "a .schematic is at most 65535 cells on each axis" end local n = sx * sy * sz - -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list local map: { [string]: number } = {} if type(base) == "table" then if Types.isObject(base.SchematicaMapping) then @@ -169382,10 +166486,9 @@ return Mcedit end __FILES["model/schematic/Sponge"] = function() --- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the --- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the --- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / --- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +-- model/schematic/Sponge: .schem (WorldEdit 7+, FAWE, Amulet), from SpongePowered/Schematic-Specification v1-3: Width / +-- Height / Length, Offset, Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities +-- (TileEntities / BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -169395,7 +166498,6 @@ local Sponge = {} local Packed = Mc.Packed --- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) local version = Common.int(s.Version) or 1 local function u16(v: any): any @@ -169464,8 +166566,6 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } end --- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, --- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then @@ -169515,12 +166615,8 @@ return Sponge end __FILES["model/smd"] = function() --- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the --- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a --- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation --- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, --- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. --- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). +-- model/smd: Valve SMD (studiomdl "version 1" text, GoldSrc and Source), from the Valve Developer Community "SMD file +-- format" page; no code taken. Units as stored (inches in Valve's games), z up. Not supported: vertex animation (flex). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -169542,8 +166638,8 @@ local Smd = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - fps: number?, -- skeleton frames per second (default 30) - name: string?, -- the root node / animation name (the api passes the file name) + fps: number?, -- default 30 + name: string?, maxVertices: number?, -- default 2^24 } type EncodeOptions = Write.Options @@ -169586,14 +166682,9 @@ return Smd end __FILES["model/smd/Read"] = function() --- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, --- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone --- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px --- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). --- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material --- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, --- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond --- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +-- model/smd/Read: sections "nodes" (id, "name", parent), "skeleton" ("time n", "bone px py pz rx ry rz", Euler radians, +-- R = Rz Ry Rx; a bone missing from a later frame keeps its pose), "triangles" (a material line, then "bone px py pz +-- nx ny nz u v [links (bone weight)...]", model space, v up; the rest of the weight goes to the parent bone). local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -169607,7 +166698,6 @@ type Options = { fps: number?, name: string?, maxVertices: number? } type Bone = { id: number, name: string, parent: number } local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } --- read(text, opts) -> Scene | nil, message function Read.read(text: string, opts: Options?): (Types.Scene?, string?) local lines: { string } = {} for line in string.gmatch(text, "[^\r\n]*") do @@ -169764,7 +166854,7 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) local root: Types.Node = { name = opts and opts.name or "smd", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 - -- skeleton (bind pose: the first frame) + -- bind pose: the first frame local joints: { Rig.Joint } = {} local bind: { [number]: { number } } = frames[1] or {} for k, bn in bones do @@ -169773,7 +166863,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } end local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) - -- meshes if #batches > 0 then local mesh: Types.Mesh = { primitives = {} } for _, b in batches do @@ -169831,7 +166920,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) table.insert(root.children, #scene.nodes) end - -- animation if #frames > 1 or (#frames == 1 and #batches == 0) then local fps = opts and opts.fps or 30 local t: { number } = {} @@ -169863,14 +166951,8 @@ return Read end __FILES["model/smd/Write"] = function() --- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node --- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose --- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled --- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every --- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material --- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the --- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless --- opts.triangles is true. +-- model/smd/Write: Scene -> SMD version 1: the first skin's joints (or one "root" bone), the bind pose or a sampled +-- animation, world-space triangles with Source links (GoldSrc style: the strongest joint as the parent bone only). local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Flatten = __include("codecs/model/MeshFlatten") @@ -169916,7 +166998,6 @@ local function lerp(a: { number }, b: { number }, t: number): { number } return out end --- the value of channel ch at time tm (nil when the channel has no keys) local function sample(ch: Types.Channel, tm: number): { number }? local input, output = ch.input, ch.output local n = input.count @@ -169955,7 +167036,6 @@ local function sample(ch: Types.Channel, tm: number): { number }? return key(n - 1) end --- write(scene, opts) -> text | nil, message function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, "expected a Scene" @@ -170043,7 +167123,6 @@ function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) end end table.insert(out, "end") - -- triangles if not anim or (opts and opts.triangles) then local m, err = Flatten.merge(scene, function(name: string): boolean return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" @@ -170115,22 +167194,9 @@ return Write end __FILES["model/stl"] = function() --- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description --- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). --- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the --- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: --- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the --- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in --- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly --- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in --- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final --- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, --- solids, facets }. --- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans --- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after --- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle --- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either --- convention. Not supported: binary-only extensions other than the two colour conventions. +-- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports: +-- the VisCAM / SolidView and Materialise Magics colour conventions, a binary file starting with "solid" (size exactly +-- 84 + 50 * count), several ASCII solids. Not supported: other binary attribute extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -170151,18 +167217,16 @@ local Stl = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxFaces: number?, -- refuse more facets (default 2^25) - colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the - -- header = magics, else any attribute with bit 15 set = viscam, else none) + maxFaces: number?, -- default 2^25 + colors: ("auto" | "viscam" | "magics" | "none")?, -- default "auto": "COLOR=" = magics, else bit 15 = viscam } type EncodeOptions = { ascii: boolean?, -- default false (binary) - colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only) - defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly - -- that colour refer to it, the others carry their own (alpha 255) - name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh") - header: string?, -- the binary header text (at most 80 bytes; default "rosetta STL") - normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL + colors: ("viscam" | "magics")?, -- binary only + defaultColor: { number }?, -- magics object colour, 0..255 (default opaque white) + name: string?, -- default: the mesh / node name, else "mesh" + header: string?, -- at most 80 bytes; default "rosetta STL" + normals: ("compute" | "attribute")?, -- default: from the triangle } -- ------------------------------------------------------------------------------------------------ constants @@ -170406,7 +167470,7 @@ function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if size < 84 then return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) end - -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + -- extra bytes after the facets are tolerated return decodeBinary(r, maxFaces, colors) end @@ -170417,7 +167481,6 @@ local function f32(v: number): number return buffer.readf32(scratch, 0) end --- a COLOR_0 component as 0..255 local function byte(a: Flatten.Attr, v: number): number if a.raw then if a.type == "unorm16" then @@ -170457,7 +167520,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local C = m.attrs.COLOR_0 local corners = m.corners local nf = #corners // 3 - -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) local function normal(f: number): (number, number, number) local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] if N then @@ -170519,7 +167581,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end return buffer.fromstring(table.concat(out)), nil end - -- binary local buf = buffer.create(84 + 50 * nf) local header = o.header or "rosetta STL" if colors == "magics" then @@ -170536,7 +167597,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end buffer.writestring(buf, 0, header) writeu32(buf, 80, nf) - -- the attribute words: colours, or the raw words of a single STL-decoded primitive local rawAttr: { number }? = nil if colors == nil and #m.parts == 1 then local ex = m.parts[1].prim.extras @@ -170586,16 +167646,13 @@ __FILES["model/stl/Decode"] = @native function() --- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 --- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that --- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +-- model/stl/Decode: binary STL facets (50 bytes: normal, 3 vertices, u16 attribute) and the 5-5-5 colours of VisCAM / +-- SolidView and Materialise Magics. Never throws: the caller bounds the facets first. local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift local Decode = {} --- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into --- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). @native function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number local any = 0 for i = 0, n - 1 do @@ -170627,14 +167684,12 @@ local Decode = {} return any end --- 5-bit -> 8-bit, rounded @native local function x8(v: number): number return (v * 255 + 15) // 31 end --- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, --- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, --- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +-- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14. @native function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) for i = 0, n - 1 do local w = readu16(attr, i * 2) @@ -170663,22 +167718,10 @@ return Decode end __FILES["model/usda"] = function() --- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text --- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own --- reader / writer (pxr) and Blender's USD exporter. --- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / --- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, --- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one --- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every --- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, --- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / --- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> --- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / --- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). --- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. --- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs --- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel --- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. +-- model/usda: USD ASCII layers (.usda, text .usd) and USDZ packages of them, from the Sdf text format and the UsdGeom / +-- UsdShade / UsdLux docs (OpenUSD 26.x), checked against pxr and Blender's exporter. Not supported: USDC crate files, +-- composition arcs (listed in meta.source.unsupported), UsdSkel, blend shapes, curves / points / NURBS, instancers, +-- MaterialX, writing USDZ. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -170701,18 +167744,18 @@ local Usda = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin) - resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths) - files: { [string]: any }?, -- or: the files by asset path - maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25) - maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30) + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, -- default 2^25 + maxBytes: number?, -- default 2^30 } type EncodeOptions = { - files: { [string]: any }?, -- receives embedded texture bytes as _. - name: string?, -- the destination's file name (names the texture files) - format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension) - upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up) + files: { [string]: any }?, -- as _. + name: string?, + format: string?, -- "usdz" -> UNSUPPORTED + upAxis: string?, -- default: from scene.meta.up metersPerUnit: number?, -- default scene.meta.unit or 1 } @@ -170721,7 +167764,6 @@ local function isUsdz(r: Bytes.Reader): boolean if r:peek(4) ~= "PK\3\4" then return false end - -- the first entry is the root layer local lo, hi = r:peekU8(26), r:peekU8(27) if lo < 0 or hi < 0 then return false @@ -170738,7 +167780,7 @@ function Usda.sniff(r: Bytes.Reader): number return 1 end if head == "PXR-USDC" then - return 0.9 -- recognised so the error says USDC is not supported + return 0.9 -- USDC magic, so the error says it is unsupported end if isUsdz(r) then return 0.95 @@ -170873,7 +167915,6 @@ function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er end -- ------------------------------------------------------------------------------------------------ extras --- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover function Usda.parse(text: string): (Parse.Layer?, Err.Err?) local layer, msg, at = Parse.layer(text) if not layer then @@ -170886,24 +167927,9 @@ return Usda end __FILES["model/usda/Build"] = function() --- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux --- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; --- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh --- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / --- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. --- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the --- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local --- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); --- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / --- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor --- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every --- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated --- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. --- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with --- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> --- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). --- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in --- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +-- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other +-- attributes than xform ops use their earliest sample (as UsdTimeCode.EarliestTime()). Not supported: composition arcs, +-- UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Parse = __include("model/usda/Parse") @@ -170940,7 +167966,6 @@ local function str(v: any): string? end return nil end --- a tuple / scalar -> numbers (nil when not numeric) local function nums(v: any): { number }? if type(v) == "number" then return { v } @@ -170977,7 +168002,7 @@ local function num(v: any): number? return nil end --- the value of a property: its default, else its earliest time sample +-- a property's default, else its earliest time sample local function propValue(p: Prop?): any if not p then return nil @@ -171004,7 +168029,6 @@ local function joinPath(parent: string, name: string): string return if parent == "/" then "/" .. name else parent .. "/" .. name end --- resolve a (possibly relative) Sdf path against the prim path that holds it local function resolvePath(base: string, p: string): string if string.sub(p, 1, 1) == "/" then return p @@ -171025,7 +168049,6 @@ local function resolvePath(base: string, p: string): string end return "/" .. table.concat(out, "/") end --- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" local function splitProp(p: string): (string, string?) local prim, prop = string.match(p, "^(.-)%.([^/]+)$") if prim and prop then @@ -171048,7 +168071,6 @@ end -- ------------------------------------------------------------------------------------------------ xform ops type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } --- the op stack of a prim: ops in xformOpOrder, resetXformStack local function xformOps(p: Prim): ({ Op }, boolean) local order = p.props.xformOpOrder local list = order and propValue(order) @@ -171080,7 +168102,6 @@ local function xformOps(p: Prim): ({ Op }, boolean) end local AXIS = { X = 1, Y = 2, Z = 3 } --- the matrix of one op for a value local function opMatrix(op: Op, v: any): { number }? local n = nums(v) if not n then @@ -171104,7 +168125,7 @@ local function opMatrix(op: Op, v: any): { number }? elseif k == "rotate" and op.axes then local axes = op.axes :: string local r: { number } = Types.Scene.IDENTITY :: any - -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + -- rotateXZY: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles for c = 1, #axes do local a = AXIS[string.sub(axes, c, c)] local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 @@ -171127,7 +168148,6 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any end local out = table.create(#na) if quat and #na == 4 then - -- (w, x, y, z): slerp through nlerp with the short path local dot = 0 for k = 1, 4 do dot += na[k] * nb[k] @@ -171144,7 +168164,7 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any return { t = "tuple", v = out } end --- an op's value at time code t (samples interpolated linearly, held outside their range) +-- samples interpolated linearly, held outside their range local function opValueAt(op: Op, t: number?): any local p = op.prop local s = p.samples @@ -171196,7 +168216,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local unsupported: { [string]: boolean } = {} local meta = layer.meta - -- prim index (variants merged), paths local byPath: { [string]: Prim } = {} local parentOf: { [Prim]: string } = {} local pathOf: { [Prim]: string } = {} @@ -171247,7 +168266,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) parentOf[p] = parent local existing = byPath[path] if existing and existing ~= p then - -- over / def of the same path in one layer: merge into the first spec + -- over / def of the same path in one layer: merged into the first spec for _, pn in p.order do if not existing.props[pn] then existing.props[pn] = p.props[pn] @@ -171262,7 +168281,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(existing.children, c) end table.clear(p.children) - p.specifier = "class" -- skipped below + p.specifier = "class" else byPath[path] = p end @@ -171283,7 +168302,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) unsupported.subLayers = true end - -- a property of a prim path ("/a/b.inputs:x") local function propAt(path: string): (Prim?, Prop?) local pp, pn = splitProp(path) local prim = byPath[pp] @@ -171293,7 +168311,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return prim, prim.props[pn] end - -- --------------------------------------------------------------------------------------------- materials local texCoordIndex: { [string]: number } = {} local texCoordCount = 0 local function texCoordFor(name: string): number @@ -171305,7 +168322,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end return k end - -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + -- "st" first, so materials and meshes agree on TEXCOORD_n do local names: { [string]: boolean } = {} for _, p in byPath do @@ -171335,7 +168352,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end - -- an input's resolved source: a value, or { shader = Prim, output = name } type Source = { value: any?, shader: Prim?, output: string? } local function input(prim: Prim, name: string, depth: number?): Source? local d = depth or 0 @@ -171356,7 +168372,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) if outName and tprim.typeName == "Shader" then return { shader = tprim, output = outName } elseif outName then - -- a NodeGraph output: follow its connection local op = tprim.props[tn] if op and op.connect and #op.connect > 0 then local t2 = resolvePath(tp, op.connect[1]) @@ -171386,7 +168401,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local textureIndex: { [string]: number } = {} local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } - -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) local function textureRef(shader: Prim): Types.TextureRef? if shaderId(shader) ~= "UsdUVTexture" then return nil @@ -171422,7 +168436,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) textureIndex[key] = ti end local ref: Types.TextureRef = { texture = ti :: number } - -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + -- st: UsdPrimvarReader_float2, maybe through UsdTransform2d local st = input(shader, "st") local reader = st and st.shader if reader and shaderId(reader) == "UsdTransform2d" then @@ -171474,7 +168488,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) mat.metallic = 0 mat.roughness = 0.5 mat.extras = { usd = { path = path } } - -- the surface shader local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] local shader: Prim? = nil if surf and surf.connect and #surf.connect > 0 then @@ -171582,7 +168595,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return #scene.materials end - -- the bound material of a prim (material:binding, inherited from ancestors) + -- material:binding, inherited from ancestors local function binding(prim: Prim, path: string): number? local p: Prim? = prim local pp = path @@ -171620,7 +168633,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return mi :: number end - -- --------------------------------------------------------------------------------------------- meshes type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } local function primvar(p: Prop?, defaultInterp: string): Primvar? if not p then @@ -171678,7 +168690,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end faceStart[nfaces + 1] = acc end - -- primvars, validated local function sizeOk(pv: Primvar): boolean local n = (if pv.idx then #pv.idx else #pv.data // pv.w) local want = if pv.interp == "constant" then 1 @@ -171735,7 +168746,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end end - -- the value of a primvar for (point, face, corner) (0-based), component c local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number local e = if pv.interp == "constant" then 0 elseif pv.interp == "uniform" then face @@ -171758,7 +168768,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" - -- holes local hole: { [number]: boolean } = {} local hv = propValue(prim.props.holeIndices) if isArr(hv) then @@ -171766,7 +168775,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) hole[f] = true end end - -- face sets: GeomSubsets ("face" elements), the rest + -- face sets: GeomSubsets of "face" elements, then the rest local meshMaterial = binding(prim, path) local constantColor: { number }? = nil if color and color.interp == "constant" then @@ -171808,9 +168817,8 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local mesh: Types.Mesh = { name = prim.name, primitives = {} } for _, set in sets do - -- vertices: one per point (vertex-rate data) or per corner local keyToVert: { [number]: number } = {} - local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local vp, vf, vc = {}, {}, {} local nv = 0 local out: { number } = {} local faceSizes: { number } = {} @@ -171888,7 +168896,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local mi = set.material if color and not constantColor then - -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) if opacity then local a = Types.Scene.accessor(nil, "f32", 4, nv) for v = 1, nv do @@ -171935,7 +168942,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return mesh, nil end - -- --------------------------------------------------------------------------------------------- cameras / lights local function camera(prim: Prim): Types.Camera local function f(name: string, d: number): number return num(propValue(prim.props[name])) or d @@ -171982,7 +168988,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return l end - -- --------------------------------------------------------------------------------------------- nodes local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 if tcps <= 0 then tcps = 24 @@ -172034,7 +169039,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(scene.nodes, n) local ni = #scene.nodes local ops, reset = xformOps(p) - -- animated ops: the local matrix at the union of their time codes local times: { number } = {} do local seen: { [number]: boolean } = {} @@ -172079,7 +169083,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then - -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix local simple = true local stage = 0 for _, op in ops do @@ -172175,7 +169178,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(scene.animations, animation) end - -- stage metadata local up = str(meta.upAxis) scene.meta.up = if up == "Z" then "z" else "y" local mpu = num(meta.metersPerUnit) @@ -172203,42 +169205,35 @@ return Build end __FILES["model/usda/Parse"] = function() --- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text --- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes --- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, --- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), --- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast --- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. --- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and --- returns nil, message, offset - nothing escapes. +-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads +-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws. local Parse = {} --- values: numbers, booleans, strings, and these tagged tables -type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened) +type Arr = { t: "arr", w: number, v: { number } } -- w numbers per element (tuples flattened) type Value = any type Prop = { name: string, - rel: boolean, -- a relationship - typeName: string?, -- "point3f", "token", ... (attributes) + rel: boolean, + typeName: string?, array: boolean?, uniform: boolean?, custom: boolean?, - value: Value?, -- the default value (attributes) or the targets (relationships: { path strings }) + value: Value?, -- relationships: { path strings } hasValue: boolean?, samples: { times: { number }, values: { Value } }?, - connect: { string }?, -- connection target paths (attributes) + connect: { string }?, meta: { [string]: Value }?, } type Prim = { - specifier: string, -- "def" | "over" | "class" + specifier: string, typeName: string?, name: string, meta: { [string]: Value }, props: { [string]: Prop }, - order: { string }, -- property names in file order + order: { string }, children: { Prim }, - variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children) + variantSets: { [string]: { [string]: Prim } }?, } type Layer = { meta: { [string]: Value }, prims: { Prim } } @@ -172255,12 +169250,10 @@ local function fail(msg: string, at: number): never error({ usda = msg, at = at }, 0) end --- the parser over one text; positions are 1-based string indices local function parser(s: string, maxBytes: number) local n = #s local depth = 0 - -- whitespace and comments (newlines included) local function ws(i: number): number while true do local _, e = sfind(s, "^[ \t\r\n]+", i) @@ -172268,13 +169261,13 @@ local function parser(s: string, maxBytes: number) i = e + 1 end local c = sbyte(s, i) - if c == 35 then -- # + if c == 35 then local nl = sfind(s, "\n", i, true) i = if nl then nl + 1 else n + 1 - elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + elseif c == 47 and sbyte(s, i + 1) == 47 then local nl = sfind(s, "\n", i, true) i = if nl then nl + 1 else n + 1 - elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + elseif c == 47 and sbyte(s, i + 1) == 42 then local _, ce = sfind(s, "*/", i + 2, true) if not ce then fail("unterminated comment", i) @@ -172309,7 +169302,7 @@ local function parser(s: string, maxBytes: number) end return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string if x == "x" then - return "\\x" .. c -- left alone (rare) + return "\\x" .. c end return ESC[c] or c end)) @@ -172352,7 +169345,6 @@ local function parser(s: string, maxBytes: number) return v, (e :: number) + 1 end end - -- inf / -inf / nan local w, e2 = sfind(s, "^[-+]?%a+", i) if w then local word = string.lower(ssub(s, w, e2)) @@ -172367,7 +169359,6 @@ local function parser(s: string, maxBytes: number) return nil, i end - -- skip a balanced (), [], {} block starting at i (strings and comments respected) local function skipBalanced(i: number): number local open = sbyte(s, i) local level = 0 @@ -172406,7 +169397,6 @@ local function parser(s: string, maxBytes: number) local value: (i: number) -> (Value, number) local metadata: (i: number) -> ({ [string]: Value }, number) - -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list local function list(i: number): (Value, number) local close = sfind(s, "]", i + 1, true) if close then @@ -172420,7 +169410,7 @@ local function parser(s: string, maxBytes: number) w += 1 end elseif sfind(body, "[%(%)]") then - w = -1 -- nested tuples: the generic path + w = -1 end if w > 0 then local out: { number } = {} @@ -172444,7 +169434,6 @@ local function parser(s: string, maxBytes: number) end end end - -- generic local items = {} i += 1 while true do @@ -172460,7 +169449,7 @@ local function parser(s: string, maxBytes: number) v, i = value(i) table.insert(items, v) i = ws(i) - if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + if ssub(s, i, i) == "(" then local _ _, i = metadata(i) i = ws(i) @@ -172472,7 +169461,6 @@ local function parser(s: string, maxBytes: number) fail("expected ',' or ']' in a list", i) end end - -- all numbers, or all equal-width numeric tuples -> arr local w: number? = nil local flat: { number } = {} for _, it in items do @@ -172530,7 +169518,6 @@ local function parser(s: string, maxBytes: number) return { t = "tuple", v = items }, i end - -- { type key = value ... } (metadata dictionaries) local function dict(i: number): (Value, number) local out: { [string]: Value } = {} i += 1 @@ -172607,7 +169594,7 @@ local function parser(s: string, maxBytes: number) end local a: { [string]: any } = { t = "asset", v = path } local j = ws(i) - if ssub(s, j, j) == "<" then -- references = @file@ + if ssub(s, j, j) == "<" then local e = sfind(s, ">", j + 1, true) if not e then fail("unterminated path", j) @@ -172648,7 +169635,6 @@ local function parser(s: string, maxBytes: number) return v, i end - -- ( key = value ; "doc" ; prepend key = value ... ) function metadata(i: number): ({ [string]: Value }, number) local out: { [string]: Value } = {} i = expect(i, "(") @@ -172685,9 +169671,7 @@ local function parser(s: string, maxBytes: number) local v v, i = value(i + 1) if op == "delete" then - -- deletions only matter for composition elseif op and op ~= "reorder" then - -- prepend / append / add: merge into one list local prev = out[key :: string] if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then for _, x in v.v do @@ -172703,7 +169687,6 @@ local function parser(s: string, maxBytes: number) end end - -- time samples: { time: value, ... } local function samples(i: number): ({ times: { number }, values: { Value } }, number) local times: { number }, values: { Value } = {}, {} i = expect(i, "{") @@ -172727,7 +169710,7 @@ local function parser(s: string, maxBytes: number) i = expect(i, ":") local v v, i = value(i) - table.insert(times, t :: number) -- fail() threw on nil + table.insert(times, t :: number) table.insert(values, v) end return { times = times, values = values }, i @@ -172766,7 +169749,6 @@ local function parser(s: string, maxBytes: number) fail("expected a prim type or name", i) end i = ws(i) - -- dotted schema names (rare) while ssub(s, i, i) == "." do local more more, i = ident(i + 1) @@ -172822,7 +169804,7 @@ local function parser(s: string, maxBytes: number) end end - -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + -- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] local function property(i: number, first: string, p: Prim): number local word: string? = first local op: string? = nil @@ -172889,7 +169871,6 @@ local function parser(s: string, maxBytes: number) local v v, i = value(i) if op == "delete" then - -- composition only elseif suffix == "connect" then pr.connect = targets(v) elseif isRel then @@ -172959,7 +169940,6 @@ local function parser(s: string, maxBytes: number) end end - -- the whole layer local function layer(): Layer local i = 1 if ssub(s, 1, 3) == "\239\187\191" then @@ -173003,7 +169983,6 @@ local function parser(s: string, maxBytes: number) return layer end --- layer(text, opts?) -> Layer | nil, message, offset (0-based) function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) local run = parser(text, maxBytes or 2 ^ 30) local ok, res = pcall(run) @@ -173016,7 +169995,6 @@ function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number? return nil, "parse error: " .. tostring(res), nil end --- version(text) -> the "#usda " string function Parse.version(text: string): string? return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") end @@ -173025,17 +170003,8 @@ return Parse end __FILES["model/usda/Write"] = function() --- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. --- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, --- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture --- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a --- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, --- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are --- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) --- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), --- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the --- embedded bytes written into opts.files as _.. Not written: skins, morph targets, weights animation, --- lines / points primitives (counted in the returned notes). +-- model/usda/Write: Scene -> USD ASCII (UsdGeom / UsdShade / UsdLux); new code. timeCodesPerSecond 24. Not written: +-- skins, morph targets, weights animation, lines / points primitives. local Types = __include("Types") local Write = {} @@ -173074,7 +170043,6 @@ local function asset(s: string): string end return "@" .. s .. "@" end --- a valid, sibling-unique prim name local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string @@ -173095,7 +170063,6 @@ local function namer(): (string?, string) -> string end end --- an accessor's elements as numbers (normalized types to floats) local function values(acc: Types.Accessor?): ({ number }?, number) if not acc then return nil, 0 @@ -173114,7 +170081,6 @@ local function values(acc: Types.Accessor?): ({ number }?, number) return out, c end --- array literal of tuples ("[(x, y, z), ...]") or scalars local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string local st = stride or width local n = count or (#vals // st) @@ -173140,12 +170106,11 @@ type Merged = { indices: { number }, normals: { number }?, uvs: { [number]: { number } }, - colors: { number }?, -- rgba + colors: { number }?, hasAlpha: boolean, subsets: { { faces: { number }, material: number? } }, } --- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) local idx: { number } if p.indices then @@ -173202,7 +170167,6 @@ local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number return counts, out end --- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? local prims: { Types.Primitive } = {} for _, p in mesh.primitives do @@ -173218,7 +170182,6 @@ local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? if #prims == 0 then return nil end - -- attributes every primitive has local all = { NORMAL = true } local uvSets: { number } = {} for k = 0, 7 do @@ -173343,7 +170306,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu local rootNames = namer() local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") - -- texture files local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" local texFile: { [number]: string } = {} for i, tex in scene.textures or {} do @@ -173364,7 +170326,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu texFile[i] = uri :: string end - -- animation: per node, per path -> { times, values (components) } type Track = { times: { number }, vals: { number }, comps: number } local tracks: { [number]: { [string]: Track? } } = {} local tcps = 24 @@ -173379,7 +170340,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu if vals and #times > 0 then local stride = comps local per = #vals // (comps * #times) - -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + -- CUBICSPLINE: in-tangent, value, out-tangent per key local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 local tv = {} @@ -173399,7 +170360,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu end end - -- header table.insert(out, "#usda 1.0") table.insert(out, "(") line(1, "defaultPrim = " .. quote(rootName)) @@ -173423,7 +170383,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) end - -- xform ops of a node (+ its animation) local function xform(depth: number, ni: number, n: Types.Node) local tr: { [string]: Track? }? = tracks[ni] local order: { string } = {} @@ -173444,7 +170403,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu local t, r, s = n.translation, n.rotation, n.scale if n.matrix and #n.matrix == 16 then if tr then - -- animated: start from the matrix's TRS local m = n.matrix local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) @@ -173502,7 +170460,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu if doubleSided then line(depth, "uniform bool doubleSided = 1") end - -- extent local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for i = 0, #m.points // 3 - 1 do for c = 1, 3 do @@ -173660,7 +170617,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu lightBody(depth + 1, lig :: Types.Light) end local childNames = namer() - -- a camera / light that did not take the node's prim if cam and kind ~= "Camera" then table.insert(out, "") line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) @@ -173704,7 +170660,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu return table.concat(out, "\n"), notes end --- the Looks scope: materials as UsdPreviewSurface networks function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) local mats = scene.materials or {} if #mats == 0 then @@ -173721,7 +170676,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat line(depth + 1, "{") local d = depth + 2 line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") - -- texture nodes (one per distinct ref) type TexNode = { name: string, ref: Types.TextureRef, color: boolean } local texNodes: { TexNode } = {} local function texNode(ref: Types.TextureRef?, color: boolean): string? @@ -173794,7 +170748,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat end line(e, "token outputs:surface") line(d, "}") - -- primvar readers per texCoord set, transforms, textures local readers: { [number]: boolean } = {} for _, tn in texNodes do local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 @@ -173867,19 +170820,9 @@ return Write end __FILES["model/vox"] = function() --- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) --- and the files MagicaVoxel 0.99.x saves (version 150 and 200). --- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / --- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, --- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown --- chunks are kept raw and written back. --- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per --- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as --- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is --- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. --- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must --- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. --- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. +-- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). +-- Supports: every chunk (unknown, PACK, MATT kept raw); shapes centred on their node like MagicaVoxel. Not supported: +-- writing models over 256 cells per axis (MagicaVoxel's limit); node scale other than mirroring. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -173899,10 +170842,10 @@ local Vox = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27) + maxCells: number?, -- default 2^27 } type EncodeOptions = { - version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one) + version: number?, -- default 200 (MagicaVoxel 0.99.7); 150 is the older one } type Dict = { [string]: string } type GraphNode = { @@ -173991,7 +170934,7 @@ local function ints(s: string?): { number } return out end --- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }); nil when not a permutation local function rotation(b: number): { { number } }? local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) if i0 > 2 or i1 > 2 or i0 == i1 then @@ -174004,7 +170947,6 @@ local function rotation(b: number): { { number } }? return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } end --- the node transform of a frame dictionary (_r, _t) local function applyFrame(node: Types.Node, f: Dict) local t = ints(f._t) local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 @@ -174053,7 +170995,7 @@ local function applyFrame(node: Types.Node, f: Dict) end end --- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +-- MATL: _type -> type, the other keys without their "_", numbers as numbers local function material(d: Dict): Types.VoxelMaterial local m: Types.VoxelMaterial = { type = "diffuse" } for k, v in d do @@ -174281,7 +171223,6 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) return out, nil end --- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? local t = graph[id] if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then @@ -174321,7 +171262,6 @@ local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: num return index end --- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) local p, err = parse(r, opts) if not p then @@ -174414,7 +171354,6 @@ local function wdict(w: Bytes.Writer, d: { [string]: any }?) end end --- a node's transform as a frame dictionary (_r, _t) | nil, message local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) local f: Dict = {} if base then @@ -174514,7 +171453,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) wdict(w, meta.info) end) end - -- models for _, v in models do local sx, sy, sz = v.size[1], v.size[2], v.size[3] chunk("SIZE", function() @@ -174530,7 +171468,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) w.pos = at + count * 4 end) end - -- the scene graph local records: { Record } = {} local nextId = 0 local function alloc(): number @@ -174664,7 +171601,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end end) end - -- layers if type(meta.layers) == "table" then for _, l in meta.layers do chunk("LAYR", function() @@ -174682,7 +171618,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end) end end - -- palette local pal = models[1].palette or DEFAULT_PALETTE chunk("RGBA", function() for i = 1, 256 do @@ -174704,7 +171639,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end end) end - -- materials local mats = models[1].materials if type(mats) == "table" then local ids = {} @@ -174773,15 +171707,11 @@ end __FILES["model/vox/Grid"] = @native function() --- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI --- records. Callers check every range first; nothing here throws. +-- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws. local Grid = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the --- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. --- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. @native function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number local skipped = 0 local sxy = sx * sy @@ -174797,7 +171727,6 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return skipped end --- count(data, cells) -> the number of non-empty cells in data[0, cells) @native function Grid.count(data: buffer, cells: number): number local n = 0 for k = 0, cells - 1 do @@ -174808,8 +171737,7 @@ end return n end --- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). --- The caller sizes dst with count() (sx, sy, sz <= 256). +-- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256) @native function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number local p = at local k = 0 @@ -174835,22 +171763,9 @@ return Grid end __FILES["model/vrml"] = function() --- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over --- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. --- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, --- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and --- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, --- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), --- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated --- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> --- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons --- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless --- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). --- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / --- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, --- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). --- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and --- skins on write (the rest pose is written). +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl / .wrz over codecs/model/Vrml; new code. Supports: +-- the scene graph, DEF / USE, PROTO / EXTERNPROTO, the geometry nodes, Viewpoints, lights, interpolator ROUTEs as +-- animations. Not supported: VRML 1.0, Text, Script, sensors, sound, NURBS; morph targets and skins on write. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -174870,16 +171785,16 @@ local Wrl = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) - segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 maxVertices: number?, -- per geometry (default 2^24) } type EncodeOptions = { - files: { [string]: any }?, -- receives the texture images (else url = texture.uri) - name: string?, -- the destination's file name (names the image files) + files: { [string]: any }?, -- else url = texture.uri + name: string?, flipV: boolean?, -- default true (the inverse of decode) } @@ -174914,22 +171829,9 @@ return Wrl end __FILES["model/x"] = function() --- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", --- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format --- specification and the standard templates, checked against assimp's X importer and test models. --- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per --- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal --- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global --- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, --- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), --- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four --- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, --- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. --- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. --- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in --- meta.source.skippedFaces). --- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key --- interpolation options (keys are linear). +-- model/x: DirectX .x, read only: text ("txt "), binary ("bin "), MSZIP ("tzip" / "bzip"), 32- and 64-bit floats; from +-- Microsoft's DirectX file format spec and templates, checked against assimp. AnimTicksPerSecond defaults to 4800. Not +-- supported: DeclData / FVFData, progressive and patch meshes, non-linear key interpolation. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -174951,10 +171853,10 @@ local X = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25) - maxValues: number?, -- refuse files with more numbers than this (default 2^27) - maxBytes: number?, -- refuse compressed files inflating to more (default 2^30) + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 + maxValues: number?, -- default 2^27 + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants @@ -174970,8 +171872,7 @@ end -- ------------------------------------------------------------------------------------------------ decode -- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, --- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may --- refer back into the previous block's output). +-- "CK" + deflate data); each block may refer back into the previous block's output. local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) if p + 4 > limit then return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) @@ -175058,11 +171959,8 @@ return X end __FILES["model/x/Build"] = function() --- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is --- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding --- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). --- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep --- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +-- model/x/Build: the .x object tree to a Scene, from the DirectX template layouts. Direct3D is left-handed (y up, row +-- vectors): z is negated (matrices as S * M * S) and windings reversed, as assimp does; UVs stay top-left. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Rig = __include("codecs/model/Rig") @@ -175075,7 +171973,6 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 type Node = Parse.Node --- a cursor over an object's flattened values type Vals = { v: { any }, i: number } local function num(c: Vals): number local x = c.v[c.i] @@ -175093,7 +171990,6 @@ local function str(c: Vals): string end return x end --- a non-negative integer (an index) local function index(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -175102,8 +171998,6 @@ local function index(c: Vals, limit: number): number return n end --- a count of items that follow (each takes at least one value: a count past the data is refused before anything --- is allocated for it) local function count(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -175115,7 +172009,7 @@ local function count(c: Vals, limit: number): number return n end --- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +-- S * M * S, S = diag(1, 1, -1) local function mirror(m: { number }): { number } local o = table.clone(m) for _, k in { 3, 7, 9, 10, 12, 15 } do @@ -175199,7 +172093,6 @@ local function accessorF32(values: { number }, comps: number): Types.Accessor return Scene.accessor(b, "f32", comps, n // comps) end --- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local scene = ctx.scene local c: Vals = { v = m.vals, i = 1 } @@ -175227,7 +172120,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end faces[f] = face end - -- the optional data objects local normals: { number }? = nil local nfaces: { { number } }? = nil local uvSets: { { number } } = {} @@ -175302,12 +172194,11 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) end end - -- material per face (a single index applies to every face) + -- a single index applies to every face local function matOf(f: number): number local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] return if mi then mi + 1 else 1 end - -- unique vertices per (position, normal index) local key: { [number]: number } = {} local srcPos: { number } = {} local srcNrm: { number } = {} @@ -175323,7 +172214,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local nface = nfaces and nfaces[f] local vs = table.create(n) :: { number } for k = 1, n do - local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept + local src = if k == 1 then 1 else n - k + 2 local p = face[src] local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 local kk = p * (nNormals + 1) + q + 1 @@ -175360,7 +172251,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) return nil, nil end table.sort(order) - -- shared vertex attributes (one vertex buffer for every primitive of the mesh) local nout = #srcPos local P = table.create(nout * 3) :: { number } for v = 1, nout do @@ -175474,7 +172364,6 @@ local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, d node.matrix = m end elseif k.type == "Mesh" then - -- the first mesh on the frame's node, more as child nodes local mi, bones = mesh(ctx, k, triangulate) if mi then local holder = ni @@ -175595,7 +172484,6 @@ function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: num end end end - -- skins: bone names -> frames for _, ps in ctx.pendingSkins do local joints: { number } = {} local ibm = buffer.create(#ps.bones * 64) @@ -175634,23 +172522,15 @@ return Build end __FILES["model/x/Parse"] = function() --- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the --- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and --- binary tokens), checked against what assimp's XFileParser accepts (no code taken). --- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and --- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), --- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. --- Text: ; and , separators, // and # comments, quoted strings, s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). --- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and --- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/x/Parse: .x text and binary tokens to { type, name?, vals, kids } objects, from Microsoft's "DirectX File +-- Format Specification", checked against assimp's XFileParser (no code taken). Templates are skipped; Blender's +-- "1.#IND00" / "1.#QNAN0" read as 0. Never throws: bad data returns nil, message. local Parse = {} type Node = { type: string, name: string?, vals: { any }, kids: { Node } } local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring --- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), --- "punct", "eof"; err holds a message after a bad token type Lexer = { next: () -> (string, any), err: string? } local KEYWORDS: { [number]: string } = { @@ -175685,7 +172565,7 @@ local function textLexer(s: string): Lexer return "eof", nil end local c = string.byte(s, p) - if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then local nl = string.find(s, "[\r\n]", p) p = if nl then nl + 1 else n + 1 else @@ -175834,7 +172714,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return if q then q[1] else "eof" end local budget = maxValues - -- skips a template / unknown block whose "{" was just read local function skipBlock(): string? local depth = 1 while depth > 0 do @@ -175850,7 +172729,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return nil end local body: (Node, number) -> string? - -- an object whose type token was read: [name] { ... } local function object(parent: Node, typ: string, depth: number): string? local name: string? = nil local kind, v = take() @@ -175932,7 +172810,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return root, nil end --- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) return tree(lex, maxValues) @@ -175942,18 +172819,9 @@ return Parse end __FILES["model/x3d"] = function() --- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, --- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). --- New code. --- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, --- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, --- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / --- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; --- head meta, components and UNIT length (-> meta.unit). --- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the --- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). --- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, --- H-Anim skinning, scripts. +-- model/x3d: X3D (ISO/IEC 19775-1) XML (.x3d, 19776-1) and classic VRML (.x3dv, 19776-2) encodings, plain or gzipped, +-- over codecs/model/Vrml; new code. Supports: the model/vrml set plus the X3D geometry and material nodes. +-- Not supported: binary encodings (.x3db Fast Infoset / EXI), X3D JSON, Text, NURBS, shaders, H-Anim skinning, scripts. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -175973,18 +172841,18 @@ local X3d = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) - segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 maxVertices: number?, -- per geometry (default 2^24) } type EncodeOptions = { encoding: ("xml" | "x3dv")?, -- default "xml" - format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding - files: { [string]: any }?, -- receives the texture images (else url = texture.uri) - name: string?, -- the destination's file name (names the image files) + format: string?, -- "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- else url = texture.uri + name: string?, flipV: boolean?, -- default true (the inverse of decode) } @@ -176029,13 +172897,9 @@ return X3d end __FILES["music/669"] = function() --- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and --- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides --- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until --- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), --- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). --- Not supported: UNIS 669's "super fast" speed 0, writing. +-- music/669: Composer 669 / UNIS 669 modules ("if" / "JN"), ported from OpenMPT's Load_669.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Supports: 8 channels, 64-row patterns, played as the "s3m" family with 669's quirks +-- (periods in Hz, auto portamentos, effects D..H, a fixed 78 BPM). Not supported: UNIS 669's speed 0, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176055,16 +172919,16 @@ local Six69 = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local IT = Load.IT --- the 669 effects (high nibble of the effect byte) by name +-- effects: the high nibble of the effect byte local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } -- ------------------------------------------------------------------------------------------------ sniff --- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +-- the 497-byte header (the magic is two bytes only, so the other fields are checked too) local function validHeader(r: Bytes.Reader): boolean if r:size() < 497 then return false @@ -176227,7 +173091,6 @@ function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Six69.decode(r, opts) if not m then @@ -176240,12 +173103,9 @@ return Six69 end __FILES["music/ahx"] = function() --- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: --- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). --- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel --- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's --- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. --- Not supported: writing. +-- music/ahx: AHX (Abyss' Highest eXperience) 4-channel Amiga synth modules, "THX\0" .. "THX\2", rendered through +-- codecs/audio/Hively (a port of HivelyTracker's hvl2wav, BSD-3-Clause; at 44.1 kHz, stereo 0, equal to hvl2wav). +-- Supports: tracks, positions with transposes, PList instruments, subsongs. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176264,7 +173124,7 @@ local Ahx = { } -- ------------------------------------------------------------------------------------------------ types -type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration +type RenderOptions = Hively.RenderOptions -- stereo 0..4 -- ------------------------------------------------------------------------------------------------ sniff function Ahx.sniff(r: Bytes.Reader): number @@ -176282,7 +173142,6 @@ function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Ahx.decode(r) if not song then @@ -176295,13 +173154,9 @@ return Ahx end __FILES["music/far"] = function() --- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any --- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads --- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods --- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, --- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed --- tempo OpenMPT uses (80 BPM in tracker terms). --- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. +-- music/far: Farandole Composer modules (FAR, 16 channels), ported from OpenMPT's Load_far.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Plays as the "s3m" family with FAR's quirks (periods in Hz, a slide step of +-- 36318 / 1024 Hz, OpenMPT's fixed 80 BPM). Not supported: FAR's tempo effects (D / E), note offset (C), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176321,7 +173176,7 @@ local Far = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -176336,7 +173191,7 @@ function Far.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +-- effect byte -> S3M effect, parameter, volume byte (0 = none): OpenMPT's table local function effect(e: number): (number, number, number) local cmd, p = e // 16, e % 16 if cmd == 1 then @@ -176516,7 +173371,6 @@ function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Far.decode(r, opts) if not m then @@ -176529,16 +173383,9 @@ return Far end __FILES["music/hmp"] = function() --- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) --- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the --- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE --- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per --- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker --- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a --- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP --- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the --- tracks apply on top. Renders through codecs/audio/MidiRender. --- Not supported: writing; HMP branch tables (skipped). +-- music/hmp: HMI SOS music: HMP ("HMIMIDIP", "HMIMIDIP013195") and HMI ("HMI-MIDISONG061595"), from the layout +-- notes (wildmidi only as a test reference). Decodes to a Types.Midi (format 1, a track per chunk; the tick rate at +-- HMP 0x38 / HMI byte 212, as division 60). Not supported: writing, HMP branch tables. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176573,8 +173420,7 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; --- otherwise the MIDI encoding +-- HMP deltas: 7-bit groups, least significant first, the last byte has bit 7 set; HMI: the MIDI encoding local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) local v, shift = 0, 1 for _ = 1, 5 do @@ -176609,14 +173455,13 @@ end type Ctx = { loops: number, budget: number } --- one track [p, e) -> events (note-offs merged in) | nil, message local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, running = 0, 0 while p < e do local d, q = delta(b, p, e, hmp) if not d then - break -- (a track cut inside its last delta: keep what was read) + break end tick += d p = q @@ -176700,7 +173545,6 @@ local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ( return out, nil end --- the chunk table -> { { start, stop } } track ranges | nil, message, kind local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) local new = buffer.readstring(b, base + 8, 6) == "013195" local n = readu32(b, base + 0x30) @@ -176791,7 +173635,6 @@ function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Hmp.decode(r, opts) if not midi then @@ -176804,12 +173647,9 @@ return Hmp end __FILES["music/hvl"] = function() --- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, --- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- --- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with --- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer --- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. --- Not supported: writing. +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1" (AHX extended: 4..16 channels, two effect columns, ring +-- modulation, panning, stereo separation), rendered through codecs/audio/Hively (a port of hvl2wav, BSD-3-Clause; at +-- 44.1 kHz equal to hvl2wav). Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176828,7 +173668,7 @@ local Hvl = { } -- ------------------------------------------------------------------------------------------------ types -type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's) +type RenderOptions = Hively.RenderOptions -- stereo comes from the file -- ------------------------------------------------------------------------------------------------ sniff function Hvl.sniff(r: Bytes.Reader): number @@ -176846,7 +173686,6 @@ function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Hvl.decode(r) if not song then @@ -176859,14 +173698,9 @@ return Hvl end __FILES["music/it"] = function() --- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to --- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or --- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, --- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo --- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. --- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's --- extension chunks (plugins, extended instrument properties), writing. +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT), played through codecs/audio/Tracker. Supports: 64 channels, +-- instrument / sample mode, old and new instrument headers, envelopes, NNAs, resonant filters (default Zxx macros), +-- IT 2.14 / 2.15 compressed samples, the message. Not supported: embedded MIDI macros, OpenMPT extensions, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176886,7 +173720,7 @@ local It = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -177033,7 +173867,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- channels: the highest one any pattern uses local nch = 1 local packed: { Bytes.Reader? } = {} local rowsOf: { number } = {} @@ -177047,7 +173880,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end local data = pr:slice(len) packed[p], rowsOf[p] = data, rows - -- scan for the channel count local scan = data:sub(0) local seen: { [number]: number } = {} while not scan:eof() do @@ -177118,7 +173950,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local mr = r:sub(msgOff, msgLen) m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") end - -- instruments for i = 1, insnum do local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) if not ins then @@ -177126,7 +173957,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end m.instruments[i] = ins end - -- samples local total = 0 for i = 1, smpnum do local h = r:sub(smpOff[i], 80) @@ -177208,7 +174038,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(rowsOf[p], nch) m.patterns[p] = pat @@ -177275,7 +174104,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = It.decode(r, opts) if not m then @@ -177289,16 +174117,12 @@ end __FILES["music/it/Itsex"] = @native function() --- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). --- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of --- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. --- --- Never throws: every read is bounds-checked; corrupt streams return nil, message. +-- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each +-- a u16 length then an LSB-first bit stream of deltas with three width-change methods. local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 local Itsex = {} --- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message @native function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) local out = buffer.create(frames * 4) local blockLen = if bits == 16 then 0x4000 else 0x8000 @@ -177323,7 +174147,6 @@ local Itsex = {} return nil, "compressed block runs past the end" end p = bend - -- bit reader over [bstart, bend) local bytePos = bstart local bitBuf = 0 local bitCount = 0 @@ -177379,7 +174202,6 @@ local Itsex = {} continue end end - -- a delta, sign-extended from its width local x = v if width < topWidth then local shift = 2 ^ width @@ -177410,16 +174232,9 @@ return Itsex end __FILES["music/med"] = function() --- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, --- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song --- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL --- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks --- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop --- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave --- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, --- default pitch, volume). --- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and --- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. +-- music/med: MED / OctaMED modules (MMD0..MMD3), ported from OpenMPT's Load_med.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); the first song plays as the "xm" family with Amiga periods. Supports: 1..64 tracks, +-- play sequences, hold / decay, IFF multi-octave samples. Not supported: synth / MIDI instruments, echo, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -177439,7 +174254,7 @@ local Med = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -177489,7 +174304,7 @@ end -- ------------------------------------------------------------------------------------------------ decode type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } --- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +-- OpenMPT's MMDTempoToBPM (SPD / 8-channel / BPM modes) local function tempoToBpm(tempo: number, ctx: Ctx): number if ctx.bpm and not ctx.is8Ch then return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 @@ -177504,7 +174319,7 @@ local function tempoToBpm(tempo: number, ctx: Ctx): number return tempo / 0.264 end --- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +-- MED command -> MOD / XM effect, param, note-cut flag: OpenMPT's ConvertMEDEffect local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) local lo = math.min(p, 15) if cmd == 1 or cmd == 2 then @@ -177590,7 +174405,7 @@ local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolea return 0, 0, false end --- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +-- OpenMPT's octave wrapping local function wrapNote(note: number, vol7bit: boolean): number local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) if n > 132 and not vol7bit then @@ -177601,7 +174416,6 @@ local function wrapNote(note: number, vol7bit: boolean): number return if n >= 13 then n - 12 else 0 end --- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) local br = r:sub(off) local ntracks, nrows, info @@ -177711,7 +174525,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if numSamples > 0 and smpOff == 0 then return nil, Err.new(Err.CORRUPT, "no sample table") end - -- channels: the widest block (at least 4) local nch = 4 local blockPtr: { number } = {} for b = 0, numBlocks - 1 do @@ -177750,7 +174563,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if ext.nameOff > 0 and ext.nameLen > 0 then m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) end - -- instruments and samples local needInstruments = false local instruments, samples = {}, {} local unsupported = {} @@ -177830,7 +174642,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- sample data local list = {} for i = 0, count - 1 do local s = Tracker.newSample(name) @@ -177865,7 +174676,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) frames, ls, le = frames * 2, ls * 2, le * 2 end end - -- the instrument extras if xsize > 0 then if x.hold > 0 and not isSynth then local env = Tracker.newEnvelope() @@ -178002,7 +174812,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end m.preamp = preamp - -- tempo, speed, volume, the pattern context local ctx: Ctx = { transpose = 36 + playTranspose - (if version > 2 then 24 else 0), is8Ch = bit32.band(flags, 0x40) ~= 0, @@ -178017,7 +174826,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if masterVol > 0 then m.globalVolume = math.min(masterVol, 64) * 2 end - -- blocks for b = 0, numBlocks - 1 do local p = blockPtr[b + 1] local pat, high = nil, false @@ -178031,7 +174839,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for at, to in jumps do local prev = m.order[at - 1] if prev and prev < 254 and m.patterns[prev + 1] then - -- the block may be played elsewhere: give this order entry its own copy local src = m.patterns[prev + 1] local cp = Tracker.newPattern(src.rows, nch) buffer.copy(cp.data, 0, src.data) @@ -178060,7 +174867,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Med.decode(r, opts) if not m then @@ -178073,16 +174879,9 @@ return Med end __FILES["music/midi"] = function() --- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the --- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). --- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / --- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, --- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: --- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to --- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running --- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and --- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. --- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). +-- music/midi: Standard MIDI Files (SMF 1.0 formats 0 / 1 / 2, PPQ and SMPTE; RIFF RMID read), from the spec. Supports: +-- decode to a Types.Midi, .kar lyrics, encode (byte-identical to python mido by default), the tempo map, rendering +-- through codecs/audio/SoundFont. Not supported: RMID write, XMF / DLS banks, system common bytes in tracks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -178104,7 +174903,7 @@ local Midi = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) -type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices +type RenderOptions = Render.RenderOptions -- ------------------------------------------------------------------------------------------------ sniff function Midi.sniff(r: Bytes.Reader): number @@ -178118,8 +174917,7 @@ function Midi.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and --- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +-- .kar: FF 01 text in a "Words" track (or after an "@K" / "@T" header) and FF 05 lyrics; "@X" headers -> meta.karaoke[X] local function karaoke(midi: Types.Midi) local lyrics: { { time: number, tick: number, text: string } } = {} local headers: { [string]: { string } } = {} @@ -178193,7 +174991,6 @@ function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err? end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Midi.decode(r, opts) if not midi then @@ -178203,38 +175000,30 @@ function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) return Render.decoder(midi, opts) end --- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number return Render.seconds(Render.tempoMap(midi, track), tick) end --- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) Midi.tempoMap = Render.tempoMap Midi.seconds = Render.seconds --- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +-- as python mido's MidiFile.length (formats 0 / 1) function Midi.length(midi: Types.Midi): number return Render.length(midi) end --- text(data) -> the bytes of a text meta event as a string Midi.text = Smf.text return Midi end __FILES["music/midi/Smf"] = function() --- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE --- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps --- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are --- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the --- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track --- has none. Written from the SMF 1.0 specification (no third-party code). +-- music/midi/Smf: SMF 1.0 MThd / MTrk <-> Types.Midi (running status also across meta / sysex, RIFF RMID unwrapped). +-- Writes what python mido writes: running status reset after meta / sysex, one end-of-track, track names at tick 0. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -178273,13 +175062,11 @@ end Smf.text = text -- ------------------------------------------------------------------------------------------------ read --- one MTrk body [p, e): events | nil, message, truncated local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = {} local tick = 0 local running = 0 while p < e do - -- delta time local delta, n = 0, 0 repeat if p >= e then @@ -178370,7 +175157,6 @@ local function readTrack(b: buffer, p: number, e: number, budget: { number }): ( return events, nil, false end --- read(r, opts?) -> Midi | nil, Err function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) local strict = opts and opts.strict or false local budget = { opts and opts.maxEvents or 2 ^ 24 } @@ -178497,7 +175283,6 @@ local function byteList(d: any, want: number?): { number }? return d end --- write(midi, opts?) -> buffer | nil, Err function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(midi) ~= "table" or type(midi.tracks) ~= "table" then return nil, Err.new(Err.ARG, "needs a Midi value with tracks") @@ -178528,7 +175313,6 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(events) ~= "table" then return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") end - -- stable order by tick local sorted = true local last = 0 for i, ev in events do @@ -178554,7 +175338,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) return order[a] < order[c] end) end - -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own +-- a track-name meta event (0x03) at tick 0 when the track has none (as mido) if type(track.name) == "string" and track.name ~= "" then local named = false for _, ev in list do @@ -178649,13 +175433,9 @@ return Smf end __FILES["music/mod"] = function() --- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, --- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or --- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through --- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" --- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). --- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter --- (E0x), PowerPacker-packed files. +-- music/mod: ProTracker / NoiseTracker / StarTrekker MODs (M.K., M!K!, FLT4, xCHN, xxCH, xxCN, CD81, OKTA, TDZx; +-- 15-sample Soundtracker by name or extension), from the ProTracker 2.3 docs. Writes 31-sample MODs from "mod" modules +-- and XM ones that fit. Not supported: FLT8's split patterns (read as 8 channels), the E0x filter, PowerPacker files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -178674,7 +175454,7 @@ local Mod = { } type DecodeOptions = { - maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) + maxBytes: number?, -- f32 bytes of sample data in total, default 64 MB } type EncodeOptions = {} @@ -178696,7 +175476,7 @@ local FIXED: { [string]: number } = { ["EXO8"] = 8, } --- channels from the 4-byte signature at 1080, or nil +-- the 4-byte signature at offset 1080 local function signatureChannels(sig: string): number? local fixed = FIXED[sig] if fixed then @@ -178793,7 +175573,6 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.restart = if restart < songLength then restart else 0 m.meta.signature = if nsamples == 31 then sig else nil m.flags.amigaLimits = nch == 4 - -- patterns local npat = maxPat + 1 local patBytes = 64 * nch * 4 if not r:need(npat * patBytes) then @@ -178818,7 +175597,7 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.patterns[p + 1] = pat end r:skip(npat * patBytes) - -- sample data (8-bit signed; the last samples of a truncated file are cut short) +-- sample data: 8-bit signed local total = 0 for i = 1, nsamples do local s = m.samples[i] @@ -178856,8 +175635,6 @@ local function writeName(w: Bytes.Writer, s: string, n: number) w:fill(0, n - #t) end --- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to --- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) local ok, verr = Tracker.validate(m) if not ok then @@ -178870,7 +175647,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) if nch > 32 then return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") end - -- the sample for each instrument number local smpOf: { any } = {} if m.format == "xm" then for i, ins in m.instruments do @@ -178923,7 +175699,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) local len = math.min(s.length, 131070) local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) if s.channels == 2 then - -- mix stereo samples down local mono = buffer.create(len * 4) for k = 0, len - 1 do buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) @@ -178999,7 +175774,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mod.decode(r, opts) if not m then @@ -179012,12 +175786,9 @@ return Mod end __FILES["music/mtm"] = function() --- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared --- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): --- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk --- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). --- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. +-- music/mtm: MultiTracker modules (MTM, 1..32 channels, patterns of shared tracks), ported from OpenMPT's Load_mtm.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "xm" family with Amiga periods, as OpenMPT does. Not supported: +-- MultiTracker's E9x / EDx retrigger timing and vibrato start phase (played as in XM), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179037,7 +175808,7 @@ local Mtm = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -179117,7 +175888,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for i = 1, nch do m.channelPan[i] = (pans[i] % 16) * 16 + 8 end - -- samples local sizes: { number } = {} for i = 1, numSamples do local s = Tracker.newSample(r:fixed(22)) @@ -179148,7 +175918,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.length = frames m.samples[i] = s end - -- the order list for i = 1, 128 do local o = r:u8() if i <= lastOrder + 1 then @@ -179227,7 +175996,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mtm.decode(r, opts) if not m then @@ -179240,15 +176008,9 @@ return Mtm end __FILES["music/mus"] = function() --- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format --- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter --- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel --- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at --- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without --- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per --- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / --- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. --- Not supported: writing (save as .mid through the midi format's encoder). +-- music/mus: DMX MUS ("MUS\x1a"; Doom, Heretic, Hexen, Strife), from Vladimir Arnost's "MUS File Format" (wildmidi +-- only as a test reference). Decodes to a Types.Midi as the usual converters map it (MUS channel 15 -> 9; 140 ticks/s +-- as division 70 at 500000 us per quarter). Not supported: writing (encode as .mid with the midi format). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179284,7 +176046,6 @@ end -- ------------------------------------------------------------------------------------------------ decode local readu8 = buffer.readu8 --- the score [p, e) -> events | nil, message local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } local map: { [number]: number } = { [15] = 9 } @@ -179392,7 +176153,6 @@ function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Mus.decode(r, opts) if not midi then @@ -179405,13 +176165,9 @@ return Mus end __FILES["music/okt"] = function() --- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can --- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style --- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with --- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample --- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: --- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. --- Not supported: the Amiga LED filter (F), writing. +-- music/okt: Oktalyzer modules (OKTASONG, 4..8 channels: each Amiga channel may be a mixed pair), ported from OpenMPT's +-- Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, loops as sustain +-- loops (released by R), the three arpeggios and note slides. Not supported: the LED filter (F), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179432,7 +176188,7 @@ local Okt = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -179445,7 +176201,6 @@ function Okt.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a negative arpeggio offset as the equivalent positive one local function invert(p: number): number p %= 16 if p == 0 then @@ -179454,7 +176209,6 @@ local function invert(p: number): number return if p <= 12 then 12 - p else 24 - p end --- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) if e == 1 and p > 0 then return "portaup", p, -1, false -- "portamento down (period)": the period goes down @@ -179680,7 +176434,6 @@ function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Okt.decode(r, opts) if not m then @@ -179693,13 +176446,9 @@ return Okt end __FILES["music/ptm"] = function() --- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD --- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx --- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, --- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the --- byte stream, as PolyTracker stores them), ping-pong loops. --- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. +-- music/ptm: PolyTracker modules (PTMF, up to 32 channels), ported from OpenMPT's Load_ptm.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts PTM. Not supported: +-- reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179719,7 +176468,7 @@ local Ptm = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -179753,7 +176502,6 @@ local function delta16(buf: buffer, off: number, frames: number, limit: number): return raw, n end --- a PolyTracker effect -> name?, param local function effect(cmd: number, param: number): (string?, number) if cmd == 0x10 then return "globalvol", math.min(param, 0x40) * 2 @@ -179848,7 +176596,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- samples local buf = r.buf for i = 1, nsmp do local h = r:slice(80) @@ -179909,7 +176656,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ptm.decode(r, opts) if not m then @@ -179922,12 +176668,9 @@ return Ptm end __FILES["music/s3m"] = function() --- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio --- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning --- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 --- speed reference, as IT shows S3M files). --- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC). Supports: 32 PCM channels, 8 / 16-bit mono / stereo +-- samples, the panning table, ST3.00 fast slides, every ST3 effect; notes stored an octave up (S3M C-4 = note 61, as IT +-- shows S3M files). Not supported: AdLib (OPL) instruments (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179946,7 +176689,7 @@ local S3m = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -180009,7 +176752,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } - -- orders, parapointers, panning r:seek(96) for i = 1, ordnum do local o = r:u8() @@ -180049,7 +176791,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.channelPan[i] = pan m.channelMute[i] = c >= 16 end - -- samples local total = 0 local unsigned = ffi ~= 1 for i = 1, insnum do @@ -180077,7 +176818,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 local off = (hi * 65536 + lo) * 16 len = math.min(len, 2 ^ 26) - -- a short file: keep what is there local avail = math.max(0, r:size() - off) // (nchs * bits // 8) len = math.min(len, avail) total += len * nchs * 4 @@ -180093,7 +176833,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(64, nch) m.patterns[p] = pat @@ -180153,7 +176892,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = S3m.decode(r, opts) if not m then @@ -180166,11 +176904,9 @@ return S3m end __FILES["music/sf2"] = function() --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the --- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), --- presets / instruments / sample headers with global zones, generator merging into playable regions. --- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). --- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 spec), read-only, over codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: INFO, 16 / 24-bit (sm24) samples, presets / instruments with global zones, generators merged into regions. +-- Not supported: writing, SF3 (Vorbis samples), modulators (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180204,7 +176940,6 @@ function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback @@ -180212,12 +176947,9 @@ return Sf2 end __FILES["music/stm"] = function() --- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). --- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module --- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the --- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump --- happens at the end of the pattern or at the next Cxx). --- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro), ported from OpenMPT's +-- Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "s3m" family with ST2's tempo, no effect memory and +-- its deferred Bxx. Not supported: STX, ST2's noise for samples at volume 0 (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180237,7 +176969,7 @@ local Stm = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -180434,7 +177166,6 @@ function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Stm.decode(r, opts) if not m then @@ -180447,14 +177178,9 @@ return Stm end __FILES["music/ult"] = function() --- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored --- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). --- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects --- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect --- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone --- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. --- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the --- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004, up to 32 channels), ported from OpenMPT's Load_ult.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts ULT. Not +-- supported: reverse (5x2), "no loop" (5x1), E0x, offsets past 64 KiB, pre-1.4 log volumes, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180474,7 +177200,7 @@ local Ult = { } type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -180493,7 +177219,7 @@ function Ult.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +-- OpenMPT's TranslateULTCommands local function translate(e: number, param: number, version: number): (string?, number) local name = EFFECTS[e] if e == 0 then @@ -180542,7 +177268,7 @@ local function translate(e: number, param: number, version: number): (string?, n return name, param end --- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +-- OpenMPT's CombineEffects (volume slide + vibrato / tone portamento without a parameter) local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 @@ -180552,8 +177278,7 @@ local function combine(a: string?, pa: number, b: string?, pb: number): (string? return a, pa, b, pb end --- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, --- lost global effect (name?, param) +-- event: [0xFC repeat] note instrument effects param1 param2 local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) local rep = 1 local b = r:u8() @@ -180745,7 +177470,6 @@ function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ult.decode(r, opts) if not m then @@ -180758,14 +177482,9 @@ return Ult end __FILES["music/umx"] = function() --- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package --- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): --- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each --- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first --- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and --- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is --- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. --- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. +-- music/umx: Unreal Engine 1 music packages (.umx, versions up to 128), ported from OpenMPT's UMXTools.cpp / +-- ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): the IT / S3M / XM / MOD module of a "music" export; decode +-- needs opts.decodeModule (the api passes it). Not supported: Unreal Engine 2+ packages (.uax), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180784,8 +177503,8 @@ local Umx = { } type DecodeOptions = { - decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it) - index: number?, -- which music export to load (1-based, default 1) + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, + index: number?, -- 1-based, default 1 } type Entry = { name: string, data: buffer, format: string? } @@ -180863,8 +177582,6 @@ function Umx.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: --- a guess from the inner module's signature: "it", "s3m", "xm", "mod") function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) local h = header(r) if not h then @@ -180969,7 +177686,6 @@ function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Umx.decode(r, opts) if not m then @@ -180982,14 +177698,9 @@ return Umx end __FILES["music/xm"] = function() --- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / --- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and --- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit --- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga --- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files --- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). --- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's --- stereo-sample / extra-effect extensions on write. +-- music/xm: FastTracker 2 Extended Modules (XM 1.04), from the XM spec and FT2 behaviour notes. Supports: 8 / 16-bit +-- delta and ModPlug ADPCM samples, envelopes, linear / Amiga tables, every FT2 effect; writes "xm" (byte-identical in +-- FT2's layout) and "mod" modules. Not supported: OpenMPT's stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181046,7 +177757,6 @@ local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: numb e.loop = bit32.band(typ, 4) ~= 0 e.susStart, e.susEnd = sus + 1, sus + 1 e.loopStart, e.loopEnd = ls + 1, le + 1 - -- the raw fields, for a faithful re-save e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } return e end @@ -181089,7 +177799,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end m.meta.tracker = tracker m.meta.source = { format = "xm", tracker = tracker, version = version } - -- patterns if not r:seek(hdrStart + hdrSize) then return nil, r.err end @@ -181141,7 +177850,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) param = pr:u8() end if pr.err then - break -- a short pattern: the rest stays empty + break end if note == 97 then note = 255 @@ -181160,7 +177869,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- instruments and their samples local total = 0 for i = 1, nins do local start = r:tell() @@ -181169,7 +177877,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) r:u8() local ns = r:u16le() if r.err then - -- a file cut inside the instruments: keep what was read r.err = nil break end @@ -181226,8 +177933,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.pan = h.pan local frames = h.len // bps if h.res == 0xAD and bits == 8 then - -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps - -- the samples whose nibbles are present +-- ModPlug ADPCM: a 16-byte delta table, then 4 bits per sample frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) total += frames * 4 if total > maxBytes then @@ -181283,7 +177989,6 @@ local function writeName(w: Bytes.Writer, s: string?, n: number) w:fill(0, n - #t) end --- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } local function instrumentsOf(m: any): ({ any }?, string?) local out = {} if m.format == "mod" then @@ -181348,7 +178053,7 @@ local function envelopeFields(e: any): (number, number, number, number, number) local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) local raw = e.raw if raw and raw.type % 8 == typ then - typ = raw.type -- keep unknown bits + typ = raw.type end local function idx(v: number): number return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) @@ -181361,7 +178066,6 @@ local function envelopeFields(e: any): (number, number, number, number, number) return n, typ, sus, ls, le end --- encode(module, opts) -> XM bytes ("xm" or "mod" modules) function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) local ok, verr = Tracker.validate(m) if not ok then @@ -181462,7 +178166,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) w:u16le(buffer.len(data)) w:bytes(data) end - -- instruments for _, it in insts do local ins = it.ins local smps = it.samples @@ -181544,7 +178247,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Xm.decode(r, opts) if not m then @@ -181557,14 +178259,9 @@ return Xm end __FILES["music/xmi"] = function() --- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, --- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description --- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, --- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's --- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second --- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the --- first tempo event's value, unused). Renders through codecs/audio/MidiRender. --- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. +-- music/xmi: Miles XMIDI (IFF: optional FORM XDIR, then CAT XMID of FORM XMID songs with TIMB / RBRN / EVNT), from +-- the XMIDI notes (Miles AIL, Ryan Nunn; wildmidi only as a test reference). Decodes one song to a Types.Midi at the +-- fixed 120 ticks per second (division 60). Not supported: writing, the RBRN branch table, MT-32 -> GM mapping. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181603,7 +178300,6 @@ local readu8 = buffer.readu8 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a MIDI variable-length number at p -> value, next p (nil past e) local function vlq(b: buffer, p: number, e: number): (number?, number) local v = 0 for _ = 1, 4 do @@ -181628,7 +178324,6 @@ local function bytes(b: buffer, p: number, n: number): { number } return t end --- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, tempo = 0, nil @@ -181695,7 +178390,6 @@ local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Ty return Render.merge(list, offs), tick, tempo end --- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } } local out = {} local function form(c: Chunks.Chunk) @@ -181761,7 +178455,6 @@ function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Xmi.decode(r, opts) if not midi then @@ -181774,20 +178467,8 @@ return Xmi end __FILES["ops/AudioOps"] = function() --- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an --- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), --- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. --- --- local AudioOps = require("@rosetta/ops/AudioOps") -- F.ops.audio in the api --- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder --- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) --- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) --- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) --- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's --- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) --- local both = AudioOps.concat({ a, b }) --- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape --- +-- ops/AudioOps: editing on the standard Audio: collect, gain, normalize, mix, remix, resample (codecs/audio/Resample), +-- trim, concat, fades, peak / RMS. New code. -- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders -- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the -- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot @@ -181803,7 +178484,6 @@ local AudioOps = {} local readf32, writef32 = buffer.readf32, buffer.writef32 local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt --- ------------------------------------------------------------------------------------------------ validation local function isAudio(a: any): boolean return type(a) == "table" and a.kind == "audio" @@ -181820,7 +178500,6 @@ local function bad(what: string): (nil, Err.Err) return nil, Err.new(Err.ARG, what) end --- a new Audio with a's rate / tags / meta and the given layout local function like(a: Types.Audio, channels: number, frames: number, rate: number?): Types.Audio local out = Types.Audio.new(rate or a.sampleRate, channels, frames) out.tags = table.clone(a.tags or {}) @@ -181828,9 +178507,6 @@ local function like(a: Types.Audio, channels: number, frames: number, rate: numb return out end --- ------------------------------------------------------------------------------------------------ conversion --- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT --- past it; default 2^31) function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, Err.Err?) if isAudio(v) then return v, nil @@ -181843,8 +178519,6 @@ function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, end AudioOps.fromDecoder = AudioOps.toAudio --- ------------------------------------------------------------------------------------------------ levels --- gain(a, factor) -> Audio with every sample times factor function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("gain: expected an Audio") @@ -181861,7 +178535,6 @@ function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?) return out, nil end --- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?) if type(db) ~= "number" or db ~= db then return bad("gainDb: dB must be a number") @@ -181869,7 +178542,6 @@ function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?) return AudioOps.gain(a, 10 ^ (db / 20)) end --- peak(a) -> the largest |sample|, { per channel } function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err) if not isAudio(a) then return nil, Err.new(Err.ARG, "peak: expected an Audio") @@ -181893,7 +178565,6 @@ function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err) return m, per end --- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err) if not isAudio(a) then return nil, Err.new(Err.ARG, "rms: expected an Audio") @@ -181917,7 +178588,6 @@ function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err) return sqrt(total / (n * ch)), per end --- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err.Err?) local p, perr = AudioOps.peak(a) if not p then @@ -181930,7 +178600,6 @@ function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err return AudioOps.gain(a, if p > 0 then t / p else 1) end --- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("fade: expected an Audio") @@ -181961,7 +178630,6 @@ function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types. return out, nil end --- ------------------------------------------------------------------------------------------------ channels -- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) local LAYOUT: { { string } } = { { "C" }, @@ -181980,7 +178648,7 @@ local TO_STEREO: { [string]: { number } } = { SR = { 0, H }, BC = { 0.5, 0.5 }, } --- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +-- m[o][i]: output channel o = sum m[o][i] * input i local function matrix(from: number, to: number): { { number } } local m: { { number } } = table.create(to) :: any for o = 1, to do @@ -182071,7 +178739,6 @@ local function matrix(from: number, to: number): { { number } } end AudioOps.matrix = matrix --- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("remix: expected an Audio") @@ -182113,7 +178780,6 @@ function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): ( return out, nil end --- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("downmix: expected an Audio") @@ -182125,7 +178791,6 @@ function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err return AudioOps.remix(a, n) end --- upmix(a, channels) -> Audio with more channels function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("upmix: expected an Audio") @@ -182136,8 +178801,6 @@ function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Er return AudioOps.remix(a, channels) end --- ------------------------------------------------------------------------------------------------ time --- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("resample: expected an Audio") @@ -182152,7 +178815,6 @@ function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options? return out, nil end --- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("trim: expected an Audio") @@ -182168,7 +178830,6 @@ function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Aud return out, nil end --- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, Err.Err?) if type(list) ~= "table" or #list == 0 then return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") @@ -182202,7 +178863,6 @@ local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, return out, nil end --- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?) local items, err = conform(list, "concat") if not items then @@ -182223,8 +178883,6 @@ function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?) return out, nil end --- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at --- the first one's rate and channel count function AudioOps.mix(list: { Types.Audio }, weights: { number }?): (Types.Audio?, Err.Err?) local items, err = conform(list, "mix") if not items then @@ -182258,17 +178916,8 @@ return AudioOps end __FILES["ops/ImageOps"] = function() --- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion, --- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as --- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and --- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources. --- --- local Ops = require("@rosetta/ops/ImageOps") --- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws) --- local grey = Ops.convert(img, "gray8") --- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over" --- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation --- +-- ops/ImageOps: editing on the standard Image: conversion, crop, resize, flips, rotation, compositing, pixel access, +-- animation helpers. New code; the resampling and compositing follow Pillow's C sources. -- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as -- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's -- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and @@ -182284,7 +178933,6 @@ local MAX_PIXELS = 2 ^ 26 type Image = Types.Image --- ------------------------------------------------------------------------------------------------ validation local function arg(msg: string): (nil, Err.Err) return nil, Err.new(Err.ARG, msg) end @@ -182301,7 +178949,6 @@ local function bytesOf(fmt: string, w: number, h: number): number? return if bpp then w * h * bpp else nil end --- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough) local function check(img: any): (boolean?, Err.Err?) if type(img) ~= "table" or type(img.pixels) ~= "buffer" then return arg("expected an Image") @@ -182328,7 +178975,6 @@ local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) return true, nil end --- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames local function like(img: Image, w: number, h: number, fmt: string?): Image local out = Types.Image.new(w, h, (fmt or img.format) :: any) for k, v in img.meta do @@ -182338,8 +178984,6 @@ local function like(img: Image, w: number, h: number, fmt: string?): Image return out end --- ------------------------------------------------------------------------------------------------ basics --- new(w, h, format?) -> a zero-filled Image | nil, Err function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) local fmt = format or "rgba8" if not isInt(w) or not isInt(h) or w < 1 or h < 1 then @@ -182355,7 +178999,6 @@ function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) return Types.Image.new(w, h, fmt :: any), nil end --- copy(img) -> a deep copy of the pixels (frames are shared) function ImageOps.copy(img: Image): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182367,8 +179010,6 @@ function ImageOps.copy(img: Image): (Image?, Err.Err?) return out, nil end --- ------------------------------------------------------------------------------------------------ convert --- convert(img, format) -> a new Image in format (a copy when it is already) function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182417,10 +179058,8 @@ local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, E return ImageOps.convert(res, "yuv420p") end --- ------------------------------------------------------------------------------------------------ geometry local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } --- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182442,7 +179081,6 @@ function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): end) end --- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom) function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182458,7 +179096,6 @@ function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) end) end --- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise) function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182481,7 +179118,6 @@ end type ResizeFilter = "nearest" | "bilinear" | "lanczos" --- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels) function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182534,9 +179170,6 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts end) end --- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's --- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered --- pixels are zero (transparent). opts.maxPixels. function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182596,14 +179229,10 @@ function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, end) end --- ------------------------------------------------------------------------------------------------ compositing local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true } type BlitOptions = { blend: ("over" | "source")?, opacity: number? } --- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's --- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite --- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only). function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?) local ok, e = check(dst) if not ok then @@ -182624,7 +179253,6 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then return arg("blit: opacity must be 0..1") end - -- clip local sx, sy = math.max(0, -x), math.max(0, -y) local dx, dy = math.max(0, x), math.max(0, y) local w = math.min(src.width - sx, dst.width - dx) @@ -182662,7 +179290,6 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO return dst, nil end --- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?) local out, e = ImageOps.copy(dst) if not out then @@ -182685,7 +179312,6 @@ local function premul(img: Image, un: boolean): (Image?, Err.Err?) return out, nil end --- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) function ImageOps.premultiply(img: Image): (Image?, Err.Err?) return premul(img, false) end @@ -182693,11 +179319,8 @@ function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?) return premul(img, true) end --- ------------------------------------------------------------------------------------------------ pixels local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } --- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; --- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?) local ok, e = check(img) if not ok then @@ -182737,8 +179360,6 @@ function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number? return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 end --- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and --- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p. function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?) local ok, e = check(img) if not ok then @@ -182805,7 +179426,6 @@ function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: numbe return true, nil end --- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?) local ok, e = check(img) if not ok then @@ -182829,8 +179449,6 @@ function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): return img, nil end --- ------------------------------------------------------------------------------------------------ animation --- frameCount(img) -> the number of frames (1 for a still image) function ImageOps.frameCount(img: Image): number if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then return #img.frames @@ -182838,7 +179456,6 @@ function ImageOps.frameCount(img: Image): number return 1 end --- durations(img) -> { seconds } per frame ({ 0 } for a still image) function ImageOps.durations(img: Image): { number } local out = {} if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then @@ -182850,10 +179467,7 @@ function ImageOps.durations(img: Image): { number } return { 0 } end --- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 / --- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's --- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores --- the canvas from before the frame). A still image gives { img }. +-- coalesce: dispose "none" keeps the canvas, "background" clears the frame's rectangle, "previous" restores it function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) local ok, e = check(img) if not ok then @@ -182909,9 +179523,6 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) return out, nil end --- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, --- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds } --- (default 0.1). All images need the same size and format. function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?) if type(images) ~= "table" or #images == 0 then return arg("fromFrames: a non-empty list of Images") @@ -182951,12 +179562,9 @@ __FILES["ops/ImageOps/Kernels"] = @native function() --- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller --- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by --- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers). --- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by --- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through --- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c. +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps; callers validate, so indexes are in range by construction. +-- Sample kinds: 1 = u8, 2 = u16, 4 = f32 (little endian). Resampling follows Pillow's Resample.c (separable, 22-bit +-- fixed point for 8-bit) and Geometry.c (affine through pixel centres); compositing is Pillow's AlphaComposite.c. local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 local floor, clamp = math.floor, math.clamp @@ -182986,7 +179594,6 @@ end end end --- ------------------------------------------------------------------------------------------------ convert -- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } @@ -183005,7 +179612,6 @@ local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } end return v / 65535 end - -- float if v ~= v then v = 0 end @@ -183151,8 +179757,6 @@ end local _ = ch end --- ------------------------------------------------------------------------------------------------ geometry --- flip(src, dst, w, h, bpp, horizontal) @native function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) local stride = w * bpp if not horizontal then @@ -183169,7 +179773,7 @@ end end end --- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3 +-- counter-clockwise quarter turns 1..3 @native function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) for y = 0, h - 1 do for x = 0, w - 1 do @@ -183191,7 +179795,6 @@ end end end --- ------------------------------------------------------------------------------------------------ resample @native local function bilinearF(x: number): number if x < 0 then x = -x @@ -183253,7 +179856,6 @@ type Coeffs = { start: { number }, count: { number }, weights: { { number } } } return { start = start, count = count, weights = weights } end --- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind. @native function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) local start, count, weights = c.start, c.count, c.weights local size = kind @@ -183333,8 +179935,8 @@ end end end --- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src --- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow) +-- affine: dst pixel centres through m = { a, b, c, d, e, f } (xin = a x + b y + c), bilinear with clamped +-- neighbours; centres outside the source -> zeros (Pillow) @native function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] local size = kind @@ -183371,8 +179973,7 @@ end end end --- ------------------------------------------------------------------------------------------------ compositing --- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place +-- Pillow's alpha_composite of src onto dst, in place @native function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) for y = 0, h - 1 do for x = 0, w - 1 do @@ -183425,14 +180026,12 @@ end end end --- copyRect: rows of a rectangle (bpp bytes per pixel) @native function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) for y = 0, h - 1 do buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) end end --- premultiply / unpremultiply in place: ch channels, alpha last, kind @native function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1 local px = ch * kind @@ -183474,13 +180073,6 @@ __FILES["ops/LayerOps"] = function() -- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an -- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and -- grey layer masks; every frame as an animated Image; walking the leaves. --- --- local LayerOps = require("@rosetta/ops/LayerOps") --- local img = LayerOps.flatten(layered) -- frame 1 / the layers --- local img3 = LayerOps.flatten(layered, { frame = 3 }) --- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) --- for layer, depth in LayerOps.leaves(layered.layers) do ... end --- -- Never throws: bad values return nil, Err.ARG. local Err = __include("core/Err") local Types = __include("Types") @@ -183494,7 +180086,6 @@ type FlattenOptions = { background: { number }?, -- r, g, b, a 0..255 under everything (default transparent) } --- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then return nil, Err.new(Err.ARG, "flatten: needs a Layered value") @@ -183526,7 +180117,6 @@ function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types return img, nil end --- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) local first, err = LayerOps.flatten(layered, opts) if not first then @@ -183550,7 +180140,6 @@ function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): return first, nil end --- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?) local stack: { { any } } = { { layers, 0, 0 } } return function(): (Types.Layer?, number?) @@ -183574,18 +180163,9 @@ return LayerOps end __FILES["ops/MeshOps"] = function() --- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear --- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), --- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an --- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis --- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). --- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type --- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). --- --- local MeshOps = require("@rosetta/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops) --- local prim = MeshOps.merge(scene) -- one triangle primitive in world space --- MeshOps.computeNormals(prim) --- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +-- ops/MeshOps: editing meshes in the standard Scene type: triangulate, transform, normals (area weighted or flat), +-- tangents (Lengyel 2001), weld, bounds, merge into world space, unit / up-axis changes, greedy voxel meshing. Inputs +-- may use any accessor type; outputs are f32 attributes and u32 indices. Never throws. local Err = __include("core/Err") local Types = __include("Types") local Greedy = __include("ops/MeshOps/Greedy") @@ -183600,8 +180180,6 @@ local Scene = Types.Scene local readf32, writef32 = buffer.readf32, buffer.writef32 local readu32, writeu32 = buffer.readu32, buffer.writeu32 --- ------------------------------------------------------------------------------------------------ accessors --- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one function MeshOps.f32(acc: Accessor): Accessor? if acc.type == "f32" then return acc @@ -183622,7 +180200,6 @@ function MeshOps.f32(acc: Accessor): Accessor? return a end --- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 local function indexBuffer(prim: Primitive): (buffer, number) local ind = prim.indices if ind then @@ -183689,7 +180266,6 @@ local function checkPrim(prim: any): Err.Err? end MeshOps.check = checkPrim --- ------------------------------------------------------------------------------------------------ triangulate -- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) local k = #poly @@ -183781,9 +180357,7 @@ local function u32(list: { number }): Accessor return Scene.accessor(b, "u32", 1, n) end --- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" --- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). --- Lines and points come back unchanged. +-- strips and fans unroll with glTF's alternating strip winding function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then @@ -183869,7 +180443,6 @@ function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Prim }, nil end --- ------------------------------------------------------------------------------------------------ transform local function det3(m: { number }): number return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) end @@ -183892,8 +180465,7 @@ local function normalMatrix(m: { number }): { number } } end --- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). --- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +-- a mirroring matrix (negative determinant) reverses the winding so faces stay front-facing function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then @@ -183998,10 +180570,6 @@ function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err return prim, nil end --- ------------------------------------------------------------------------------------------------ normals / tangents --- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | --- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle --- modes are triangulated first (the returned primitive is then a new one). function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) local p = prim if (prim.mode or "triangles") ~= "triangles" then @@ -184057,8 +180625,7 @@ function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Pr return p, nil end --- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | --- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_. +-- TANGENT: f32 vec4, xyz orthogonal to the normal, w = +-1 handedness function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) local p = prim if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then @@ -184140,7 +180707,6 @@ function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): return p, nil end --- ------------------------------------------------------------------------------------------------ weld / unweld local function gather(acc: Accessor, ib: buffer, n: number): Accessor local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components local out = buffer.create(n * size) @@ -184152,7 +180718,6 @@ local function gather(acc: Accessor, ib: buffer, n: number): Accessor return a end --- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) function MeshOps.unweld(prim: Primitive): Primitive local ib, n = indexBuffer(prim) local attrs = {} @@ -184173,10 +180738,6 @@ function MeshOps.unweld(prim: Primitive): Primitive return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } end --- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. --- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other --- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). --- Morph targets are kept per merged vertex (the first one's). function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then @@ -184255,9 +180816,6 @@ function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: }, nil end --- ------------------------------------------------------------------------------------------------ bounds --- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and --- voxel shape cell corners excluded) | nil, nil when there are no positions function MeshOps.bounds(x: any): ({ number }?, { number }?) local lo = { math.huge, math.huge, math.huge } local hi = { -math.huge, -math.huge, -math.huge } @@ -184311,7 +180869,6 @@ function MeshOps.bounds(x: any): ({ number }?, { number }?) return lo, hi end --- ------------------------------------------------------------------------------------------------ merge -- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) local function defaultFor(name: string, k: number): number if string.sub(name, 1, 6) == "COLOR_" then @@ -184323,11 +180880,6 @@ local function defaultFor(name: string, k: number): number return 0 end --- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | --- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input --- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. --- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets --- are not applied (the rest pose). function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) local placed: { Types.Placed } = {} if type(input) ~= "table" then @@ -184340,7 +180892,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } end end - -- triangulate + bake each local groups: { [number]: { Primitive } } = {} local order: { number } = {} local allPoints = #placed > 0 @@ -184436,7 +180987,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? return concat(all, first and first.material), nil end --- ------------------------------------------------------------------------------------------------ units / up axis local function scaleAccessor(acc: Accessor?, f: number): Accessor? if not acc then return nil @@ -184452,9 +181002,6 @@ local function scaleAccessor(acc: Accessor?, f: number): Accessor? return a end --- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and --- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by --- factor (the same physical size in smaller units). function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") @@ -184531,7 +181078,6 @@ function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) return scene, nil end --- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") @@ -184540,8 +181086,6 @@ function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err? return MeshOps.scale(scene, from / metresPerUnit) end --- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. --- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") @@ -184559,17 +181103,12 @@ function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) return scene, nil end --- ------------------------------------------------------------------------------------------------ voxels local function linear(c: number): number local s = c / 255 return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 end --- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, --- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. --- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); --- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or --- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +-- pivot "center": MagicaVoxel's placement (cell x spans x - floor(sx / 2) ..) function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a Voxels grid") @@ -184626,9 +181165,6 @@ function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scal return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil end --- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node --- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as --- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids). function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, Err.new(Err.ARG, "expected a Scene") @@ -184683,7 +181219,7 @@ type Out = { quads: number, } --- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale +-- vertex position = (cell corner + (ox, oy, oz)) * scale @native function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out local cap = 1024 local pos = buffer.create(cap * 48) @@ -184753,7 +181289,6 @@ type Out = { writei32(mask, (i + k + jj * nu) * 4, 0) end end - -- emit the rectangle if quads == cap then local ncap = cap * 2 @native local function grow2(b: buffer, per: number): buffer @@ -184768,7 +181303,6 @@ type Out = { corner[u + 1] = i corner[v + 1] = j local cx, cy, cz = corner[1], corner[2], corner[3] - -- the u and v edge vectors local ux = if u == 0 then w else 0 local uy = if u == 1 then w else 0 local uz = if u == 2 then w else 0 @@ -184832,18 +181366,8 @@ return Greedy end __FILES["ops/MusicOps"] = function() --- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the --- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, --- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / --- addInstrument / note in the api (also F.ops.music). --- --- local M = require("@rosetta/ops/MusicOps") --- local song = M.new({ format = "mod", channels = 4, title = "demo" }) --- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 --- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list --- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) --- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod --- +-- ops/MusicOps: building and editing tracker Modules over codecs/audio/Tracker without touching the engine's internal +-- layout (5-byte cells, f32 samples, tuning fields). New code. -- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample -- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 -- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering @@ -184868,7 +181392,6 @@ local function int(v: any, lo: number, hi: number): boolean return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi end --- ------------------------------------------------------------------------------------------------ module type NewOptions = { format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved) channels: number?, -- 1..32 for mod, else 1..64 (default 4) @@ -184877,7 +181400,6 @@ type NewOptions = { tempo: number?, -- BPM (default 125) } --- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format function MusicOps.new(opts: NewOptions?): (any, Err.Err?) local o: NewOptions = opts or {} local format = o.format or "mod" @@ -184906,9 +181428,6 @@ function MusicOps.new(opts: NewOptions?): (any, Err.Err?) return m, nil end --- ------------------------------------------------------------------------------------------------ patterns --- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). --- The pattern is appended to the order list unless opts.order == false. function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?) if not isModule(m) then return bad("addPattern: needs a tracker Module") @@ -184928,8 +181447,6 @@ end local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } --- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, --- "Db4" = 50, "off", "cut", "fade" function MusicOps.note(v: any): (number?, Err.Err?) if type(v) == "number" then if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then @@ -184981,7 +181498,6 @@ local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Er return p, nil end --- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?) local p, err = patternAt(m, pattern, row, channel) if not p then @@ -185008,7 +181524,6 @@ function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, return true, nil end --- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?) local p, err = patternAt(m, pattern, row, channel) if not p then @@ -185018,7 +181533,6 @@ function MusicOps.getCell(m: any, pattern: number, row: number, channel: number) return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil end --- ------------------------------------------------------------------------------------------------ samples type SampleSpec = { name: string?, audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate @@ -185036,9 +181550,8 @@ type SampleSpec = { local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 } --- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for --- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, --- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). +-- tuning: c5speed for S3M / IT; relativeNote + finetune (1/128 semitone from 8363 Hz) for MOD / XM (MOD stores +-- only the finetune, -1..+7/8 semitone) function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) if not isModule(m) then return bad("addSample: needs a tracker Module") @@ -185116,7 +181629,6 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) return #m.samples, nil end --- ------------------------------------------------------------------------------------------------ instruments type InstrumentSpec = { name: string?, sample: number?, -- the sample every note plays (1-based) @@ -185126,8 +181638,7 @@ type InstrumentSpec = { -- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes } --- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / --- S3M cells name samples directly). +-- instruments: XM and IT only (MOD / S3M cells name samples directly) function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?) if not isModule(m) then return bad("addInstrument: needs a tracker Module") @@ -185203,18 +181714,9 @@ return MusicOps end __FILES["playlist/m3u"] = function() --- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no --- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain --- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / --- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media --- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, --- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base --- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, --- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. --- --- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) --- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" --- local out = M3u.encode(pl, { title = "My Mix" }) +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists, absorbed from playlist-luau 3fc7fd3 (same author). Supports: +-- #EXTM3U / #EXTINF / #PLAYLIST, plain lists, BOM, CRLF / CR, Windows-1252, HLS master and media playlists; locations +-- resolve per RFC 3986; mp3 HLS segments are playable, .ts / .aac / fMP4 are flagged. Not supported: writing HLS tags. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -185238,13 +181740,12 @@ local M3u = { type Entry = { url: string, title: string?, - duration: number?, -- seconds; nil when unknown (-1 in the file) - playable: boolean, -- an http(s) URL the player can fetch - reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... - -- HLS - bandwidth: number?, -- master: BANDWIDTH - codecs: string?, -- master: CODECS - attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE } @@ -185252,10 +181753,10 @@ type Hls = { master: boolean, targetDuration: number?, mediaSequence: number?, - endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + endList: boolean, -- EXT-X-ENDLIST (false = live) encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE - totalDuration: number?, -- media: sum of the segment durations - segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" + totalDuration: number?, + segmentFormat: string?, } type Result = { @@ -185264,13 +181765,13 @@ type Result = { meta: { [string]: any }, entries: { Entry }, warnings: { string }, - title: string?, -- #PLAYLIST: / PLS has none + title: string?, -- #PLAYLIST: hls: Hls?, } type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } type EncodeOptions = { title: string?, -- #PLAYLIST: (default: the playlist's title) @@ -185279,7 +181780,6 @@ type EncodeOptions = { -- ------------------------------------------------------------------------------------------------ constants local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } --- The extension of a URL's path (lower case), or nil local function extension(url: string): string? local p = Url.split(url).path local ext = string.match(p, "%.([%w]+)$") @@ -185505,7 +182005,6 @@ local function parseHls(ls: { string }, base: string?, baseScheme: string?, warn return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -185530,8 +182029,6 @@ function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Er end -- ------------------------------------------------------------------------------------------------ encode --- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:,). Durations are rounded; unknown = -1. --- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. local function serialize(entries: { any }, opts: { title: string? }?): string local out = { "#EXTM3U" } local function clean(s: string): string @@ -185554,8 +182051,6 @@ local function serialize(entries: { any }, opts: { title: string? }?): string return table.concat(out, "\n") .. "\n" end --- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of --- entries ({ url, title?, duration? }) function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -185572,14 +182067,9 @@ return M3u end __FILES["playlist/pls"] = function() --- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case --- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a --- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / --- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. --- --- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) --- local out = Pls.encode(pl) +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version), absorbed from +-- playlist-luau 3fc7fd3 (same author) plus a new writer. Supports: keys in any case / order, comments, BOM, CRLF / CR, +-- Windows-1252, numbering gaps; locations resolve per RFC 3986. Encode: Version=2, Length -1 for unknown durations. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -185603,13 +182093,12 @@ local Pls = { type Entry = { url: string, title: string?, - duration: number?, -- seconds; nil when unknown (-1 in the file) - playable: boolean, -- an http(s) URL the player can fetch - reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... - -- HLS - bandwidth: number?, -- master: BANDWIDTH - codecs: string?, -- master: CODECS - attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE } @@ -185617,10 +182106,10 @@ type Hls = { master: boolean, targetDuration: number?, mediaSequence: number?, - endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + endList: boolean, -- EXT-X-ENDLIST (false = live) encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE - totalDuration: number?, -- media: sum of the segment durations - segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" + totalDuration: number?, + segmentFormat: string?, } type Result = { @@ -185629,13 +182118,13 @@ type Result = { meta: { [string]: any }, entries: { Entry }, warnings: { string }, - title: string?, -- #PLAYLIST: / PLS has none + title: string?, -- #PLAYLIST: hls: Hls?, } type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } -- ------------------------------------------------------------------------------------------------ constants @@ -185702,7 +182191,6 @@ local function parsePls(ls: { string }, base: string?, baseScheme: string?, warn return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -185726,8 +182214,6 @@ function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Er end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a --- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -185759,17 +182245,9 @@ return Pls end __FILES["playlist/xspf"] = function() --- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau --- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, --- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, --- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; --- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other --- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- playlist/xspf: XSPF 1 (https://xspf.org/spec) playlists on codecs/text/Xml. Supports: playlist and track metadata, +-- every track location (entry.locations), duration (ms), xml:base then opts.baseUrl (RFC 3986). -- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. --- --- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) --- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end --- local out = Xspf.encode(pl) -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -185790,8 +182268,8 @@ local Xspf = { -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } -- ------------------------------------------------------------------------------------------------ constants @@ -185803,7 +182281,6 @@ local function trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end --- the text of the first child element with this local name, trimmed (nil when missing or empty) local function field(node: any, name: string): string? for _, c in node.children do if type(c) == "table" and Xml.localName(c.name) == name then @@ -185835,8 +182312,6 @@ function Xspf.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd --- tracks become warnings) function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -185921,8 +182396,6 @@ function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, E end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list --- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -185975,16 +182448,9 @@ return Xspf end __FILES["subtitle/ass"] = function() --- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of --- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] --- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the --- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any --- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. --- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become --- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. --- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, --- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: --- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. +-- subtitle/ass: ASS (v4.00+) / SSA (v4.00) scripts (de-facto spec of Aegisub / libass / ffmpeg). Supports: Script +-- Info, Styles, Events (Dialogue / Comment), other sections verbatim, H:MM:SS.cc; {\i1} {\b1} {\u1} {\s1} as the shared +-- markup (cue.raw keeps the original). Not supported: rendering, karaoke timing (\k), embedded font / graphic decoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186003,10 +182469,10 @@ local Ass = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } type EncodeOptions = { - crlf: boolean?, -- CRLF line ends (default false) + crlf: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -186039,7 +182505,6 @@ local STYLE_DEFAULT: { [string]: string } = { Encoding = "0", } local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } --- event fields -> cue keys (the rest keep their field name) local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } local function trim(s: string): string @@ -186054,7 +182519,6 @@ local function fields(s: string): { string } return out end --- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil local function time(s: string): number? local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") if not h then @@ -186064,7 +182528,6 @@ local function time(s: string): number? return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr end --- ASS text -> the shared markup local TAGS = { i = "i", b = "b", u = "u", s = "s" } function Ass.toMarkup(raw: string): string local open: { [string]: boolean } = {} @@ -186105,7 +182568,6 @@ function Ass.toMarkup(raw: string): string return out end --- the shared markup -> ASS text function Ass.fromMarkup(text: string): string local s = string.gsub(text, "\r\n?", "\n") s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string @@ -186168,7 +182630,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end if section == "script info" then if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then - table.insert(infoOrder, line) -- a comment line, kept in place + table.insert(infoOrder, line) -- `;` / `!` comment line, kept in place else local k, v = string.match(line, "^([^:]+):%s?(.*)$") if k then @@ -186241,7 +182703,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end if ok then if k == "Comment" then - cue.after = #subs.cues -- written back after that many dialogue lines + cue.after = #subs.cues table.insert(comments, cue) else table.insert(subs.cues, cue :: any) @@ -186262,7 +182724,6 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E subs.meta.comments = comments end if #sections > 0 then - -- drop trailing blank lines (the writer adds its own) for _, sec in sections do while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do table.remove(sec.lines) @@ -186312,7 +182773,6 @@ function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. end table.sort(rest) table.move(rest, 1, #rest, #out + 1, out) - -- styles local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT table.insert(out, "") @@ -186350,7 +182810,6 @@ function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. end table.insert(out, "Style: " .. table.concat(vals, ",")) end - -- events local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT if efmt[#efmt] ~= "Text" then return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") @@ -186433,13 +182892,9 @@ return Ass end __FILES["subtitle/srt"] = function() --- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or --- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing --- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends --- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / --- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. --- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. --- Not supported: positioning beyond keeping the coordinates; the tags are not validated. +-- subtitle/srt: SubRip text (de-facto; matches ffmpeg's srt demuxer / muxer). Supports: numbered or unnumbered +-- cues, `,` / `.` decimals, X1/Y1 coordinates (cue.settings), inner blank lines, BOM, CRLF / CR; text kept as is. +-- Not supported: positioning beyond keeping the coordinates; tags are not validated. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186458,16 +182913,15 @@ local Srt = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } type EncodeOptions = { - crlf: boolean?, -- CRLF line ends (default false: LF) + crlf: boolean?, -- default false (LF) } -- ------------------------------------------------------------------------------------------------ constants local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" --- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) local function text(r: Bytes.Reader): string? local s = buffer.readstring(r.buf, r.base, r.limit - r.base) if string.find(s, "\0", 1, true) then @@ -186483,7 +182937,6 @@ local function frac(digits: string): number return (tonumber(digits) :: number) / 10 ^ #digits end --- timing(line) -> start, stop, settings | nil local function timing(line: string): (number?, number?, string?) local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) if not h1 then @@ -186522,7 +182975,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E local n = #lines local subs = Types.Subtitles.new() local i = 1 - local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing) + local function isStart(k: number): boolean local l = lines[k] if l == nil then return false @@ -186546,7 +182999,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E while i <= n do local l = lines[i] if string.match(l, "^%s*$") then - -- blank: the end of the cue unless more text follows before the next cue + -- a blank line ends the cue only before the next index / timing line local k = i while k <= n and string.match(lines[k], "^%s*$") do k += 1 @@ -186559,7 +183012,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end i = k elseif timing(l) then - break -- a cue without the blank separator + break else table.insert(body, l) i += 1 @@ -186601,7 +183054,6 @@ function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") end - -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue local body = string.gsub(c.text, "\r\n?", "\n") local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl @@ -186613,12 +183065,9 @@ return Srt end __FILES["subtitle/vtt"] = function() --- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in --- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments --- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept --- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). --- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text --- are dropped and `-->` escaped (WebVTT cue text cannot hold them). +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the header (meta.header), cue ids, `[hh:]mm:ss.ttt` timings, +-- cue settings, NOTE (meta.notes), STYLE (meta.css) and REGION (meta.regions) blocks, BOM, CRLF / CR; cue text as +-- written. Encode drops blank lines in cue text and escapes `-->` (cue text cannot hold them). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186637,7 +183086,7 @@ local Vtt = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } type EncodeOptions = {} @@ -186646,7 +183095,6 @@ local function frac(digits: string): number return (tonumber(digits) :: number) / 10 ^ #digits end --- one timestamp at the start of s: seconds, the rest | nil local function timestamp(s: string): (number?, string) local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") if h then @@ -186659,7 +183107,6 @@ local function timestamp(s: string): (number?, string) return nil, s end --- timing(line) -> start, stop, settings | nil local function timing(line: string): (number?, number?, string?) local a, rest = timestamp((string.gsub(line, "^%s+", ""))) if not a then @@ -186724,7 +183171,6 @@ function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E i += 1 continue end - -- a block: lines up to the next blank local first = i while i <= n and lines[i] ~= "" do i += 1 @@ -186774,7 +183220,6 @@ local function stamp(t: number): string return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) end --- one block's text: no blank lines (they end a block), no `-->` local function clean(s: string): string s = string.gsub(s, "\r\n?", "\n") s = string.gsub(s, "\n[ \t]*\n", "\n") @@ -186823,17 +183268,9 @@ return Vtt end __FILES["vector/svg"] = function() --- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs --- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg --- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from --- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / --- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and --- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path --- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). --- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and --- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. --- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also --- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. +-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms, +-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported +-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186856,7 +183293,7 @@ local Svg = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } type EncodeOptions = {} type RasterizeOptions = Render.Options @@ -186901,8 +183338,6 @@ function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox --- maps onto w x h by its preserveAspectRatio. function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) if type(v) ~= "table" or type(v.paths) ~= "table" then return nil, Err.new(Err.ARG, "needs a Vector value") @@ -186919,13 +183354,7 @@ return Svg end __FILES["vector/svg/Parse"] = function() --- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, --- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space --- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into --- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a --- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. --- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. --- Never throws. +-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips. local Xml = __include("codecs/text/Xml") local Types = __include("Types") local Style = __include("vector/svg/Style") @@ -186979,7 +183408,7 @@ type Ctx = { groups: { any }, clips: { any }, unsupported: { [string]: number }, - vw: number, -- the current viewport (for percentages) + vw: number, vh: number, depth: number, useDepth: number, @@ -187010,7 +183439,7 @@ local function refId(s: string?): string? return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") end --- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +-- cascade: presentation attributes < CSS rules (by specificity, then order) < style="" local function specified(n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k, v in pairs(n.attrs :: any) do @@ -187050,7 +183479,6 @@ local function specified(n: Node, ctx: Ctx): { [string]: string } return out end --- computed(parent, n) -> the element's computed property strings local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k in pairs(INHERITED) do @@ -187108,7 +183536,6 @@ local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } return list end --- a gradient attribute, looked up through href templates local function gattr(g: Node, k: string, ctx: Ctx): string? local cur: Node? = g local guard = 0 @@ -187170,7 +183597,6 @@ local function gradient(g: Node, opacity: number, ctx: Ctx): any return p end --- paint(value, opacity, st) -> Paint | nil (none) local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any if value == nil then return nil @@ -187290,7 +183716,6 @@ local function transformOf(n: Node): M return IDENTITY end --- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? local cp = ctx.ids[ref] if cp == nil or local_(cp) ~= "clipPath" then @@ -187428,7 +183853,6 @@ local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: numbe table.insert(ctx.vector.paths, p) end --- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M if vb == nil or vb[3] <= 0 or vb[4] <= 0 then return { 1, 0, 0, 1, x, y } @@ -187473,7 +183897,6 @@ local function viewBox(n: Node): { number }? end local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) - -- a layer for opacity / clip-path local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) local clipRef = refId(st["clip-path"]) local g = group @@ -187483,7 +183906,6 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe local bbox: { number }? = nil local cp = ctx.ids[clipRef] if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then - -- the group's bounding box in its user space: walk once into a scratch vector local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips local scratch = Types.Vector.new(0, 0) ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} @@ -187530,7 +183952,7 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe end end --- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +-- nested svg / symbol: overflow is hidden unless it says otherwise local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? local ov = attr(n, "overflow") if ov == "visible" or ov == "auto" then @@ -187618,7 +184040,6 @@ walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: numbe end -- ------------------------------------------------------------------------------------------------ entry --- document(doc, opts) -> Vector | nil, message function Parse.document(doc: any): (Types.Vector?, string?) local root = doc.root if root == nil or Xml.localName(root.name) ~= "svg" then @@ -187679,11 +184100,8 @@ return Parse end __FILES["vector/svg/PathData"] = function() --- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands --- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the --- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a --- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the --- commands so far are kept, as the spec's error handling says). +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes +-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says). local PathData = {} type Cmd = { op: string, [number]: number } @@ -187693,7 +184111,6 @@ local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } --- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) if x1 == x2 and y1 == y2 then return @@ -187761,14 +184178,13 @@ local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: numbe end PathData.arc = arc --- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) function PathData.parse(d: string): ({ Cmd }, boolean) local out: { Cmd } = {} local i, n = 1, #d - local cx, cy = 0, 0 -- current point - local sx, sy = 0, 0 -- subpath start - local lcx, lcy = 0, 0 -- last control point (for S / T) - local last = "" -- previous command letter (upper case) + local cx, cy = 0, 0 + local sx, sy = 0, 0 + local lcx, lcy = 0, 0 + local last = "" local cmd: string? = nil local rel = false local nums: { number } = table.create(7) :: { number } @@ -187929,15 +184345,12 @@ function PathData.parse(d: string): ({ Cmd }, boolean) return out, true end --- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box --- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge local px, py = 0, 0 for _, c in cmds do local op = c.op if op == "C" then - -- the curve's exact extrema local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] for axis = 1, 2 do local p0 = if axis == 1 then px else py @@ -188008,7 +184421,6 @@ function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) return x0, y0, x1, y1 end --- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) local function num(v: number): string if v ~= v or v == math.huge or v == -math.huge then return "0" @@ -188023,7 +184435,6 @@ local function num(v: number): string end PathData.num = num --- serialize(cmds) -> path data text function PathData.serialize(cmds: { Cmd }): string local out = {} for _, c in cmds do @@ -188040,7 +184451,6 @@ function PathData.serialize(cmds: { Cmd }): string return table.concat(out, " ") end --- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } function PathData.toRaster(cmds: { Cmd }): { any } local out = table.create(#cmds) @@ -188058,11 +184468,7 @@ return PathData end __FILES["vector/svg/Render"] = function() --- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, --- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and --- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, --- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox --- maps onto the image by meta.preserveAspectRatio. Never throws. +-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend. local Types = __include("Types") local Raster = __include("codecs/image/Raster") local Blend = __include("codecs/image/Blend") @@ -188101,7 +184507,6 @@ local function stopColor(stops: { { number } }, t: number): (number, number, num return s[2], s[3], s[4], s[5] end --- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? local stops = p.stops if type(stops) ~= "table" or #stops == 0 then @@ -188187,7 +184592,6 @@ local function gradientFn(p: any, device: M, bbox: { number }?): ((number, numbe end -- ------------------------------------------------------------------------------------------------ dashes --- subpaths of a command list with their closed flag local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } local out = {} local cur: { any }? = nil @@ -188210,7 +184614,6 @@ local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } return out end --- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) local function polyline(cmds: { any }, tol: number): { number } local pts: { number } = {} local px, py = 0, 0 @@ -188328,16 +184731,14 @@ end -- ------------------------------------------------------------------------------------------------ rendering type Options = { - background: { number }?, -- r, g, b, a under the drawing (default transparent) - tolerance: number?, -- curve flattening in device pixels (default 0.1) + background: { number }?, -- r, g, b, a; default transparent + tolerance: number?, -- device pixels; default 0.1 } --- the device transform scale (for stroke flattening tolerances) local function scaleOf(m: M): number return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) end --- rasterize(v, w, h, opts?) -> rgba8 Image function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image local o: Options = opts or {} local img = Types.Image.new(w, h) @@ -188356,7 +184757,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} local tol = o.tolerance or 0.1 local clipCache: { [number]: buffer } = {} - -- a clip's coverage over the whole image (1 byte per pixel) local function clipMask(id: number): buffer? if clipCache[id] then return clipCache[id] @@ -188384,7 +184784,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) clipCache[id] = mask return mask end - -- the layer stack: { group id, image } local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } local function chain(g: number?): { number } local out = {} @@ -188424,7 +184823,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) if type(p) ~= "table" or type(p.d) ~= "table" then continue end - -- groups: pop the layers this path is not in, push the ones it needs local want = chain(p.group) local keep = 1 while keep < #stack and stack[keep + 1].id == want[keep] do @@ -188487,11 +184885,7 @@ return Render end __FILES["vector/svg/Style"] = function() --- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / --- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), --- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated --- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). --- Never throws. +-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset. local Raster = __include("codecs/image/Raster") local Style = {} @@ -188545,7 +184939,6 @@ local function hue(p: number, q: number, t: number): number return p end --- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value function Style.color(s: string, current: { number }?): any s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) if s == "none" then @@ -188624,7 +185017,7 @@ function Style.color(s: string, current: { number }?): any return nil end --- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +-- SVG number: sign? digits? ("." digits)? exponent? local function scan(s: string, i: number): (number?, number) local n = #s local st = i @@ -188682,7 +185075,6 @@ local function scan(s: string, i: number): (number?, number) return tonumber(string.sub(s, st, i - 1)), i end --- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } function Style.length(s: string?, ref: number?, fontSize: number?): number? if s == nil then @@ -188707,7 +185099,6 @@ function Style.length(s: string?, ref: number?, fontSize: number?): number? return if k then x * k else nil end --- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else function Style.numbers(s: string?): { number } local out = {} if s == nil then @@ -188730,7 +185121,6 @@ function Style.numbers(s: string?): { number } return out end --- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error local mul = Raster.multiply Style.multiply = mul function Style.transform(s: string): { number }? @@ -188773,7 +185163,6 @@ function Style.transform(s: string): { number }? return m end --- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) function Style.declarations(s: string): { [string]: string } local out: { [string]: string } = {} for decl in string.gmatch(s, "[^;]+") do @@ -188821,7 +185210,6 @@ local function selector(s: string): Selector? return sel end --- css(text, rules?) -> rules (appended to the list given) function Style.css(text: string, rules: { Rule }?): { Rule } local out: { Rule } = rules or {} text = string.gsub(text, "/%*.-%*/", "") @@ -188850,7 +185238,6 @@ function Style.css(text: string, rules: { Rule }?): { Rule } return out end --- matches(sel, tag, id, classes) -> boolean function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean if sel.tag and sel.tag ~= tag then return false @@ -188870,9 +185257,7 @@ return Style end __FILES["vector/svg/Write"] = function() --- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients --- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> --- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message). local Xml = __include("codecs/text/Xml") local Types = __include("Types") local PathData = __include("vector/svg/PathData") @@ -188912,7 +185297,6 @@ local function matrix(m: any): string? return "matrix(" .. table.concat(parts, " ") .. ")" end --- write(v) -> SVG text | nil, message function Write.vector(v: Types.Vector): (string?, string?) if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then return nil, "needs a Vector value" @@ -188922,7 +185306,6 @@ function Write.vector(v: Types.Vector): (string?, string?) local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} local defs = {} local gradients = 0 - -- paints -> attribute values (gradients go to defs) local function paintAttrs(p: any, which: string): { { any } } if type(p) ~= "table" then return { { which, "none" } } @@ -188980,7 +185363,6 @@ function Write.vector(v: Types.Vector): (string?, string?) return "url(#" .. clipIds[id] .. ")" end local root = {} - -- the open <g> stack: { id, children } local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } } local function chain(g: number?): { number } local out = {} @@ -189075,16 +185457,9 @@ return Write end __FILES["vector/tiled"] = function() --- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map --- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / --- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, --- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, --- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets --- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay --- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the --- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". --- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external --- tilesets or images (callers resolve `source` / `imageSource` paths themselves). +-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON +-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties, +-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -189107,14 +185482,14 @@ local Tiled = { } type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 256 MB) + maxBytes: number?, -- default 256 MB } type EncodeOptions = { - format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx + format: string?, -- "tmx" | "tsx" | "tmj" | "tsj" | "json"; default: the source's flavour, else tmx encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64" - compression: string?, -- base64 data: nil | "zlib" | "gzip" - level: number?, -- deflate level for compressed data (default 6) - indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) + compression: string?, -- nil | "zlib" | "gzip" + level: number?, -- default 6 + indent: number?, -- default 1 (TMX), 2 (TMJ); 0 = compact JSON } -- ------------------------------------------------------------------------------------------------ sniff @@ -189148,8 +185523,6 @@ function Tiled.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its --- meta.tileset is true) | nil, Err function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 28 if r.limit - r.base > maxBytes then @@ -189264,14 +185637,12 @@ return Tiled end __FILES["vector/tiled/Data"] = function() --- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) --- to gids and back; property values and their types; number formatting. Never throws. +-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers. local Base64 = __include("core/Base64") local Deflate = __include("codecs/compress/Deflate") local Data = {} --- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message function Data.csv(text: string): ({ number }?, string?) local out = {} for tok in string.gmatch(text, "[^,%s]+") do @@ -189284,7 +185655,6 @@ function Data.csv(text: string): ({ number }?, string?) return out, nil end --- base64(text, compression) -> { gid } | nil, message, unsupported? function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) local raw, err = Base64.decode(text) if not raw then @@ -189314,7 +185684,6 @@ function Data.base64(text: string, compression: string?): ({ number }?, string?, return out, nil, nil end --- toBase64(gids, compression?, level?) -> text | nil, message function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?) local b = buffer.create(#gids * 4) for i, g in gids do @@ -189338,7 +185707,7 @@ function Data.toBase64(gids: { number }, compression: string?, level: number?): return Base64.encode(b), nil end --- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print function Data.num(v: number): string if v % 1 == 0 and math.abs(v) < 2 ^ 53 then return string.format("%.0f", v) @@ -189350,7 +185719,7 @@ function Data.num(v: number): string return s end --- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +-- Tiled's CSV layout: one row per line function Data.csvText(gids: { number }, width: number): string local rows = {} local row = {} @@ -189367,7 +185736,7 @@ function Data.csvText(gids: { number }, width: number): string return "\n" .. table.concat(rows, ",\n") .. "\n" end --- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque function Data.color(s: string?): string? if type(s) ~= "string" then return nil @@ -189379,7 +185748,6 @@ function Data.color(s: string?): string? return "#" .. h end --- property values: TMX / TMJ type names -> a Luau value from text function Data.value(typ: string, text: string): any if typ == "int" or typ == "float" or typ == "object" then return tonumber(text) or 0 @@ -189391,7 +185759,6 @@ function Data.value(typ: string, text: string): any return text end --- typeOf(v, declared?) -> the Tiled type to write for v function Data.typeOf(v: any, declared: string?): string if declared then return declared @@ -189406,7 +185773,6 @@ function Data.typeOf(v: any, declared: string?): string return "string" end --- sortedKeys(t) -> its string keys, sorted function Data.sortedKeys(t: { [any]: any }): { string } local out = {} for k in pairs(t) do @@ -189422,8 +185788,7 @@ return Data end __FILES["vector/tiled/Tmj"] = function() --- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ --- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap. local Types = __include("Types") local Data = __include("vector/tiled/Data") @@ -189668,7 +186033,6 @@ layer = function(v: any, depth: number): (any, string?, boolean?) return nil, "unknown layer type " .. tostring(v.type) end --- tileset(v) -> Tileset (a map's entry, or a .tsj root) function Tmj.tileset(v: any): any local ts: any = { firstGid = n(v.firstgid, 1), @@ -189720,7 +186084,6 @@ function Tmj.tileset(v: any): any return ts end --- read(value) -> TileMap | nil, message, unsupported? function Tmj.read(v: any): (any, string?, boolean?) if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then return nil, "not a Tiled map (type is not \"map\")" @@ -189958,7 +186321,6 @@ writeLayer = function(l: any, o: WriteOptions): (any, string?) return obj(fields), nil end --- tilesetValue(ts, inMap) -> a JSON object function Tmj.tilesetValue(ts: any, inMap: boolean): any if inMap and type(ts.source) == "string" then return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -190013,7 +186375,6 @@ function Tmj.tilesetValue(ts: any, inMap: boolean): any }) end --- write(map, opts) -> a JSON value | nil, message function Tmj.write(map: any, o: WriteOptions): (any, string?) local layers = {} for _, l in map.layers do @@ -190058,8 +186419,7 @@ return Tmj end __FILES["vector/tiled/Tmx"] = function() --- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. --- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap. local Xml = __include("codecs/text/Xml") local Types = __include("Types") local Data = __include("vector/tiled/Data") @@ -190087,7 +186447,6 @@ local function flag(n: Node, k: string, default: boolean): boolean end -- ------------------------------------------------------------------------------------------------ read --- <properties> -> values, types (types only for the non-string ones) local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) local props: { [string]: any } = {} local types: { [string]: string }? = nil @@ -190127,7 +186486,6 @@ local function withProps(t: any, n: Node) end end --- the gids of a <data> (or <chunk>) node local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) if encoding == "csv" then return Data.csv(Xml.text(d)) @@ -190292,7 +186650,6 @@ layer = function(n: Node): (any, string?, boolean?) return nil end --- a <tileset> element (in a map, or a .tsx root) -> Tileset function Tmx.tileset(n: Node): any local ts: any = { firstGid = num(n, "firstgid", 1), @@ -190346,7 +186703,6 @@ function Tmx.tileset(n: Node): any return ts end --- read(root) -> TileMap | nil, message, unsupported? function Tmx.read(root: Node): (any, string?, boolean?) if root.name ~= "map" then return nil, "the root element is <" .. root.name .. ">, not <map>" @@ -190389,7 +186745,6 @@ end type Attrs = { [string]: string } local function el(name: string, attrs: { { any } }, children: { any }?): Node - -- attrs in order; nil / default values dropped by the caller local o = Types.object() for _, kv in attrs do if kv[2] ~= nil then @@ -190592,7 +186947,6 @@ writeLayer = function(l: any, o: WriteOptions): (Node?, string?) return nil, "unknown layer type " .. tostring(t) end --- tilesetNode(ts, inMap) -> <tileset> function Tmx.tilesetNode(ts: any, inMap: boolean): Node if inMap and type(ts.source) == "string" then return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -190637,7 +186991,6 @@ function Tmx.tilesetNode(ts: any, inMap: boolean): Node }, kids) end --- write(map, opts) -> an XML document node | nil, message function Tmx.write(map: any, o: WriteOptions): (Node?, string?) local kids = {} addProps(kids, map) @@ -190678,15 +187031,9 @@ return Tmx end __FILES["video/avi"] = function() --- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. --- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, --- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is --- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, --- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. --- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's --- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. --- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -190709,18 +187056,18 @@ local AviFormat = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) - track: number?, -- the video track (stream index + 1) to decode - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p; BI_RGB gives rgba8 + track: number?, -- stream index + 1 + audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api } type EncodeOptions = { - quality: number?, -- MJPEG quality 1..100 (default 90) - reencode: boolean?, -- encode the frames even when the source is MJPEG - audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + quality: number?, -- 1..100, default 90 + reencode: boolean?, + audio: boolean?, -- default: PCM s16 from the source's audio video: boolean?, - maxFps: number?, -- the highest frame rate variable delays may need (default 100) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -190849,7 +187196,6 @@ local function audioTrack(s: Avi.Stream, id: number): Types.Track return t end --- demux(r, opts?) -> the Demuxer | nil, Err function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) if not ok then @@ -190876,7 +187222,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } local dmx = Demux.new("avi", tracks, r.buf, meta) - -- packets in file order across streams: merge by offset local items: { { number } } = {} for k, st in streams do local s: Avi.Stream, t: any = st[1], st[2] @@ -190906,7 +187251,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -190957,7 +187301,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks in time order (the video packets already repeated to the constant rate) local chunks: { { any } } = {} for _, item in Source.interleave(streams) do table.insert(chunks, { item[1], item[2].data, true }) @@ -190970,7 +187313,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = AviFormat.demux(r, opts) if not dmx then @@ -190983,14 +187325,9 @@ return AviFormat end __FILES["video/fli"] = function() --- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC --- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). --- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: --- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, --- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 --- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the --- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. --- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -191011,9 +187348,9 @@ local Fli = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) } -- ------------------------------------------------------------------------------------------------ constants @@ -191040,7 +187377,6 @@ function Fli.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer | nil, Err function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit local n = limit - base @@ -191092,7 +187428,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) default = true, bitsPerPixel = depth, } - -- the frame chunks local offs, sizes = {}, {} local p = base + HEADER while p + 6 <= limit do @@ -191103,7 +187438,7 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end if (cm == FRAME or cm == FRAME2) and size > 6 then if p + size > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, size) @@ -191129,7 +187464,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Fli.demux(r, opts) if not dmx then @@ -191142,22 +187476,9 @@ return Fli end __FILES["video/flv"] = function() --- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's --- FourCC video tags). New in rosetta. --- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... --- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by --- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 --- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks --- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets --- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), --- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through --- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. --- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / --- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at --- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data --- rates, codec ids, file size). --- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx --- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -191184,17 +187505,17 @@ local Flv = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id (1 video, 2 audio) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more tags (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- 1 video, 2 audio + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } type EncodeOptions = { - video: boolean?, -- false: no video - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped) - reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, } -- ------------------------------------------------------------------------------------------------ constants @@ -191261,7 +187582,6 @@ local function copy(b: buffer, p: number, n: number): buffer return c end --- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) if codec == "flv1" then local h = H263.header(b, p, n, true) @@ -191295,7 +187615,6 @@ local function frameSize(codec: string, b: buffer, p: number, n: number): (numbe return nil, nil end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local o: OpenOptions = opts or {} local b, base, limit = r.buf, r.base, r.limit @@ -191312,7 +187631,7 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local tracks: { Types.Track } = {} local dmx = Demux.new("flv", tracks, b, meta) local vt: any, at: any = nil, nil - local keyOff, keyLen = -1, 0 -- the first video keyframe + local keyOff, keyLen = -1, 0 local maxPackets = o.maxPackets or 2 ^ 24 local count = 0 local p = base + dataOffset + 4 -- after PreviousTagSize0 @@ -191459,7 +187778,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end p = d + size + 4 end - -- the track facts onMetaData and the codec headers give local md: { [string]: any } = meta.metadata or {} if type(md.duration) == "number" and md.duration > 0 then meta.duration = md.duration @@ -191481,7 +187799,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) if type(fr) == "number" and fr > 0 and fr < 1000 then vt.frameRate = fr else - -- from the timestamps: the frames over the time they span local n = dmx:count(vt.id) local t0 = if n > 0 then dmx:info(vt.id, 1) else nil local t1 = if n > 1 then dmx:info(vt.id, n) else nil @@ -191498,7 +187815,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { @@ -191508,7 +187824,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not streams then return nil, err end - -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true for i = #streams, 1, -1 do local s = streams[i] local why = s.kind == "audio" and Mux.audioProblem(s) @@ -191530,7 +187845,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Flv.demux, r, opts) if not ok then @@ -191546,13 +187860,8 @@ return Flv end __FILES["video/flv/Amf"] = function() --- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 --- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference --- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the --- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. --- --- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } --- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. local Bytes = __include("core/Bytes") local Amf = {} @@ -191637,13 +187946,11 @@ readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any return nil end --- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) function Amf.value(r: Bytes.Reader): any local ok, v = pcall(readValue, r, 0, {}) return if ok and not r.err then v else nil end --- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil function Amf.script(r: Bytes.Reader): (string?, any) local name = Amf.value(r) if type(name) ~= "string" then @@ -191664,7 +187971,6 @@ local function writeString(w: Bytes.Writer, s: string) w:string(s) end --- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null function Amf.writeValue(w: Bytes.Writer, v: any) local t = type(v) if t == "number" then @@ -191686,8 +187992,6 @@ function Amf.writeValue(w: Bytes.Writer, v: any) end end --- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as --- { key, { pairs = { ... } } } becomes an object) function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) if object then w:u8(3) @@ -191714,12 +188018,8 @@ return Amf end __FILES["video/flv/Mux"] = function() --- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag --- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 --- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source --- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), --- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made --- from the first ADTS header. Interpreted; never throws (returns nil, Err). +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Amf = __include("video/flv/Amf") @@ -191745,7 +188045,6 @@ local function isAdts(s: any): boolean return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 end --- audioProblem(stream) -> why FLV cannot hold this audio stream | nil function Mux.audioProblem(s: any): string? local fmt = AUDIO_FORMATS[s.codec] if not fmt then @@ -191839,7 +188138,6 @@ local function f64At(b: buffer, at: number, v: number) end end --- mux(streams) -> buffer | nil, Err function Mux.mux(streams: { any }): (buffer?, Err.Err?) local video, audio = nil :: any, nil :: any for _, s in streams do @@ -191882,7 +188180,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) end end end - -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative local shift = 0 local duration = 0 local vBytes, aBytes = 0, 0 @@ -191926,7 +188223,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) w:u32be(11 + n) end - -- onMetaData local props: { { any } } = { { "duration", duration } } if video then table.insert(props, { "width", video.width or 0 }) @@ -191953,7 +188249,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) tag(18, 0, {}, metaBody) local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker - -- sequence headers local vid = if video then VIDEO_IDS[video.codec] else 0 if video and video.codec == "h264" then tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) @@ -192004,14 +188299,9 @@ return Mux end __FILES["video/h264"] = function() --- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg --- `-f h264` output, the JVT conformance bitstreams). New in rosetta. --- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw --- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). --- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, --- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -192034,10 +188324,10 @@ local Format = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^22 luma samples + frameRate: number?, -- default 25 + deblock: boolean?, -- false: faster, not conformant } -- ------------------------------------------------------------------------------------------------ sniff @@ -192070,7 +188360,6 @@ function Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local units = H264.accessUnits(buf, base, limit - base) @@ -192111,7 +188400,6 @@ function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) if not streams then @@ -192138,7 +188426,6 @@ function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Format.demux(r, opts) if not dmx then @@ -192151,18 +188438,9 @@ return Format end __FILES["video/mkv"] = function() --- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in --- rosetta, on containers/Ebml. --- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio --- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text --- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. --- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied --- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from --- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, --- track.unsupported says why), chapters / attachments (skipped), writing subtitles. +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -192185,22 +188463,22 @@ local Mkv = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track number to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more packets (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } type EncodeOptions = { - format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska - webm: boolean?, -- the same as format = "webm" - quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) - reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) - video: boolean?, -- false: no video stream - audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + format: string?, -- "webm": DocType webm, WebM codecs only; else Matroska + webm: boolean?, -- as format = "webm" + quality: number?, -- 1..100, default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail if the audio cannot be written (default: dropped) title: string?, - clusterSeconds: number?, -- target cluster length (default 2) + clusterSeconds: number?, -- seconds, default 2 } -- ------------------------------------------------------------------------------------------------ constants @@ -192219,7 +188497,6 @@ function Mkv.sniff(r: Bytes.Reader): number return 0.5 end --- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r: Bytes.Reader): string? local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then @@ -192229,8 +188506,6 @@ function Mkv.variant(r: Bytes.Reader): string? end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) --- or a Demuxer function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") @@ -192273,7 +188548,6 @@ function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) if not ok then @@ -192282,7 +188556,6 @@ function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, err end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mkv.demux(r, opts) if not dmx then @@ -192292,7 +188565,6 @@ function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er end -- ------------------------------------------------------------------------------------------------ extras --- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? local track = nil for _, t in dmx.tracks do @@ -192322,11 +188594,8 @@ return Mkv end __FILES["video/mkv/Mux"] = function() --- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), --- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of --- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative --- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). local Err = __include("core/Err") local Ebml = __include("containers/Ebml") local Video = __include("codecs/video/Video") @@ -192359,7 +188628,6 @@ local AUDIO_IDS: { [string]: string } = { } Mux.AUDIO_IDS = AUDIO_IDS --- codecId(stream) -> the Matroska CodecID | nil function Mux.codecId(kind: string, codec: string): string? if kind == "video" then local e = Video.entry(codec) @@ -192387,12 +188655,10 @@ type Options = { clusterSeconds: number?, -- default 2 } --- mux(streams, opts) -> buffer | nil, Err function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) local webm = opts.webm == true local app = opts.app or "rosetta" local clusterSpan = opts.clusterSeconds or 2 - -- tracks local ids: { string } = {} local videoIndex = 0 for i, s in streams do @@ -192473,7 +188739,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) end body:close(tracks) - -- clusters local cues: { { number } } = {} -- { time ms, track, cluster offset in body } local cl: number? = nil local clTime = 0 @@ -192587,7 +188852,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) bodyBuf = nb end - -- the file local out = Ebml.writer(buffer.len(bodyBuf) + 256) local eb = out:open(ID.EBML) out:uint(0x4286, 1) @@ -192609,11 +188873,8 @@ return Mux end __FILES["video/mkv/Parse"] = function() --- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles --- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, --- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, --- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by --- default). Interpreted (it only walks headers); never throws. +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. local Err = __include("core/Err") local Types = __include("Types") local Ebml = __include("containers/Ebml") @@ -192748,7 +189009,6 @@ local SUBS: { [string]: string } = { ["S_HDMV/PGS"] = "pgs", } --- codecFor(CodecID, bitDepth) -> our codec id local function codecFor(id: string, kind: string, bits: number?): string if kind == "video" then return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) @@ -192829,8 +189089,7 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any) end end --- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption --- are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? for id, o, n in Ebml.children(buf, off, off + len) do if id == ID.ContentEncoding then @@ -193028,7 +189287,7 @@ type Ctx = { maxPackets: number, } --- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +-- Block / SimpleBlock: track, relative timecode, flags, lacing local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) local buf = ctx.buf local limit = off + len @@ -193153,7 +189412,6 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si end end --- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number local buf = ctx.buf local pos = off @@ -193201,9 +189459,6 @@ end type Options = { maxPackets: number? } --- parse(buf, base, limit, opts) -> a Demux | nil, Err --- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data --- offset | nil, Err function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) local id, size, data = Ebml.header(buf, base, limit) if id ~= ID.EBML or not size or not data then @@ -193230,7 +189485,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) end local pos = data + size - -- the Segment (skip anything else at the top level) local segData, segEnd = -1, limit while pos < limit do local sid, ssize, sdata = Ebml.header(buf, pos, limit) @@ -193273,7 +189527,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) elseif cid == ID.Cluster then if unknown then - -- find its end: walk children until a top-level ID local p = cdata while p < segEnd do local xid, xsize, xdata = Ebml.header(buf, p, segEnd) @@ -193341,20 +189594,9 @@ return Parse end __FILES["video/mp4"] = function() --- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on --- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. --- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first --- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG --- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through --- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / --- 'lpcm' / 'ipcm'). --- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied --- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v --- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV --- only; MP4 drops other audio unless opts.audio = true, which fails). --- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented --- writing, timed text tracks, encrypted tracks. +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -193378,18 +189620,18 @@ local Mp4 = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { rgba: boolean?, - track: number?, -- the video track id (default: the first video track) + track: number?, -- default: the first video track audio: boolean?, maxPixels: number?, maxSamples: number?, openAudio: any?, -- set by the api } type EncodeOptions = { - format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') - quality: number?, -- MJPEG quality when frames are encoded (default 90) - reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + format: string?, -- "mov": QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- default 90 + reencode: boolean?, video: boolean?, - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written + audio: boolean?, -- true: fail when the audio cannot be written } -- ------------------------------------------------------------------------------------------------ constants @@ -193448,7 +189690,6 @@ local function pcmCodec(t: any): string return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") end --- demux(r, opts?) -> the Demuxer | nil, Err function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) if not ok then @@ -193506,7 +189747,6 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) table.insert(src, it) end local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) - -- samples in file order across tracks local items: { { number } } = {} for k, it in src do -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio @@ -193557,7 +189797,6 @@ local function dOps(head: buffer?): buffer? return w:finish() end --- encode(video, opts?) -> buffer | nil, Err function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -193671,7 +189910,6 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mp4.demux(r, opts) if not dmx then @@ -193684,14 +189922,9 @@ return Mp4 end __FILES["video/mpegps"] = function() --- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / --- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both --- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get --- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). --- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its --- sequence extension), audio through the api's opts.openAudio hook. --- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -193715,7 +189948,7 @@ local Ps = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { rgba: boolean?, - track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + track: number?, -- 0xE0..; default: the first video stream audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -193733,7 +189966,6 @@ function Ps.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) local total = 0 for _, p in s.pes do @@ -193804,7 +190036,6 @@ local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) end end --- demux(r, opts?) -> the Demuxer | nil, Err function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) if r:peek(4) == "\0\0\1\179" then -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps @@ -193866,7 +190097,6 @@ function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ps.demux(r, opts) if not dmx then @@ -193879,15 +190109,9 @@ return Ps end __FILES["video/mpegts"] = function() --- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, --- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS --- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the --- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, --- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / --- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. --- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, --- PES without PTS for video before the first one (dropped). +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -193911,7 +190135,7 @@ local Ts = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { rgba: boolean?, - track: number?, -- the video PID to decode (default: the first video stream of the PMT) + track: number?, -- default: the first video stream of the PMT audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -193932,8 +190156,7 @@ local CODEC: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ sniff --- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart --- (fewer in a short file) within the first 2 KB +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB local function packetSize(r: Bytes.Reader): (number, number) local n = r:remaining() for start = 0, math.min(n, 2048) - 1 do @@ -193992,7 +190215,6 @@ local function mpegAudioCodec(u: any): string return "mp2" end --- demux(r, opts?) -> the Demuxer | nil, Err function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local size, off = packetSize(r) if size == 0 then @@ -194044,7 +190266,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) for _, u in units do track(u.pid, u.kind, u.codec, u.streamType, nil) end - -- codec details from the first unit local seen: { [number]: boolean } = {} for _, u in units do local t = byPid[u.pid] @@ -194114,7 +190335,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ts.demux(r, opts) if not dmx then @@ -194127,17 +190347,9 @@ return Ts end __FILES["video/ogv"] = function() --- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, --- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. --- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from --- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, --- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / --- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's --- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. --- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied --- (the audio pages come from containers/AudioWrap and are interleaved by time). --- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), --- encoding Theora (there is no encoder: other sources cannot be written). +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194162,23 +190374,22 @@ local Ogv = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, maxPixels: number?, - verify: boolean?, -- false: skip the page CRC checks (default true) + verify: boolean?, -- default true openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } type EncodeOptions = { - audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) + audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped) } -- ------------------------------------------------------------------------------------------------ constants local AUDIO = { vorbis = true, opus = true, flac = true } -- ------------------------------------------------------------------------------------------------ sniff --- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain --- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) function Ogv.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -194206,7 +190417,6 @@ function Ogv.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ encode --- the pages of an Ogg buffer: { offset, size, serial, granule, bos } local function pages(b: buffer): { { number } } local out = {} local pos = 0 @@ -194221,7 +190431,6 @@ local function pages(b: buffer): { { number } } return out end --- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) @@ -194265,7 +190474,6 @@ function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) end local video = mux:finish() - -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time local audio: buffer? = nil local arate, askip = 1, 0 if as and o.audio ~= false then @@ -194360,7 +190568,6 @@ end type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) if not ogg then @@ -194429,7 +190636,7 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) break end if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then - continue -- a stray header + continue end table.insert(packets, p) if base == nil and p.granule >= 0 then @@ -194520,7 +190727,6 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, nil end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Ogv.demux, r, opts) if not ok then @@ -194536,18 +190742,9 @@ return Ogv end __FILES["video/smk"] = function() --- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description --- (MultimediaWiki "Smacker"). --- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio --- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette --- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() --- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the --- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio --- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it --- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that --- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, --- track) the Decoder of any of its audio tracks. --- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194570,11 +190767,11 @@ local Smk = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - audio: boolean?, -- false: do not open the audio track - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) - openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) + audio: boolean?, + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) + openAudio: any?, -- the api's hook, only for Bink audio } -- ------------------------------------------------------------------------------------------------ constants @@ -194596,7 +190793,6 @@ function Smk.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) local pal = buffer.create(1024) buffer.copy(pal, 0, old, 0, 1024) @@ -194633,7 +190829,6 @@ local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer return pal end --- demux(r, opts?) -> the Demuxer | nil, Err function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < HEADER then @@ -194784,7 +190979,6 @@ function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) local codec = track.codec if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then @@ -194836,7 +191030,6 @@ function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) }) end --- open(r, opts?) -> a VideoDecoder | nil, Err function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Smk.demux(r, opts) if not dmx then @@ -194860,20 +191053,15 @@ __FILES["video/smk/Audio"] = @native function() --- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker --- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), --- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ --- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per --- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / --- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives --- them. Never throws: trees are bounded and every read past the packet gives zero bits. +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). local Smacker = __include("codecs/video/Legacy/Smacker") local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} --- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message @native function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) local n = buffer.len(d) if not packed then @@ -194902,7 +191090,7 @@ local Audio = {} local br = Smacker.bits(d, 4, n - 4) local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk if bit(br) == 0 then - return 0, {} -- no data + return 0, {} end local stereo = bit(br) local wide = bit(br) @@ -194983,13 +191171,9 @@ return Audio end __FILES["video/y4m"] = function() --- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. --- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder --- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono --- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. --- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), --- alpha (C444alpha drops it). +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -195011,13 +191195,12 @@ local Y4m = { -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + rgba: boolean?, -- default false: yuv420p maxPixels: number?, -- default 2^26 } type EncodeOptions = { - frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the - -- shortest frame, longer frames repeated) - maxFps: number?, -- the highest rate uneven frame times may need (default 100) + frameRate: { number }?, -- { num, den } of the F tag (default: the shortest frame's rate) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -195061,7 +191244,6 @@ local function frameSize(pf: string, bits: number, w: number, h: number): number return w * h * bps end --- demux(r, opts?) -> the raw-video Demuxer | nil, Err function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local nl = -1 @@ -195148,7 +191330,7 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end local data = e + 1 if data + size > limit then - break -- a truncated last frame is dropped + break end dmx:add(1, k, k, 1, true, data, size) k += 1 @@ -195159,7 +191341,6 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) if not streams then @@ -195181,7 +191362,6 @@ function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Y4m.demux(r, opts) if not dmx then diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index 4ef4981..780163b 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,539 +1,539 @@ [ [27, "src/Rosetta/init.luau"], -[955, "src/Rosetta/Registry.luau"], -[3064, "src/Rosetta/Types.luau"], -[4221, "src/Rosetta/archive/7z/init.luau"], -[4614, "src/Rosetta/archive/7z/Header.luau"], -[5146, "src/Rosetta/archive/adf/init.luau"], -[5436, "src/Rosetta/archive/applesingle/init.luau"], -[5628, "src/Rosetta/archive/ar/init.luau"], -[6040, "src/Rosetta/archive/arj/init.luau"], -[6254, "src/Rosetta/archive/binhex/init.luau"], -[6510, "src/Rosetta/archive/br/init.luau"], -[6588, "src/Rosetta/archive/bz2/init.luau"], -[6654, "src/Rosetta/archive/cab/init.luau"], -[7083, "src/Rosetta/archive/cab/Sum.luau"], -[7127, "src/Rosetta/archive/cpio/init.luau"], -[7301, "src/Rosetta/archive/d64/init.luau"], -[7727, "src/Rosetta/archive/fat/init.luau"], -[7853, "src/Rosetta/archive/grp/init.luau"], -[7970, "src/Rosetta/archive/gzip/init.luau"], -[8159, "src/Rosetta/archive/iso/init.luau"], -[8236, "src/Rosetta/archive/lha/init.luau"], -[8672, "src/Rosetta/archive/lz4/init.luau"], -[9027, "src/Rosetta/archive/macbinary/init.luau"], -[9230, "src/Rosetta/archive/mpq/init.luau"], -[9651, "src/Rosetta/archive/mpq/Crypt.luau"], -[9718, "src/Rosetta/archive/pak/init.luau"], -[9855, "src/Rosetta/archive/rpm/init.luau"], -[10190, "src/Rosetta/archive/tar/init.luau"], -[10312, "src/Rosetta/archive/uu/init.luau"], -[10590, "src/Rosetta/archive/vpk/init.luau"], -[10909, "src/Rosetta/archive/wad/init.luau"], -[11385, "src/Rosetta/archive/wad/Map.luau"], -[11828, "src/Rosetta/archive/wad/Picture.luau"], -[11939, "src/Rosetta/archive/xz/init.luau"], -[12042, "src/Rosetta/archive/yenc/init.luau"], -[12321, "src/Rosetta/archive/z/init.luau"], -[12421, "src/Rosetta/archive/zip/init.luau"], -[12661, "src/Rosetta/archive/zoo/init.luau"], -[12860, "src/Rosetta/archive/zst/init.luau"], -[12925, "src/Rosetta/audio/aac/init.luau"], -[13136, "src/Rosetta/audio/ac3/init.luau"], -[13285, "src/Rosetta/audio/adpcm/init.luau"], -[13442, "src/Rosetta/audio/adx/init.luau"], -[13681, "src/Rosetta/audio/aiff/init.luau"], -[14083, "src/Rosetta/audio/ape/init.luau"], -[14219, "src/Rosetta/audio/au/init.luau"], -[14382, "src/Rosetta/audio/brstm/init.luau"], -[14682, "src/Rosetta/audio/caf/init.luau"], -[15352, "src/Rosetta/audio/flac/init.luau"], -[15515, "src/Rosetta/audio/flac/Meta.luau"], -[15740, "src/Rosetta/audio/flac/Stream.luau"], -[16125, "src/Rosetta/audio/m4a/init.luau"], -[16467, "src/Rosetta/audio/mp3/init.luau"], -[16747, "src/Rosetta/audio/mp3/Index.luau"], -[16943, "src/Rosetta/audio/mp3/Stream.luau"], -[17178, "src/Rosetta/audio/mp3/Tags.luau"], -[17497, "src/Rosetta/audio/mpc/init.luau"], -[17595, "src/Rosetta/audio/opus/init.luau"], -[17999, "src/Rosetta/audio/opus/Encode.luau"], -[18118, "src/Rosetta/audio/qoa/init.luau"], -[18305, "src/Rosetta/audio/tta/init.luau"], -[18430, "src/Rosetta/audio/vag/init.luau"], -[18663, "src/Rosetta/audio/voc/init.luau"], -[18943, "src/Rosetta/audio/vorbis/init.luau"], -[19415, "src/Rosetta/audio/vorbis/Encode.luau"], -[20244, "src/Rosetta/audio/wav/init.luau"], -[20889, "src/Rosetta/audio/wav/Codecs.luau"], -[21064, "src/Rosetta/audio/wavpack/init.luau"], -[21285, "src/Rosetta/cad/step/init.luau"], -[21697, "src/Rosetta/cad/step/Brep.luau"], -[21947, "src/Rosetta/cad/step/Parse.luau"], -[22522, "src/Rosetta/cad/step/Write.luau"], -[22776, "src/Rosetta/codecs/audio/Aac/init.luau"], -[23095, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23978, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24313, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24472, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25357, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25458, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26212, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26514, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26748, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27167, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27579, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27794, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28555, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28652, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28663, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29612, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30209, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30405, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30654, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31612, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31831, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[32015, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32224, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32570, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32584, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32643, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34246, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34538, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34923, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35564, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35705, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35931, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36276, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[37157, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37535, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37549, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39396, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40461, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40521, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40981, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41318, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41551, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43587, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43961, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44224, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44521, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44803, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45162, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45216, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45359, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45872, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46653, "src/Rosetta/codecs/audio/Stream.luau"], -[46814, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47296, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47574, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47743, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47871, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49859, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49975, "src/Rosetta/codecs/audio/Tta/init.luau"], -[50092, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50344, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50357, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50741, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51307, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51728, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51767, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51819, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[52041, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53496, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53559, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53646, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54615, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55483, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55531, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[56047, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56373, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56793, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57228, "src/Rosetta/codecs/compress/Explode.luau"], -[57424, "src/Rosetta/codecs/compress/Lz4.luau"], -[57693, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58297, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58837, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58875, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59348, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59524, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59792, "src/Rosetta/codecs/compress/Lzx.luau"], -[60226, "src/Rosetta/codecs/compress/PackBits.luau"], -[60316, "src/Rosetta/codecs/compress/Quantum.luau"], -[60553, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60857, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60926, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60983, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61941, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[62093, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62375, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62386, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62600, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62844, "src/Rosetta/codecs/font/Bitmap.luau"], -[63045, "src/Rosetta/codecs/font/Cff/init.luau"], -[63686, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63836, "src/Rosetta/codecs/font/TrueType/init.luau"], -[64150, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64542, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[65044, "src/Rosetta/codecs/image/Bcn/init.luau"], -[65151, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65640, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[66069, "src/Rosetta/codecs/image/Blend.luau"], -[66448, "src/Rosetta/codecs/image/Dct/init.luau"], -[66829, "src/Rosetta/codecs/image/Etc.luau"], -[67127, "src/Rosetta/codecs/image/Half.luau"], -[67196, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67550, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67958, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68195, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68955, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69836, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70282, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70360, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70427, "src/Rosetta/codecs/image/Pixels.luau"], -[70691, "src/Rosetta/codecs/image/Quantize/init.luau"], -[71150, "src/Rosetta/codecs/image/Raster.luau"], -[71847, "src/Rosetta/codecs/image/Texel.luau"], -[72220, "src/Rosetta/codecs/image/Texture.luau"], -[72365, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72495, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74451, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74710, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74959, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[75078, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75182, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[76035, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76987, "src/Rosetta/codecs/image/Yuv.luau"], -[77255, "src/Rosetta/codecs/model/Draco/init.luau"], -[77587, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[78056, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79245, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[79394, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79753, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80715, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81189, "src/Rosetta/codecs/model/Mat4.luau"], -[81448, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81976, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[82528, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82607, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82714, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82920, "src/Rosetta/codecs/model/Polygon.luau"], -[83154, "src/Rosetta/codecs/model/Rbx/init.luau"], -[83391, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[84145, "src/Rosetta/codecs/model/Rig.luau"], -[84388, "src/Rosetta/codecs/model/Sampler.luau"], -[84548, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84696, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85270, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[85433, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86182, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86704, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[87431, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87663, "src/Rosetta/codecs/text/Json/init.luau"], -[87932, "src/Rosetta/codecs/text/Json/Decode.luau"], -[88346, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88648, "src/Rosetta/codecs/text/Nbt/init.luau"], -[89001, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[89693, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90333, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90571, "src/Rosetta/codecs/text/Text/init.luau"], -[90662, "src/Rosetta/codecs/text/Url/init.luau"], -[90867, "src/Rosetta/codecs/text/Xml/init.luau"], -[91270, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[92010, "src/Rosetta/codecs/video/Dsp.luau"], -[92733, "src/Rosetta/codecs/video/H263/init.luau"], -[92889, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[93747, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93950, "src/Rosetta/codecs/video/H264/init.luau"], -[94323, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94598, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[95729, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[96497, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[96755, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[97764, "src/Rosetta/codecs/video/H264/Inter.luau"], -[98018, "src/Rosetta/codecs/video/H264/Intra.luau"], -[98425, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99331, "src/Rosetta/codecs/video/H264/Params.luau"], -[99778, "src/Rosetta/codecs/video/H264/Slice.luau"], -[100029, "src/Rosetta/codecs/video/H264/Tables.luau"], -[100070, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100235, "src/Rosetta/codecs/video/Legacy/init.luau"], -[100433, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[100730, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[101097, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101215, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101323, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101596, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101991, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102168, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102180, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102547, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[104054, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104193, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104331, "src/Rosetta/codecs/video/Theora/init.luau"], -[104594, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105858, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106221, "src/Rosetta/codecs/video/Video/init.luau"], -[106778, "src/Rosetta/codecs/video/Video/Source.luau"], -[107063, "src/Rosetta/containers/Archive.luau"], -[107356, "src/Rosetta/containers/AudioWrap.luau"], -[107877, "src/Rosetta/containers/Avi/init.luau"], -[108449, "src/Rosetta/containers/Chunks.luau"], -[108593, "src/Rosetta/containers/Cpio.luau"], -[109035, "src/Rosetta/containers/Demux.luau"], -[109333, "src/Rosetta/containers/Ebml/init.luau"], -[109670, "src/Rosetta/containers/Fat.luau"], -[110379, "src/Rosetta/containers/Iso9660.luau"], -[110906, "src/Rosetta/containers/IsoBmff/init.luau"], -[111096, "src/Rosetta/containers/IsoBmff/Box.luau"], -[111291, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[112155, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[112685, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[113206, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[113328, "src/Rosetta/containers/MacFile.luau"], -[113488, "src/Rosetta/containers/MpegEs.luau"], -[113663, "src/Rosetta/containers/MpegPs/init.luau"], -[113889, "src/Rosetta/containers/MpegTs/init.luau"], -[114706, "src/Rosetta/containers/Ogg/init.luau"], -[115164, "src/Rosetta/containers/Ogg/Mux.luau"], -[115374, "src/Rosetta/containers/Ogg/Page.luau"], -[115551, "src/Rosetta/containers/Riff/init.luau"], -[115896, "src/Rosetta/containers/Tar.luau"], -[116324, "src/Rosetta/containers/Zip/init.luau"], -[116984, "src/Rosetta/core/Adler32.luau"], -[117036, "src/Rosetta/core/Base64.luau"], -[117205, "src/Rosetta/core/Bits.luau"], -[117517, "src/Rosetta/core/Bytes.luau"], -[118086, "src/Rosetta/core/Crc16.luau"], -[118140, "src/Rosetta/core/Crc32.luau"], -[118263, "src/Rosetta/core/Err.luau"], -[118359, "src/Rosetta/core/Input.luau"], -[118443, "src/Rosetta/core/Md5.luau"], -[118609, "src/Rosetta/core/Sniff.luau"], -[118647, "src/Rosetta/data/cbor/init.luau"], -[118749, "src/Rosetta/data/cbor/Codec.luau"], -[119326, "src/Rosetta/data/csv/init.luau"], -[119643, "src/Rosetta/data/ini/init.luau"], -[119894, "src/Rosetta/data/json/init.luau"], -[119987, "src/Rosetta/data/msgpack/init.luau"], -[120079, "src/Rosetta/data/msgpack/Codec.luau"], -[120527, "src/Rosetta/data/nbt/init.luau"], -[120589, "src/Rosetta/data/plist/init.luau"], -[120897, "src/Rosetta/data/plist/Binary.luau"], -[121170, "src/Rosetta/data/snbt/init.luau"], -[121235, "src/Rosetta/data/toml/init.luau"], -[121307, "src/Rosetta/data/toml/Decode.luau"], -[121944, "src/Rosetta/data/toml/Encode.luau"], -[122160, "src/Rosetta/data/xml/init.luau"], -[122217, "src/Rosetta/data/yaml/init.luau"], -[122296, "src/Rosetta/data/yaml/Emit.luau"], -[122597, "src/Rosetta/data/yaml/Parse.luau"], -[123921, "src/Rosetta/font/bdf/init.luau"], -[124218, "src/Rosetta/font/bmfont/init.luau"], -[124660, "src/Rosetta/font/bmfont/Parse.luau"], -[125119, "src/Rosetta/font/eot/init.luau"], -[125354, "src/Rosetta/font/fon/init.luau"], -[125644, "src/Rosetta/font/hershey/init.luau"], -[125846, "src/Rosetta/font/pcf/init.luau"], -[126138, "src/Rosetta/font/psf/init.luau"], -[126468, "src/Rosetta/font/ttf/init.luau"], -[126522, "src/Rosetta/font/type1/init.luau"], -[126892, "src/Rosetta/font/type1/Charstring.luau"], -[127177, "src/Rosetta/font/woff/init.luau"], -[127311, "src/Rosetta/font/woff2/init.luau"], -[127370, "src/Rosetta/font/woff2/Rebuild.luau"], -[127920, "src/Rosetta/host/init.luau"], -[127972, "src/Rosetta/host/Love.luau"], -[128123, "src/Rosetta/host/LuaJIT.luau"], -[128173, "src/Rosetta/host/Luau.luau"], -[128196, "src/Rosetta/host/Roblox.luau"], -[128587, "src/Rosetta/image/ani/init.luau"], -[128772, "src/Rosetta/image/blp/init.luau"], -[129040, "src/Rosetta/image/bmp/init.luau"], -[129471, "src/Rosetta/image/dds/init.luau"], -[129970, "src/Rosetta/image/exr/init.luau"], -[130754, "src/Rosetta/image/exr/Codec.luau"], -[130873, "src/Rosetta/image/exr/Piz.luau"], -[131242, "src/Rosetta/image/gif/init.luau"], -[131778, "src/Rosetta/image/gif/Decode.luau"], -[131848, "src/Rosetta/image/hdr/init.luau"], -[132084, "src/Rosetta/image/hdr/Codec.luau"], -[132305, "src/Rosetta/image/icns/init.luau"], -[132644, "src/Rosetta/image/ico/init.luau"], -[132928, "src/Rosetta/image/ico/Dib.luau"], -[133029, "src/Rosetta/image/ilbm/init.luau"], -[133355, "src/Rosetta/image/jpeg/init.luau"], -[133506, "src/Rosetta/image/ktx/init.luau"], -[134180, "src/Rosetta/image/pcx/init.luau"], -[134448, "src/Rosetta/image/png/init.luau"], -[135046, "src/Rosetta/image/png/Apng.luau"], -[135130, "src/Rosetta/image/png/Decode.luau"], -[135385, "src/Rosetta/image/png/Encode.luau"], -[135549, "src/Rosetta/image/pnm/init.luau"], -[135935, "src/Rosetta/image/pnm/Codec.luau"], -[136226, "src/Rosetta/image/qoi/init.luau"], -[136350, "src/Rosetta/image/qoi/Codec.luau"], -[136504, "src/Rosetta/image/sgi/init.luau"], -[136792, "src/Rosetta/image/sunras/init.luau"], -[137041, "src/Rosetta/image/tga/init.luau"], -[137319, "src/Rosetta/image/tga/Codec.luau"], -[137478, "src/Rosetta/image/tiff/init.luau"], -[138322, "src/Rosetta/image/tiff/Pixels.luau"], -[138723, "src/Rosetta/image/tim/init.luau"], -[138972, "src/Rosetta/image/vtf/init.luau"], -[139219, "src/Rosetta/image/webp/init.luau"], -[139848, "src/Rosetta/image/webp/Alpha.luau"], -[139926, "src/Rosetta/image/webp/Anim.luau"], -[140090, "src/Rosetta/image/xbm/init.luau"], -[140254, "src/Rosetta/image/xpm/init.luau"], -[140528, "src/Rosetta/image/xpm/Names.luau"], -[140587, "src/Rosetta/layered/aseprite/init.luau"], -[141343, "src/Rosetta/layered/ora/init.luau"], -[141638, "src/Rosetta/layered/psd/init.luau"], -[142383, "src/Rosetta/layered/psd/Channels.luau"], -[142754, "src/Rosetta/model/3ds/init.luau"], -[142856, "src/Rosetta/model/3ds/Build.luau"], -[143521, "src/Rosetta/model/3ds/Read.luau"], -[144029, "src/Rosetta/model/3ds/Write.luau"], -[144858, "src/Rosetta/model/3mf/init.luau"], -[144955, "src/Rosetta/model/3mf/Read.luau"], -[145555, "src/Rosetta/model/3mf/Write.luau"], -[145974, "src/Rosetta/model/b3d/init.luau"], -[146044, "src/Rosetta/model/b3d/Read.luau"], -[146622, "src/Rosetta/model/bsp/init.luau"], -[146774, "src/Rosetta/model/bsp/Brush.luau"], -[147067, "src/Rosetta/model/bsp/Quake3.luau"], -[147330, "src/Rosetta/model/dae/init.luau"], -[147538, "src/Rosetta/model/dae/Math.luau"], -[147586, "src/Rosetta/model/dae/Read.luau"], -[149468, "src/Rosetta/model/dae/Write.luau"], -[149846, "src/Rosetta/model/fbx/init.luau"], -[150014, "src/Rosetta/model/fbx/Ascii.luau"], -[150290, "src/Rosetta/model/fbx/Binary.luau"], -[150753, "src/Rosetta/model/fbx/Read.luau"], -[152139, "src/Rosetta/model/fbx/Write.luau"], -[153137, "src/Rosetta/model/fbx/Xform.luau"], -[153181, "src/Rosetta/model/gltf/init.luau"], -[153435, "src/Rosetta/model/gltf/Pack.luau"], -[153511, "src/Rosetta/model/gltf/Read.luau"], -[154260, "src/Rosetta/model/gltf/Write.luau"], -[154958, "src/Rosetta/model/iqm/init.luau"], -[155042, "src/Rosetta/model/iqm/Read.luau"], -[155403, "src/Rosetta/model/iqm/Write.luau"], -[156111, "src/Rosetta/model/ldraw/init.luau"], -[156218, "src/Rosetta/model/ldraw/Colors.luau"], -[156539, "src/Rosetta/model/ldraw/Read.luau"], -[157121, "src/Rosetta/model/lwo/init.luau"], -[157209, "src/Rosetta/model/lwo/Build.luau"], -[157680, "src/Rosetta/model/lwo/Parse.luau"], -[158233, "src/Rosetta/model/mca/init.luau"], -[158590, "src/Rosetta/model/mca/Chunk.luau"], -[158727, "src/Rosetta/model/mca/Lz4Block.luau"], -[158799, "src/Rosetta/model/md2/init.luau"], -[159010, "src/Rosetta/model/md3/init.luau"], -[159246, "src/Rosetta/model/md5/init.luau"], -[159331, "src/Rosetta/model/md5/Read.luau"], -[159773, "src/Rosetta/model/mdl/init.luau"], -[159859, "src/Rosetta/model/mdl/HalfLife.luau"], -[160201, "src/Rosetta/model/mdl/Quake.luau"], -[160425, "src/Rosetta/model/ms3d/init.luau"], -[160509, "src/Rosetta/model/ms3d/Read.luau"], -[160975, "src/Rosetta/model/ms3d/Write.luau"], -[161463, "src/Rosetta/model/obj/init.luau"], -[162228, "src/Rosetta/model/obj/Mtl.luau"], -[162524, "src/Rosetta/model/off/init.luau"], -[163006, "src/Rosetta/model/ply/init.luau"], -[164156, "src/Rosetta/model/ply/Binary.luau"], -[164370, "src/Rosetta/model/pmx/init.luau"], -[164449, "src/Rosetta/model/pmx/Build.luau"], -[164758, "src/Rosetta/model/pmx/Pmd.luau"], -[165099, "src/Rosetta/model/pmx/Read.luau"], -[165512, "src/Rosetta/model/qb/init.luau"], -[165915, "src/Rosetta/model/rbxm/init.luau"], -[166522, "src/Rosetta/model/rbxmx/init.luau"], -[167191, "src/Rosetta/model/robloxmesh/init.luau"], -[167877, "src/Rosetta/model/robloxmesh/Parse.luau"], -[168339, "src/Rosetta/model/robloxmesh/Write.luau"], -[168450, "src/Rosetta/model/schematic/init.luau"], -[168786, "src/Rosetta/model/schematic/Common.luau"], -[168916, "src/Rosetta/model/schematic/Litematic.luau"], -[169133, "src/Rosetta/model/schematic/Mcedit.luau"], -[169384, "src/Rosetta/model/schematic/Sponge.luau"], -[169517, "src/Rosetta/model/smd/init.luau"], -[169588, "src/Rosetta/model/smd/Read.luau"], -[169865, "src/Rosetta/model/smd/Write.luau"], -[170117, "src/Rosetta/model/stl/init.luau"], -[170586, "src/Rosetta/model/stl/Decode.luau"], -[170665, "src/Rosetta/model/usda/init.luau"], -[170888, "src/Rosetta/model/usda/Build.luau"], -[172205, "src/Rosetta/model/usda/Parse.luau"], -[173027, "src/Rosetta/model/usda/Write.luau"], -[173869, "src/Rosetta/model/vox/init.luau"], -[174774, "src/Rosetta/model/vox/Grid.luau"], -[174837, "src/Rosetta/model/vrml/init.luau"], -[174916, "src/Rosetta/model/x/init.luau"], -[175060, "src/Rosetta/model/x/Build.luau"], -[175636, "src/Rosetta/model/x/Parse.luau"], -[175944, "src/Rosetta/model/x3d/init.luau"], -[176031, "src/Rosetta/music/669/init.luau"], -[176242, "src/Rosetta/music/ahx/init.luau"], -[176297, "src/Rosetta/music/far/init.luau"], -[176531, "src/Rosetta/music/hmp/init.luau"], -[176806, "src/Rosetta/music/hvl/init.luau"], -[176861, "src/Rosetta/music/it/init.luau"], -[177290, "src/Rosetta/music/it/Itsex.luau"], -[177412, "src/Rosetta/music/med/init.luau"], -[178075, "src/Rosetta/music/midi/init.luau"], -[178231, "src/Rosetta/music/midi/Smf.luau"], -[178651, "src/Rosetta/music/mod/init.luau"], -[179014, "src/Rosetta/music/mtm/init.luau"], -[179242, "src/Rosetta/music/mus/init.luau"], -[179407, "src/Rosetta/music/okt/init.luau"], -[179695, "src/Rosetta/music/ptm/init.luau"], -[179924, "src/Rosetta/music/s3m/init.luau"], -[180168, "src/Rosetta/music/sf2/init.luau"], -[180214, "src/Rosetta/music/stm/init.luau"], -[180449, "src/Rosetta/music/ult/init.luau"], -[180760, "src/Rosetta/music/umx/init.luau"], -[180984, "src/Rosetta/music/xm/init.luau"], -[181559, "src/Rosetta/music/xmi/init.luau"], -[181776, "src/Rosetta/ops/AudioOps.luau"], -[182260, "src/Rosetta/ops/ImageOps/init.luau"], -[182951, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[183473, "src/Rosetta/ops/LayerOps.luau"], -[183576, "src/Rosetta/ops/MeshOps/init.luau"], -[184665, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[184834, "src/Rosetta/ops/MusicOps.luau"], -[185205, "src/Rosetta/playlist/m3u/init.luau"], -[185574, "src/Rosetta/playlist/pls/init.luau"], -[185761, "src/Rosetta/playlist/xspf/init.luau"], -[185977, "src/Rosetta/subtitle/ass/init.luau"], -[186435, "src/Rosetta/subtitle/srt/init.luau"], -[186615, "src/Rosetta/subtitle/vtt/init.luau"], -[186825, "src/Rosetta/vector/svg/init.luau"], -[186921, "src/Rosetta/vector/svg/Parse.luau"], -[187681, "src/Rosetta/vector/svg/PathData.luau"], -[188060, "src/Rosetta/vector/svg/Render.luau"], -[188489, "src/Rosetta/vector/svg/Style.luau"], -[188872, "src/Rosetta/vector/svg/Write.luau"], -[189077, "src/Rosetta/vector/tiled/init.luau"], -[189266, "src/Rosetta/vector/tiled/Data.luau"], -[189424, "src/Rosetta/vector/tiled/Tmj.luau"], -[190060, "src/Rosetta/vector/tiled/Tmx.luau"], -[190680, "src/Rosetta/video/avi/init.luau"], -[190985, "src/Rosetta/video/fli/init.luau"], -[191144, "src/Rosetta/video/flv/init.luau"], -[191548, "src/Rosetta/video/flv/Amf.luau"], -[191716, "src/Rosetta/video/flv/Mux.luau"], -[192006, "src/Rosetta/video/h264/init.luau"], -[192153, "src/Rosetta/video/mkv/init.luau"], -[192324, "src/Rosetta/video/mkv/Mux.luau"], -[192611, "src/Rosetta/video/mkv/Parse.luau"], -[193343, "src/Rosetta/video/mp4/init.luau"], -[193686, "src/Rosetta/video/mpegps/init.luau"], -[193881, "src/Rosetta/video/mpegts/init.luau"], -[194129, "src/Rosetta/video/ogv/init.luau"], -[194538, "src/Rosetta/video/smk/init.luau"], -[194860, "src/Rosetta/video/smk/Audio.luau"], -[194985, "src/Rosetta/video/y4m/init.luau"] +[871, "src/Rosetta/Registry.luau"], +[2980, "src/Rosetta/Types.luau"], +[4063, "src/Rosetta/archive/7z/init.luau"], +[4448, "src/Rosetta/archive/7z/Header.luau"], +[4975, "src/Rosetta/archive/adf/init.luau"], +[5257, "src/Rosetta/archive/applesingle/init.luau"], +[5443, "src/Rosetta/archive/ar/init.luau"], +[5846, "src/Rosetta/archive/arj/init.luau"], +[6056, "src/Rosetta/archive/binhex/init.luau"], +[6305, "src/Rosetta/archive/br/init.luau"], +[6380, "src/Rosetta/archive/bz2/init.luau"], +[6444, "src/Rosetta/archive/cab/init.luau"], +[6857, "src/Rosetta/archive/cab/Sum.luau"], +[6898, "src/Rosetta/archive/cpio/init.luau"], +[7066, "src/Rosetta/archive/d64/init.luau"], +[7480, "src/Rosetta/archive/fat/init.luau"], +[7602, "src/Rosetta/archive/grp/init.luau"], +[7716, "src/Rosetta/archive/gzip/init.luau"], +[7901, "src/Rosetta/archive/iso/init.luau"], +[7973, "src/Rosetta/archive/lha/init.luau"], +[8398, "src/Rosetta/archive/lz4/init.luau"], +[8742, "src/Rosetta/archive/macbinary/init.luau"], +[8940, "src/Rosetta/archive/mpq/init.luau"], +[9346, "src/Rosetta/archive/mpq/Crypt.luau"], +[9411, "src/Rosetta/archive/pak/init.luau"], +[9545, "src/Rosetta/archive/rpm/init.luau"], +[9869, "src/Rosetta/archive/tar/init.luau"], +[9987, "src/Rosetta/archive/uu/init.luau"], +[10257, "src/Rosetta/archive/vpk/init.luau"], +[10568, "src/Rosetta/archive/wad/init.luau"], +[11018, "src/Rosetta/archive/wad/Map.luau"], +[11448, "src/Rosetta/archive/wad/Picture.luau"], +[11550, "src/Rosetta/archive/xz/init.luau"], +[11650, "src/Rosetta/archive/yenc/init.luau"], +[11922, "src/Rosetta/archive/z/init.luau"], +[12018, "src/Rosetta/archive/zip/init.luau"], +[12237, "src/Rosetta/archive/zoo/init.luau"], +[12433, "src/Rosetta/archive/zst/init.luau"], +[12497, "src/Rosetta/audio/aac/init.luau"], +[12703, "src/Rosetta/audio/ac3/init.luau"], +[12849, "src/Rosetta/audio/adpcm/init.luau"], +[12994, "src/Rosetta/audio/adx/init.luau"], +[13225, "src/Rosetta/audio/aiff/init.luau"], +[13616, "src/Rosetta/audio/ape/init.luau"], +[13744, "src/Rosetta/audio/au/init.luau"], +[13905, "src/Rosetta/audio/brstm/init.luau"], +[14196, "src/Rosetta/audio/caf/init.luau"], +[14858, "src/Rosetta/audio/flac/init.luau"], +[15006, "src/Rosetta/audio/flac/Meta.luau"], +[15228, "src/Rosetta/audio/flac/Stream.luau"], +[15598, "src/Rosetta/audio/m4a/init.luau"], +[15932, "src/Rosetta/audio/mp3/init.luau"], +[16192, "src/Rosetta/audio/mp3/Index.luau"], +[16383, "src/Rosetta/audio/mp3/Stream.luau"], +[16606, "src/Rosetta/audio/mp3/Tags.luau"], +[16918, "src/Rosetta/audio/mpc/init.luau"], +[17012, "src/Rosetta/audio/opus/init.luau"], +[17390, "src/Rosetta/audio/opus/Encode.luau"], +[17501, "src/Rosetta/audio/qoa/init.luau"], +[17681, "src/Rosetta/audio/tta/init.luau"], +[17799, "src/Rosetta/audio/vag/init.luau"], +[18022, "src/Rosetta/audio/voc/init.luau"], +[18297, "src/Rosetta/audio/vorbis/init.luau"], +[18751, "src/Rosetta/audio/vorbis/Encode.luau"], +[19564, "src/Rosetta/audio/wav/init.luau"], +[20185, "src/Rosetta/audio/wav/Codecs.luau"], +[20351, "src/Rosetta/audio/wavpack/init.luau"], +[20558, "src/Rosetta/cad/step/init.luau"], +[20940, "src/Rosetta/cad/step/Brep.luau"], +[21175, "src/Rosetta/cad/step/Parse.luau"], +[21732, "src/Rosetta/cad/step/Write.luau"], +[21980, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22299, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23182, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23517, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[23676, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24561, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[24662, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25416, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[25718, "src/Rosetta/codecs/audio/Alac/init.luau"], +[25952, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26371, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[26783, "src/Rosetta/codecs/audio/Ape/init.luau"], +[26998, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[27759, "src/Rosetta/codecs/audio/ApeTag.luau"], +[27856, "src/Rosetta/codecs/audio/Flac/init.luau"], +[27867, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[28816, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29413, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29609, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[29858, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[30816, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31035, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31219, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31428, "src/Rosetta/codecs/audio/MidiRender.luau"], +[31774, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[31788, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[31847, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33450, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[33742, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34127, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[34768, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[34909, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35135, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35480, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36361, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[36739, "src/Rosetta/codecs/audio/Opus/init.luau"], +[36753, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38600, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[39665, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[39725, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40185, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40522, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[40755, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[42791, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43165, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43428, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[43725, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44007, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44366, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44420, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44563, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45076, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[45857, "src/Rosetta/codecs/audio/Stream.luau"], +[46018, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46500, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[46778, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[46947, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47075, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49063, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49179, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49296, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49548, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49561, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[49945, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50511, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[50932, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[50971, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51023, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51245, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[52700, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[52763, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[52850, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[53819, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[54687, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[54735, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55251, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55577, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[55997, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56432, "src/Rosetta/codecs/compress/Explode.luau"], +[56628, "src/Rosetta/codecs/compress/Lz4.luau"], +[56897, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57501, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58041, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58079, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58552, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[58728, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[58996, "src/Rosetta/codecs/compress/Lzx.luau"], +[59430, "src/Rosetta/codecs/compress/PackBits.luau"], +[59520, "src/Rosetta/codecs/compress/Quantum.luau"], +[59757, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60061, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60130, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60187, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61145, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61297, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61579, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61590, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[61804, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62048, "src/Rosetta/codecs/font/Bitmap.luau"], +[62249, "src/Rosetta/codecs/font/Cff/init.luau"], +[62890, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63040, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63354, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[63746, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64248, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64355, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[64844, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65273, "src/Rosetta/codecs/image/Blend.luau"], +[65652, "src/Rosetta/codecs/image/Dct/init.luau"], +[66033, "src/Rosetta/codecs/image/Etc.luau"], +[66331, "src/Rosetta/codecs/image/Half.luau"], +[66400, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[66754, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67162, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67399, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68159, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69040, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69486, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69564, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69631, "src/Rosetta/codecs/image/Pixels.luau"], +[69895, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70354, "src/Rosetta/codecs/image/Raster.luau"], +[71051, "src/Rosetta/codecs/image/Texel.luau"], +[71424, "src/Rosetta/codecs/image/Texture.luau"], +[71569, "src/Rosetta/codecs/image/Vp8/init.luau"], +[71699, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[73655, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[73914, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74163, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74282, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[74386, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75239, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76191, "src/Rosetta/codecs/image/Yuv.luau"], +[76459, "src/Rosetta/codecs/model/Draco/init.luau"], +[76791, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77260, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[78449, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[78598, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[78957, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[79919, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[80393, "src/Rosetta/codecs/model/Mat4.luau"], +[80652, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81180, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[81732, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[81811, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[81918, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82124, "src/Rosetta/codecs/model/Polygon.luau"], +[82358, "src/Rosetta/codecs/model/Rbx/init.luau"], +[82595, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83349, "src/Rosetta/codecs/model/Rig.luau"], +[83592, "src/Rosetta/codecs/model/Sampler.luau"], +[83752, "src/Rosetta/codecs/model/Vrml/init.luau"], +[83900, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[84474, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[84637, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[85386, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[85908, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[86635, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[86867, "src/Rosetta/codecs/text/Json/init.luau"], +[87136, "src/Rosetta/codecs/text/Json/Decode.luau"], +[87550, "src/Rosetta/codecs/text/Json/Encode.luau"], +[87852, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88205, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[88897, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[89537, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[89775, "src/Rosetta/codecs/text/Text/init.luau"], +[89866, "src/Rosetta/codecs/text/Url/init.luau"], +[90071, "src/Rosetta/codecs/text/Xml/init.luau"], +[90474, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91214, "src/Rosetta/codecs/video/Dsp.luau"], +[91937, "src/Rosetta/codecs/video/H263/init.luau"], +[92093, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[92951, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93154, "src/Rosetta/codecs/video/H264/init.luau"], +[93527, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[93802, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[94933, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[95701, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[95959, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[96968, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97222, "src/Rosetta/codecs/video/H264/Intra.luau"], +[97629, "src/Rosetta/codecs/video/H264/Mb.luau"], +[98535, "src/Rosetta/codecs/video/H264/Params.luau"], +[98982, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99233, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99274, "src/Rosetta/codecs/video/H264/Transform.luau"], +[99439, "src/Rosetta/codecs/video/Legacy/init.luau"], +[99637, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[99934, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100301, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[100419, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[100527, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[100800, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101195, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[101372, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[101384, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[101751, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103258, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[103397, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[103535, "src/Rosetta/codecs/video/Theora/init.luau"], +[103798, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105062, "src/Rosetta/codecs/video/Theora/Header.luau"], +[105425, "src/Rosetta/codecs/video/Video/init.luau"], +[105982, "src/Rosetta/codecs/video/Video/Source.luau"], +[106267, "src/Rosetta/containers/Archive.luau"], +[106534, "src/Rosetta/containers/AudioWrap.luau"], +[107037, "src/Rosetta/containers/Avi/init.luau"], +[107589, "src/Rosetta/containers/Chunks.luau"], +[107724, "src/Rosetta/containers/Cpio.luau"], +[108152, "src/Rosetta/containers/Demux.luau"], +[108427, "src/Rosetta/containers/Ebml/init.luau"], +[108740, "src/Rosetta/containers/Fat.luau"], +[109428, "src/Rosetta/containers/Iso9660.luau"], +[109933, "src/Rosetta/containers/IsoBmff/init.luau"], +[110103, "src/Rosetta/containers/IsoBmff/Box.luau"], +[110291, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[111136, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[111657, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[112173, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[112290, "src/Rosetta/containers/MacFile.luau"], +[112439, "src/Rosetta/containers/MpegEs.luau"], +[112605, "src/Rosetta/containers/MpegPs/init.luau"], +[112825, "src/Rosetta/containers/MpegTs/init.luau"], +[113617, "src/Rosetta/containers/Ogg/init.luau"], +[114042, "src/Rosetta/containers/Ogg/Mux.luau"], +[114237, "src/Rosetta/containers/Ogg/Page.luau"], +[114406, "src/Rosetta/containers/Riff/init.luau"], +[114723, "src/Rosetta/containers/Tar.luau"], +[115137, "src/Rosetta/containers/Zip/init.luau"], +[115769, "src/Rosetta/core/Adler32.luau"], +[115815, "src/Rosetta/core/Base64.luau"], +[115974, "src/Rosetta/core/Bits.luau"], +[116267, "src/Rosetta/core/Bytes.luau"], +[116794, "src/Rosetta/core/Crc16.luau"], +[116846, "src/Rosetta/core/Crc32.luau"], +[116958, "src/Rosetta/core/Err.luau"], +[117040, "src/Rosetta/core/Input.luau"], +[117116, "src/Rosetta/core/Md5.luau"], +[117275, "src/Rosetta/core/Sniff.luau"], +[117304, "src/Rosetta/data/cbor/init.luau"], +[117403, "src/Rosetta/data/cbor/Codec.luau"], +[117972, "src/Rosetta/data/csv/init.luau"], +[118284, "src/Rosetta/data/ini/init.luau"], +[118530, "src/Rosetta/data/json/init.luau"], +[118622, "src/Rosetta/data/msgpack/init.luau"], +[118711, "src/Rosetta/data/msgpack/Codec.luau"], +[119153, "src/Rosetta/data/nbt/init.luau"], +[119212, "src/Rosetta/data/plist/init.luau"], +[119518, "src/Rosetta/data/plist/Binary.luau"], +[119785, "src/Rosetta/data/snbt/init.luau"], +[119848, "src/Rosetta/data/toml/init.luau"], +[119915, "src/Rosetta/data/toml/Decode.luau"], +[120543, "src/Rosetta/data/toml/Encode.luau"], +[120752, "src/Rosetta/data/xml/init.luau"], +[120808, "src/Rosetta/data/yaml/init.luau"], +[120881, "src/Rosetta/data/yaml/Emit.luau"], +[121171, "src/Rosetta/data/yaml/Parse.luau"], +[122464, "src/Rosetta/font/bdf/init.luau"], +[122753, "src/Rosetta/font/bmfont/init.luau"], +[123180, "src/Rosetta/font/bmfont/Parse.luau"], +[123633, "src/Rosetta/font/eot/init.luau"], +[123865, "src/Rosetta/font/fon/init.luau"], +[124148, "src/Rosetta/font/hershey/init.luau"], +[124343, "src/Rosetta/font/pcf/init.luau"], +[124623, "src/Rosetta/font/psf/init.luau"], +[124943, "src/Rosetta/font/ttf/init.luau"], +[124994, "src/Rosetta/font/type1/init.luau"], +[125353, "src/Rosetta/font/type1/Charstring.luau"], +[125631, "src/Rosetta/font/woff/init.luau"], +[125763, "src/Rosetta/font/woff2/init.luau"], +[125820, "src/Rosetta/font/woff2/Rebuild.luau"], +[126360, "src/Rosetta/host/init.luau"], +[126405, "src/Rosetta/host/Love.luau"], +[126548, "src/Rosetta/host/LuaJIT.luau"], +[126598, "src/Rosetta/host/Luau.luau"], +[126621, "src/Rosetta/host/Roblox.luau"], +[126980, "src/Rosetta/image/ani/init.luau"], +[127160, "src/Rosetta/image/blp/init.luau"], +[127418, "src/Rosetta/image/bmp/init.luau"], +[127833, "src/Rosetta/image/dds/init.luau"], +[128316, "src/Rosetta/image/exr/init.luau"], +[129076, "src/Rosetta/image/exr/Codec.luau"], +[129187, "src/Rosetta/image/exr/Piz.luau"], +[129544, "src/Rosetta/image/gif/init.luau"], +[130060, "src/Rosetta/image/gif/Decode.luau"], +[130123, "src/Rosetta/image/hdr/init.luau"], +[130352, "src/Rosetta/image/hdr/Codec.luau"], +[130563, "src/Rosetta/image/icns/init.luau"], +[130894, "src/Rosetta/image/ico/init.luau"], +[131171, "src/Rosetta/image/ico/Dib.luau"], +[131266, "src/Rosetta/image/ilbm/init.luau"], +[131585, "src/Rosetta/image/jpeg/init.luau"], +[131721, "src/Rosetta/image/ktx/init.luau"], +[132381, "src/Rosetta/image/pcx/init.luau"], +[132645, "src/Rosetta/image/png/init.luau"], +[133225, "src/Rosetta/image/png/Apng.luau"], +[133305, "src/Rosetta/image/png/Decode.luau"], +[133545, "src/Rosetta/image/png/Encode.luau"], +[133700, "src/Rosetta/image/pnm/init.luau"], +[134078, "src/Rosetta/image/pnm/Codec.luau"], +[134355, "src/Rosetta/image/qoi/init.luau"], +[134477, "src/Rosetta/image/qoi/Codec.luau"], +[134627, "src/Rosetta/image/sgi/init.luau"], +[134912, "src/Rosetta/image/sunras/init.luau"], +[135158, "src/Rosetta/image/tga/init.luau"], +[135428, "src/Rosetta/image/tga/Codec.luau"], +[135580, "src/Rosetta/image/tiff/init.luau"], +[136407, "src/Rosetta/image/tiff/Pixels.luau"], +[136797, "src/Rosetta/image/tim/init.luau"], +[137039, "src/Rosetta/image/vtf/init.luau"], +[137274, "src/Rosetta/image/webp/init.luau"], +[137884, "src/Rosetta/image/webp/Alpha.luau"], +[137960, "src/Rosetta/image/webp/Anim.luau"], +[138115, "src/Rosetta/image/xbm/init.luau"], +[138276, "src/Rosetta/image/xpm/init.luau"], +[138544, "src/Rosetta/image/xpm/Names.luau"], +[138600, "src/Rosetta/layered/aseprite/init.luau"], +[139338, "src/Rosetta/layered/ora/init.luau"], +[139625, "src/Rosetta/layered/psd/init.luau"], +[140360, "src/Rosetta/layered/psd/Channels.luau"], +[140712, "src/Rosetta/model/3ds/init.luau"], +[140795, "src/Rosetta/model/3ds/Build.luau"], +[141442, "src/Rosetta/model/3ds/Read.luau"], +[141938, "src/Rosetta/model/3ds/Write.luau"], +[142743, "src/Rosetta/model/3mf/init.luau"], +[142825, "src/Rosetta/model/3mf/Read.luau"], +[143413, "src/Rosetta/model/3mf/Write.luau"], +[143818, "src/Rosetta/model/b3d/init.luau"], +[143873, "src/Rosetta/model/b3d/Read.luau"], +[144444, "src/Rosetta/model/bsp/init.luau"], +[144589, "src/Rosetta/model/bsp/Brush.luau"], +[144867, "src/Rosetta/model/bsp/Quake3.luau"], +[145122, "src/Rosetta/model/dae/init.luau"], +[145311, "src/Rosetta/model/dae/Math.luau"], +[145358, "src/Rosetta/model/dae/Read.luau"], +[147208, "src/Rosetta/model/dae/Write.luau"], +[147577, "src/Rosetta/model/fbx/init.luau"], +[147725, "src/Rosetta/model/fbx/Ascii.luau"], +[147995, "src/Rosetta/model/fbx/Binary.luau"], +[148450, "src/Rosetta/model/fbx/Read.luau"], +[149812, "src/Rosetta/model/fbx/Write.luau"], +[150797, "src/Rosetta/model/fbx/Xform.luau"], +[150838, "src/Rosetta/model/gltf/init.luau"], +[151075, "src/Rosetta/model/gltf/Pack.luau"], +[151144, "src/Rosetta/model/gltf/Read.luau"], +[151875, "src/Rosetta/model/gltf/Write.luau"], +[152555, "src/Rosetta/model/iqm/init.luau"], +[152631, "src/Rosetta/model/iqm/Read.luau"], +[152986, "src/Rosetta/model/iqm/Write.luau"], +[153673, "src/Rosetta/model/ldraw/init.luau"], +[153751, "src/Rosetta/model/ldraw/Colors.luau"], +[154069, "src/Rosetta/model/ldraw/Read.luau"], +[154646, "src/Rosetta/model/lwo/init.luau"], +[154722, "src/Rosetta/model/lwo/Build.luau"], +[155184, "src/Rosetta/model/lwo/Parse.luau"], +[155727, "src/Rosetta/model/mca/init.luau"], +[156069, "src/Rosetta/model/mca/Chunk.luau"], +[156202, "src/Rosetta/model/mca/Lz4Block.luau"], +[156272, "src/Rosetta/model/md2/init.luau"], +[156471, "src/Rosetta/model/md3/init.luau"], +[156699, "src/Rosetta/model/md5/init.luau"], +[156780, "src/Rosetta/model/md5/Read.luau"], +[157213, "src/Rosetta/model/mdl/init.luau"], +[157295, "src/Rosetta/model/mdl/HalfLife.luau"], +[157623, "src/Rosetta/model/mdl/Quake.luau"], +[157841, "src/Rosetta/model/ms3d/init.luau"], +[157913, "src/Rosetta/model/ms3d/Read.luau"], +[158359, "src/Rosetta/model/ms3d/Write.luau"], +[158828, "src/Rosetta/model/obj/init.luau"], +[159570, "src/Rosetta/model/obj/Mtl.luau"], +[159857, "src/Rosetta/model/off/init.luau"], +[160319, "src/Rosetta/model/ply/init.luau"], +[161424, "src/Rosetta/model/ply/Binary.luau"], +[161625, "src/Rosetta/model/pmx/init.luau"], +[161694, "src/Rosetta/model/pmx/Build.luau"], +[161990, "src/Rosetta/model/pmx/Pmd.luau"], +[162325, "src/Rosetta/model/pmx/Read.luau"], +[162729, "src/Rosetta/model/qb/init.luau"], +[163122, "src/Rosetta/model/rbxm/init.luau"], +[163714, "src/Rosetta/model/rbxmx/init.luau"], +[164367, "src/Rosetta/model/robloxmesh/init.luau"], +[165026, "src/Rosetta/model/robloxmesh/Parse.luau"], +[165483, "src/Rosetta/model/robloxmesh/Write.luau"], +[165592, "src/Rosetta/model/schematic/init.luau"], +[165913, "src/Rosetta/model/schematic/Common.luau"], +[166033, "src/Rosetta/model/schematic/Litematic.luau"], +[166244, "src/Rosetta/model/schematic/Mcedit.luau"], +[166488, "src/Rosetta/model/schematic/Sponge.luau"], +[166617, "src/Rosetta/model/smd/init.luau"], +[166684, "src/Rosetta/model/smd/Read.luau"], +[166953, "src/Rosetta/model/smd/Write.luau"], +[167196, "src/Rosetta/model/stl/init.luau"], +[167646, "src/Rosetta/model/stl/Decode.luau"], +[167720, "src/Rosetta/model/usda/init.luau"], +[167929, "src/Rosetta/model/usda/Build.luau"], +[169207, "src/Rosetta/model/usda/Parse.luau"], +[170005, "src/Rosetta/model/usda/Write.luau"], +[170822, "src/Rosetta/model/vox/init.luau"], +[171708, "src/Rosetta/model/vox/Grid.luau"], +[171765, "src/Rosetta/model/vrml/init.luau"], +[171831, "src/Rosetta/model/x/init.luau"], +[171961, "src/Rosetta/model/x/Build.luau"], +[172524, "src/Rosetta/model/x/Parse.luau"], +[172821, "src/Rosetta/model/x3d/init.luau"], +[172899, "src/Rosetta/music/669/init.luau"], +[173105, "src/Rosetta/music/ahx/init.luau"], +[173156, "src/Rosetta/music/far/init.luau"], +[173385, "src/Rosetta/music/hmp/init.luau"], +[173649, "src/Rosetta/music/hvl/init.luau"], +[173700, "src/Rosetta/music/it/init.luau"], +[174118, "src/Rosetta/music/it/Itsex.luau"], +[174234, "src/Rosetta/music/med/init.luau"], +[174881, "src/Rosetta/music/midi/init.luau"], +[175024, "src/Rosetta/music/midi/Smf.luau"], +[175435, "src/Rosetta/music/mod/init.luau"], +[175788, "src/Rosetta/music/mtm/init.luau"], +[176010, "src/Rosetta/music/mus/init.luau"], +[176167, "src/Rosetta/music/okt/init.luau"], +[176448, "src/Rosetta/music/ptm/init.luau"], +[176670, "src/Rosetta/music/s3m/init.luau"], +[176906, "src/Rosetta/music/sf2/init.luau"], +[176949, "src/Rosetta/music/stm/init.luau"], +[177180, "src/Rosetta/music/ult/init.luau"], +[177484, "src/Rosetta/music/umx/init.luau"], +[177700, "src/Rosetta/music/xm/init.luau"], +[178261, "src/Rosetta/music/xmi/init.luau"], +[178469, "src/Rosetta/ops/AudioOps.luau"], +[178918, "src/Rosetta/ops/ImageOps/init.luau"], +[179562, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[180072, "src/Rosetta/ops/LayerOps.luau"], +[180165, "src/Rosetta/ops/MeshOps/init.luau"], +[181201, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[181368, "src/Rosetta/ops/MusicOps.luau"], +[181716, "src/Rosetta/playlist/m3u/init.luau"], +[182069, "src/Rosetta/playlist/pls/init.luau"], +[182247, "src/Rosetta/playlist/xspf/init.luau"], +[182450, "src/Rosetta/subtitle/ass/init.luau"], +[182894, "src/Rosetta/subtitle/srt/init.luau"], +[183067, "src/Rosetta/subtitle/vtt/init.luau"], +[183270, "src/Rosetta/vector/svg/init.luau"], +[183356, "src/Rosetta/vector/svg/Parse.luau"], +[184102, "src/Rosetta/vector/svg/PathData.luau"], +[184470, "src/Rosetta/vector/svg/Render.luau"], +[184887, "src/Rosetta/vector/svg/Style.luau"], +[185259, "src/Rosetta/vector/svg/Write.luau"], +[185459, "src/Rosetta/vector/tiled/init.luau"], +[185639, "src/Rosetta/vector/tiled/Data.luau"], +[185790, "src/Rosetta/vector/tiled/Tmj.luau"], +[186421, "src/Rosetta/vector/tiled/Tmx.luau"], +[187033, "src/Rosetta/video/avi/init.luau"], +[187327, "src/Rosetta/video/fli/init.luau"], +[187478, "src/Rosetta/video/flv/init.luau"], +[187862, "src/Rosetta/video/flv/Amf.luau"], +[188020, "src/Rosetta/video/flv/Mux.luau"], +[188301, "src/Rosetta/video/h264/init.luau"], +[188440, "src/Rosetta/video/mkv/init.luau"], +[188596, "src/Rosetta/video/mkv/Mux.luau"], +[188875, "src/Rosetta/video/mkv/Parse.luau"], +[189596, "src/Rosetta/video/mp4/init.luau"], +[189924, "src/Rosetta/video/mpegps/init.luau"], +[190111, "src/Rosetta/video/mpegts/init.luau"], +[190349, "src/Rosetta/video/ogv/init.luau"], +[190744, "src/Rosetta/video/smk/init.luau"], +[191053, "src/Rosetta/video/smk/Audio.luau"], +[191173, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/rosetta.lua b/build/rosetta.lua index 8ff95f6..ae05d3e 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -3,24 +3,12 @@ -- (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. Error lines map back to -- the sources through rosetta.lua.linemap.json (python3 -I tools/bundle.py --where). local __compat = (function() --- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain luajit and LÖVE). --- tools/build.py copies this file to build/_modules/luajit/rosetta/_compat.lua (tools/bundle.py inlines it at the top --- of build/rosetta.lua), and every built module starts with --- local __compat = require("rosetta._compat") local buffer, bit32, utf8, typeof, type, __iter = ... --- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string --- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing. --- --- Semantics follow Luau (checked by tests/compat.luau under both runtimes): --- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap --- (fractional operands: see the bit32 section). --- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws --- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a --- private metatable: typeof(b) and the injected type(b) return "buffer". --- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to --- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the --- table has no keys past #t, anything else with next. --- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b --- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes. +-- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain and LÖVE), with Luau +-- semantics (tests/compat.luau). tools/build.py copies it to build/_modules/luajit/rosetta/_compat.lua and prepends +-- `local __compat = require("rosetta._compat") ...` to every built module's first line; tools/bundle.py inlines it at +-- the top of build/rosetta.lua. Nothing is installed globally; table / math / string additions only fill gaps. +-- buffer = { p = uint8_t*, n = length } with a private metatable (typeof / type say "buffer"); LuaJIT-only +-- buffer.toffi(b) / buffer.fromffi(ptr, n). local ffi = require("ffi") local bit = require("bit") local floor = math.floor @@ -30,17 +18,13 @@ local TWO32 = 4294967296 local M = {} --- ---------------------------------------------------------------------------------------------------- bit32 -- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32. --- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs --- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step). --- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never --- passes fractions to bit32 (tests/compat.luau checks integers only). +-- The inline `if r < 0 then r = r + 2^32 end` sign fix runs ~45% faster than `r % 2^32` (inflate). +-- Divergence: bit.tobit rounds a fractional operand where Luau truncates (the library never passes fractions). do local band, bor, bxor, bnot, lshift, rshift, arshift, bswap = bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap local B = {} - -- the 2- and 3-argument forms are the hot ones: no varargs on that path function B.band(a, b, c, d, ...) local r if b == nil then @@ -191,7 +175,6 @@ do M.bit32 = B end --- ---------------------------------------------------------------------------------------------------- buffer do ffi.cdef([[ void *memmove(void *dst, const void *src, size_t n); @@ -213,9 +196,8 @@ do BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end M.BUFFER_MT = BUF - -- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the - -- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every - -- 512 MB of them. + -- big buffers are calloc'd so they don't count against the 2 GB GC heap of non-GC64 builds (LÖVE); a full + -- collection runs every 512 MB of them since the GC doesn't see those bytes local BIG = 262144 local external = 0 @@ -385,7 +367,6 @@ do end end - -- LuaJIT-only extensions function Buf.toffi(b) return b.p end function Buf.fromffi(ptr, n) local b = create(n) @@ -395,7 +376,6 @@ do M.buffer = Buf end --- ---------------------------------------------------------------------------------------------------- typeof / type do local BUF = M.BUFFER_MT function M.type(v) @@ -409,7 +389,6 @@ do M.isbuffer = function(v) return getmetatable(v) == BUF end end --- ---------------------------------------------------------------------------------------------------- __iter local function arrayIter(s, i) local t, n = s[1], s[2] i = i + 1 @@ -435,7 +414,6 @@ function M.__iter(t, s, c) return next, t, nil end --- ---------------------------------------------------------------------------------------------------- table do local okn, tnew = pcall(require, "table.new") local okc, tclear = pcall(require, "table.clear") @@ -480,11 +458,9 @@ do end end --- ---------------------------------------------------------------------------------------------------- math do - -- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent - -- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and - -- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo). + -- math.min / math.max are branch-free in a trace; an if / elseif clamp spawned side traces and ran ~3.5x slower. + -- NaN stays NaN, as in Luau (maxsd would return lo). local mmin, mmax = math.min, math.max math.clamp = math.clamp or function(x, lo, hi) if lo > hi then error("max must be greater than or equal to min", 2) end @@ -512,7 +488,6 @@ do end end --- ---------------------------------------------------------------------------------------------------- string string.split = string.split or function(s, sep) sep = sep or "," local out = {} @@ -532,7 +507,6 @@ string.split = string.split or function(s, sep) end end --- ---------------------------------------------------------------------------------------------------- utf8 do -- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" } @@ -551,7 +525,6 @@ do for i = 1, n do out[i] = enc((select(i, ...))) end return table.concat(out) end - -- decode at byte i: codepoint, length; nil on invalid UTF-8 local function dec(s, i) local c = byte(s, i) if not c then return nil end @@ -598,7 +571,6 @@ do end return unpack(out, 1, k) end - -- len(s, i, j) -> count | nil, position of the first invalid byte function U.len(s, i, j) i = i or 1 j = j or #s @@ -649,7 +621,6 @@ do M.utf8 = utf8 or U end --- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself) function M.install(env) env = env or _G env.buffer = env.buffer or M.buffer @@ -688,21 +659,8 @@ __LOADED["_compat"] = __compat __FILES[""] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). --- Every format of a category maps onto one standard type (src/Rosetta/Types.luau): a PNG and a WebP both load as an --- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension. --- --- local F = require(Rosetta) -- Roblox: the ModuleScript; LuaJIT: require("rosetta"); luau: "@rosetta" --- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err --- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...) --- local dec = F.audio.open(src) -- streaming decoders (audio / video) --- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format --- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files --- local s = F.saveString(img, { format = "png" }) --- local buf = F.convert(src, "png", opts?) -- load + save --- F.formats() -- the capability list (also docs/FORMATS.md) --- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector --- --- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). +-- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws +-- on bad data or bad arguments: every function returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") @@ -720,11 +678,10 @@ F.version = "0.1.0" F.Err = Err F.Types = Types F.Bytes = Bytes -F.Rbx = Rbx -- the Roblox instance tree helpers (codecs/model/Rbx: tree, instance, add, set, get, find, descendants) +F.Rbx = Rbx F.null = Types.null F.host = host F.plugins = {} --- value.kind -> category local KIND_CATEGORY= { image = "image", @@ -744,7 +701,6 @@ local KIND_CATEGORY= { playlist = "playlist", } --- ------------------------------------------------------------------------------------------------ registry access local loaded= {} local function module(entry) @@ -764,7 +720,6 @@ local function inCategory(entry, category) return category == nil or entry.category == category end --- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches local function find(key, category) local k = string.lower(key) for _, e in __iter(Registry) do @@ -780,7 +735,6 @@ local k = string.lower(key) return nil end --- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension local function detect(buf, name, category, format) if format then local e = find(format, category) @@ -820,9 +774,7 @@ if format then return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. ((name and((" (" .. name .. ")" ))or(""))) .. ((category and((" for " .. category ))or("")))) end --- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that --- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered = --- true: open the format, which renders it, instead of decoding it) +-- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true) local function detectFor(buf, name, o) local entry, err = detect(buf, name, o.category, o.format) if not entry and o.category == "audio" then @@ -847,7 +799,6 @@ local function tag(value, formatName) end end --- full decode through a streaming decoder (audio formats with open but no decode) local function drain(dec) local channels = dec.channels local parts, total = {}, 0 @@ -871,7 +822,7 @@ local channels = dec.channels return a end --- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs) +-- siblings resolve relative to path's directory only (no absolute paths, no "..", no URLs) local function siblings(path) local dir = string.match(path, "^(.*[/\\])") or "" return function(uri) @@ -890,13 +841,10 @@ return string.char((tonumber(h, 16) )) return b end end --- ------------------------------------------------------------------------------------------------ API local load --- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer --- | string, else the files next to the descriptor on hosts with a file system local function pageLoader(value, name, o) if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then @@ -918,7 +866,7 @@ if type(user) == "function" then src = (dir ) .. file end if type(src) == "table" then - return src -- already an Image + return src end if src == nil then return nil, Err.new(Err.IO, "no data for page " .. file) @@ -927,11 +875,8 @@ if type(user) == "function" then end end --- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a --- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer --- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's --- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the --- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font. +-- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with +-- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer) local function unwrap(value, formatName, o) if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then return value @@ -980,18 +925,8 @@ if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then return v end --- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format, --- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> --- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for --- the embedded parts) when called directly. --- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. --- --- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded --- as music (sniffed, or as the given format). --- --- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets --- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / --- FLAC / AC-3 as they are), opened through F.open with that format. +-- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule, +-- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are) local function openAudio(demuxer, track) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then @@ -1033,7 +968,6 @@ return F.save(img, nil, { format = format, category = "image" }) end end if c.decodeModule == nil then - -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format c.decodeModule = function(b, format) return F.load(b, { category = "music", format = format }) end @@ -1041,7 +975,6 @@ return F.load(b, { category = "music", format = format }) return c end --- load(src, opts?) -> value | nil, Err function F.load(src, opts) local o= opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -1061,7 +994,6 @@ local o= opts or {} return nil, merr end if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then - -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder o = table.clone(o) o.resolve = siblings(name) end @@ -1093,7 +1025,6 @@ local o= opts or {} end load = F.load --- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err function F.open(src, opts) local o= opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -1135,10 +1066,6 @@ local o= opts or {} end local encodeTextures --- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil, --- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are --- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap --- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is. local function videoToImage(v, o) if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then @@ -1198,9 +1125,6 @@ if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then return img, nil end --- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method --- for other engines) or a Midi (music/midi render) | --- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } local function renderMusic(value, o) local ok, dec, err @@ -1211,8 +1135,7 @@ local ok, dec, err end ok, dec, err = pcall(m.render, value, o) elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then - -- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an - -- empty Decoder carrying .err) + -- AHX / HVL render through the Module's own method (a failed render is an empty Decoder carrying .err) ok, dec = pcall(value.render, value, o) if ok and type(dec) == "table" and dec.err then return nil, dec.err @@ -1230,7 +1153,6 @@ local ok, dec, err return dec, nil end --- the writable format for a value: opts.format, the destination's extension, or the source format local function encoderFor(value, dest, o) local category = o.category if category == nil and type(value) == "table" and type(value.kind) == "string" then @@ -1290,17 +1212,12 @@ if type(scene.textures) ~= "table" then return nil end --- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files --- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the --- caller's opts.files); with a dest they are written next to it. function F.save(value, dest, opts) local o= opts or {} local entry, m, err, key = encoderFor(value, dest, o) if not entry then return nil, err end - -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file) - -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin) o = table.clone(o) o.format = o.format or key if dest then @@ -1309,7 +1226,7 @@ local o= opts or {} o.files = {} end elseif o.files == nil and entry.caps.extraFiles then - o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages + o.files = {} end if entry.category == "video" and type(value) == "table" and value.kind == "image" then local v, verr = F.video.fromImage(value) @@ -1326,7 +1243,7 @@ local o= opts or {} value = img end if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then - local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts + local dec, rerr = renderMusic(value, o) if not dec then return nil, rerr end @@ -1367,7 +1284,6 @@ local o= opts or {} return buf end --- saveString(value, opts?) -> string | nil, Err function F.saveString(value, opts) local buf, err = F.save(value, nil, opts) if not buf then @@ -1376,7 +1292,6 @@ local buf, err = F.save(value, nil, opts) return buffer.tostring(buf), nil end --- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. function F.convert(src, format, opts) local o= opts or {} local value, err = F.load(src, o) @@ -1389,7 +1304,6 @@ local o= opts or {} return F.save(value, o.out, so) end --- detect(src, opts?) -> format name | nil, Err function F.detect(src, opts) local o= opts or {} local buf, ierr, name = Input.resolve(src, o, host) @@ -1411,7 +1325,6 @@ local o= opts or {} return entry.name, nil end --- formats(category?) -> { FormatInfo } (no format module is loaded) function F.formats(category) @@ -1424,7 +1337,6 @@ local out = {} return out end --- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info) function F.format(name) local e = find(name) if not e then @@ -1433,8 +1345,6 @@ local e = find(name) return module(e) end --- ------------------------------------------------------------------------------------------------ category facades --- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category local function with(opts, category) local o= (opts and{(table.clone(opts) )}or{{} })[1] o.category = category @@ -1459,9 +1369,6 @@ return F.formats(cat) end F.data.null = Types.null --- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; --- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel --- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. for _, fn in __iter({ "toBodies", "fromBodies", "tessellate" }) do local name= fn F.cad[name] = function(value, opts) @@ -1483,16 +1390,12 @@ local o= (opts and{(table.clone(opts) )}or{{} return a, b end end --- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker --- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module for _, fn in __iter({ "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" }) do local name= fn F.music[name] = function(...) return (F.ops.music )[name](...) end end --- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited --- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). F.video.fromImage = function(img, opts) if type(img) ~= "table" or img.kind ~= "image" then return nil, Err.new(Err.ARG, "fromImage: expected an Image") @@ -1518,18 +1421,11 @@ if type(img) ~= "table" or img.kind ~= "image" then local src = type(img.meta) == "table" and img.meta.source return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) end --- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence: --- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1) F.video.fromFrames = function(images, delays, opts) return Video.fromFrames(images, delays, opts) end --- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) F.video.codecs = Video --- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or --- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images --- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose --- image format is missing or broken keep image = nil and report an Err. F.model.loadTextures = function(scene, opts) local errs= {} if type(scene) ~= "table" or type(scene.textures) ~= "table" then @@ -1555,15 +1451,6 @@ local errs= {} return scene, errs end --- ------------------------------------------------------------------------------------------------ ops --- F.ops: editing on the standard types, loaded on first use. --- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... --- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... --- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves --- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, --- concat, fade, peak, rms --- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music) --- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector local OPS= { image = function() return ImageOps @@ -3724,19 +3611,12 @@ return list end __FILES["Types"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!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 = __include("core/Err") local Types = {} --- ------------------------------------------------------------------------------------------------ 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). @@ -3790,7 +3670,6 @@ Types.BPP = (table.freeze(BPP) )-- one frame of an animation (GIF, APNG, WebP): local Image = {} --- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8) function Image.new(width, height, format) local f= format or "rgba8" local size @@ -3811,12 +3690,10 @@ local f= format or "rgba8" meta = {}, } end --- bpp(format) -> bytes per pixel (nil for planar formats) function Image.bpp(format) return BPP[format] end Types.Image = Image --- ------------------------------------------------------------------------------------------------ Audio @@ -3834,8 +3711,6 @@ Types.Image = Image --- a fully decoded sound (F.load / F.audio.load)-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share) - @@ -3858,7 +3733,6 @@ return { } end Types.Audio = Audio --- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI) @@ -3887,12 +3761,6 @@ function Midi.new(division) return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } 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. @@ -4063,38 +3931,23 @@ Types.Midi = Midi - - - - - - - - - - - - - - - --- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) --- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no +-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index-- 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`.-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out +-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load.-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out + + + + + + + + + + + + + @@ -4102,7 +3955,6 @@ Types.Midi = Midi local Voxels = {} --- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) function Voxels.new(sx, sy, sz, palette) local pal = palette if not pal then @@ -4114,7 +3966,6 @@ local pal = palette end return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal , materials = nil } end --- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check function Voxels.get(v, x, y, z) return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) end @@ -4155,7 +4006,6 @@ return { meta = {}, } end --- the byte size of one component of an accessor type local COMPONENT_SIZE= { f32 = 4, f64 = 8, @@ -4170,8 +4020,7 @@ local COMPONENT_SIZE= { snorm8 = 1, snorm16 = 2, } -Types.COMPONENT_SIZE = (table.freeze(COMPONENT_SIZE) )-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer) - +Types.COMPONENT_SIZE = (table.freeze(COMPONENT_SIZE) ) function Scene.accessor(data, type, components, count) local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) return { data = d, type = type, components = components, count = count } @@ -4188,7 +4037,6 @@ return { doubleSided = false, } end --- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF) function Scene.fromPrimitive(prim, name) local s = Scene.new() s.meshes[1] = { name = name, primitives = { prim } } @@ -4198,8 +4046,6 @@ local s = Scene.new() 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) local d, n, t = acc.data, acc.components, acc.type local size = COMPONENT_SIZE[t] @@ -4262,7 +4108,6 @@ return f(d, i * stride + c * 4) 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, b) @@ -4278,7 +4123,6 @@ local m = table.create(16, 0) end return m end --- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S) function Scene.nodeMatrix(node) if node.matrix and #node.matrix == 16 then return node.matrix @@ -4307,8 +4151,6 @@ if node.matrix and #node.matrix == 16 then tx, ty, tz, 1, } end --- 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) local out= {} @@ -4352,7 +4194,6 @@ local out= {} end 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) @@ -4382,31 +4223,28 @@ end - - - - - - - - - - - - - - - - - - - - - --- ------------------------------------------------------------------------------------------------ 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. --- ------------------------------------------------------------------------------------------------ Archive-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline-- ------------------------------------------------------------------------------------------------ Font +-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline + + + + + + + + + + + + + + + + + + + @@ -4426,12 +4264,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= (setmetatable({}, { __mode = "k" }) )-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends) - +local objectMeta= (setmetatable({}, { __mode = "k" }) ) function Types.object(t, keys) local o= t or {} if getmetatable(o) == nil then @@ -4440,11 +4274,9 @@ local o= t or {} objectMeta[o] = keys or {} return o end --- isObject(v) -> true for tables made by Types.object function Types.isObject(v) 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, k, v) local order = objectMeta[o] if order and o[k] == nil and v ~= nil then @@ -4452,7 +4284,6 @@ function Types.set(o, k, v) 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, b) local ta, tb = type(a), type(b) if ta ~= tb then @@ -4465,8 +4296,6 @@ local ta, tb = type(a), type(b) 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, emptyIsMap) if Types.isObject(t) then return false @@ -4484,8 +4313,6 @@ if Types.isObject(t) then 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) local order = objectMeta[t] local out, seen = {}, {} @@ -4584,7 +4411,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) local d= {} for k, v in __iter(f) do @@ -4597,11 +4423,9 @@ or"time-local" })[1] end return (setmetatable(d, DateMeta) ) end --- is(v) -> true for Dates function DateLib.is(v) 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) if d.year then local y, m, dd = d.year, d.month or 0, d.day or 0 @@ -4622,8 +4446,7 @@ if d.year then 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) local d= {} local rest= s @@ -4679,13 +4502,11 @@ if oh_n > 23 or om_n > 59 then end return (DateLib.valid(d) and{(DateLib.new(d) )}or{nil })[1]end --- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC) function DateLib.toUnix(d) local days = (d.year and{(daysFromCivil(d.year, d.month or 1, d.day or 1) )}or{0 })[1] 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, offset) local off = offset or 0 local whole = math.floor(t) @@ -4724,7 +4545,6 @@ Types.Date = table.freeze(DateLib) --- ------------------------------------------------------------------------------------------------ Vector @@ -4757,7 +4577,6 @@ function Vector.new(width, height) return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } 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`). @@ -4776,16 +4595,13 @@ local Layered = {} function Layered.new(width, height) 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, image, x, y) 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, children) 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 @@ -4811,7 +4627,6 @@ function TileMap.new(width, height, tileWidth, tileHeight) return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } end Types.TileMap = TileMap --- ------------------------------------------------------------------------------------------------ Subtitles @@ -4820,7 +4635,6 @@ function Subtitles.new() return { kind = "subtitles", cues = {}, styles = {}, meta = {} } end Types.Subtitles = Subtitles --- ------------------------------------------------------------------------------------------------ Playlist -- the playlist-luau shape @@ -4845,7 +4659,6 @@ Types.Subtitles = Subtitles -- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to --- ------------------------------------------------------------------------------------------------ the format contract -- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) @@ -4881,14 +4694,9 @@ return Types end __FILES["archive/7z"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose --- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) --- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / --- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, --- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, --- Windows / Unix attributes, folder and file CRC-32s (verified on read). --- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other --- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. +-- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA / +-- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s. +-- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -4980,8 +4788,7 @@ local p = ctx.base + 32 + s.packPos return p end -local function decodeFolder(ctx, s, f) -- coder -> first in / out stream index - +local function decodeFolder(ctx, s, f) local inBase, outBase = {}, {} local ni, no = 0, 0 for i, c in __iter(f.coders) do @@ -5012,7 +4819,6 @@ depth =depth+ 1 if size > ctx.maxBytes then return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) end - -- the coder's input: another coder's output, or a packed stream local inIdx = inBase[ci] local src, so, sl local bound = nil @@ -5174,7 +4980,6 @@ local o= opts or {} local s= parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false - -- folder caches and the substream -> folder map local cache= {} local subFolder, subOffset= {}, {} do @@ -5274,10 +5079,7 @@ return SevenZip end __FILES["archive/7z/Header"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): --- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / --- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and --- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +-- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info. local Text = __include("codecs/text/Text") local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -5780,8 +5582,6 @@ local p= { streams = nil, files = {}, encoded = nil } return p end --- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to --- decode and parse again. function Header.parse(b, o, n) local r = Bytes.reader(b, o, n) local ok, res = pcall(function() @@ -5806,16 +5606,9 @@ return Header end __FILES["archive/adf"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an --- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international, --- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through --- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the --- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked --- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...), --- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are --- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description --- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk --- images (use the partition contents), dircache blocks (not needed to read). +-- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables, +-- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1 +-- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -5896,7 +5689,6 @@ local function date(d, blk, off) return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + math.floor(u32(d, blk, off + 8) / 50)) + EPOCH end --- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables) local function dataBlocks(d, hdr, maxBlocks) local out = {} local blk = hdr @@ -6096,15 +5888,9 @@ return Adf end __FILES["archive/applesingle"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740): --- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2: --- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags). --- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the --- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name --- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds --- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with --- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS / --- MS-DOS / AFP info entries (kept in meta.entries as id + length). +-- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1), +-- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile. +-- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6288,15 +6074,9 @@ return AppleSingle end __FILES["archive/ar"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/" --- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard --- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not --- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their --- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and --- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed --- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and --- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written --- library needs ranlib), writing .deb control data (any entries write as a plain ar). +-- archive/ar: Unix ar ("!<arch>\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" +-- symbols) and BSD ("#1/<len>", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. +-- Not supported: thin archives ("!<thin>"), writing symbol tables or .deb control data. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6423,7 +6203,6 @@ local out= {} return out end --- control.tar[.ext] -> the control file's fields, or nil local function debControl(b, o, n, name, maxBytes) local ext = string.match(name, "^control%.tar%.?(%w*)$") local raw @@ -6472,7 +6251,7 @@ local o= opts or {} local variant = "gnu" local longNames= nil local symbols= nil - local offsets= {} -- header offset (from the start) -> member name + local offsets= {} local count = 0 local p = base + 8 while p < e do @@ -6570,7 +6349,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end a.meta.symbols = out end a.meta.source = { format = "ar", variant = variant } - -- Debian packages local list = a._entries if list[1] and list[1].name == "debian-binary" then a.meta.source.variant = "deb" @@ -6689,7 +6467,6 @@ local items = Archive.entries(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" }) function Ar.new() local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } @@ -6700,13 +6477,9 @@ return Ar end __FILES["archive/arj"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS, --- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style --- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type --- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM). --- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files, --- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those --- entries / calls). +-- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh +-- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files, +-- multi-volume archives, chapters, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6914,13 +6687,9 @@ return Arj end __FILES["archive/binhex"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name, --- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified: --- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a --- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file --- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter --- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with --- archive/macbinary), several files in one .hqx (only the first is read). +-- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as +-- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several +-- files in one .hqx (the first is read). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -6961,7 +6730,6 @@ local head = r:peek(2048) end -- ------------------------------------------------------------------------------------------------ decode --- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input) local function unhex(text, maxBytes) local banner = string.find(text, BANNER, 1, true) if not banner then @@ -7105,7 +6873,6 @@ local o= opts or {} body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) end local src = body:finish() - -- RLE90 local rle = Bytes.writer(buffer.len(src) + 16) local n = buffer.len(src) local i = 0 @@ -7159,7 +6926,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork function Binhex.new() local a = Archive.new("binhex", encoder) a.meta.source = { format = "binhex" } @@ -7170,11 +6936,8 @@ return Binhex end __FILES["archive/br"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar --- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data"). --- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number: --- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a --- low confidence, so the extension decides between candidates. +-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read. +-- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7248,10 +7011,8 @@ return Br end __FILES["archive/bz2"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated --- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), --- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported: --- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). +-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read, +-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7314,16 +7075,9 @@ return Bz2 end __FILES["archive/cab"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and --- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose --- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum --- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local --- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) --- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same --- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the --- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a --- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), --- signed / self-extracting stubs before the header. +-- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried +-- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one +-- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7369,8 +7123,7 @@ if r:peek(8) == "MSCF\0\0\0\0" then return 0 end -- ------------------------------------------------------------------------------------------------ decode --- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next --- cabinet (a block with cbUncomp 0) +-- a block with cbUncomp 0 runs into the next cabinet @@ -7410,7 +7163,6 @@ local list= {} return list, total, false end --- the decompressed data of a folder's blocks local function inflateFolder(buf, list, total, typ) local method = bit32.band(typ, 15) local out = buffer.create(total) @@ -7506,7 +7258,6 @@ local o= opts or {} flags = flags, reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, } - -- folders local folders= {} local methods = {} for i = 1, cFolders do @@ -7531,7 +7282,6 @@ local o= opts or {} if cFiles > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries files") end - -- the folder cache: the last decompressed folder local cachedIndex, cachedData, cachedRuns = 0, nil , false local function folderData(f) if cachedIndex == f.index then @@ -7548,7 +7298,6 @@ if cachedIndex == f.index then cachedIndex, cachedData, cachedRuns = f.index, data, runs == true return data, nil, runs end - -- files local fr = r:sub(coffFiles) for _ = 1, cFiles do local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() @@ -7621,7 +7370,6 @@ if spanned then end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) function Cab.encode(archive, opts) local o= opts or {} local compression = o.compression or "mszip" @@ -7649,7 +7397,6 @@ local o= opts or {} if total > 0x7FFF8000 then return nil, Err.new(Err.ARG, "more than 2 GB of data") end - -- the folder data, in 32 KB blocks local folder = buffer.create(total) local p = 0 for _, f in __iter(files) do @@ -7684,7 +7431,6 @@ if compression == "mszip" then s =s+ n end local blob = data:finish() - -- names and the file table local table_ = Bytes.writer(64 + #files * 32) local offset = 0 for _, f in __iter(files) do @@ -7732,7 +7478,6 @@ if compression == "mszip" then end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) function Cab.new() local a = Archive.new("cab", encode) a.meta.source = { format = "cab" } @@ -7745,16 +7490,14 @@ __FILES["archive/cab/Sum"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 --- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format --- description ([MS-CAB] 2.4, CFDATA.csum). +-- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most +-- significant first, then the cbData / cbUncomp word. local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift local Sum = {} --- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) function Sum.of(buf, off, len, seed) if off < 0 or len <= 0 or off + len > blen(buf) then return seed @@ -7778,7 +7521,6 @@ if off < 0 or len <= 0 or off + len > blen(buf) then return bxor(s, tail) end --- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) function Sum.block(buf, dataAt, cbData, cbUncomp) return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end @@ -7787,12 +7529,8 @@ return Sum end __FILES["archive/cpio"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the --- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc --- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters), --- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor, --- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1") --- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped). +-- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as +-- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -7941,7 +7679,6 @@ local items = Archive.entries(archive) rdevminor = num(e.rdevminor), }) end - -- opts.format may also be the api's format name ("cpio"): the variant default then local o= opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local own = (src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") and{src.variant }or{"newc" @@ -7950,7 +7687,6 @@ local items = Archive.entries(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write() function CpioFormat.new() local a = Archive.new("cpio", encode) a.meta.source = { format = "cpio" } @@ -7961,16 +7697,9 @@ return CpioFormat end __FILES["archive/d64"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info --- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and --- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are --- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are --- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII --- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the --- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any --- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS --- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers' --- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents. +-- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names +-- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as +-- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8091,7 +7820,6 @@ local function encoder(a, o) return D64.encode(a, o) end --- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops local function chain(b, base, geo, t, s) local w = Bytes.writer() local seen= {} @@ -8136,7 +7864,6 @@ local o= opts or {} a.meta.tracks = geo.tracks a.meta.errorInfo = r:size() ~= geo.total a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } - -- the directory chain local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) local seen= {} local count = 0 @@ -8197,8 +7924,7 @@ end -- ------------------------------------------------------------------------------------------------ encode -- BAM layout per variant: where each track's free count + bitmap lives -local function bamEntry(geo, img, t) -- returns (offset of the free count, offset of the bitmap, bitmap bytes) - +local function bamEntry(geo, img, t) local dir = geo.offsets[geo.dirTrack] if geo.kind == "d81" then local side = t <= 40 and 1 or 2 @@ -8248,7 +7974,6 @@ local o= opts or {} local function pad16(s) return s .. string.rep("\160", 16 - #s) end - -- header / BAM local firstDir if variant == "d81" then buffer.writestring(img, dir, "\40\3\68\0") @@ -8375,7 +8100,6 @@ while ti <= #order do end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" }) function D64.new(variant) local a = Archive.new("d64", encoder) a.meta.variant = variant or "d64" @@ -8387,12 +8111,9 @@ return D64 end __FILES["archive/fat"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the --- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 --- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the --- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy --- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a --- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. +-- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat. +-- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and +-- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8502,7 +8223,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) function FatFormat.new() local a = Archive.new("fat", encoder) a.meta.source = { format = "fat" } @@ -8513,11 +8233,9 @@ return FatFormat end __FILES["archive/grp"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, --- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive --- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they --- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. --- Not supported: the "GRP 2" / RFF / SSI variants. +-- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data), +-- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12 +-- bytes). Not supported: the "GRP 2" / RFF / SSI variants. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8619,7 +8337,6 @@ local items, err = Archive.collect(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty GRP Archive: a:add(name, data); a:write() function Grp.new() local a = Archive.new("grp", encode) a.meta.source = { format = "grp" } @@ -8630,11 +8347,9 @@ return Grp end __FILES["archive/gzip"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the --- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d --- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive --- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the --- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification. +-- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate). +-- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz). +-- Not supported: FHCRC verification. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8667,7 +8382,6 @@ return r:peek(3) == "\31\139\8" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) local function header(b, o, e) local h= {} if o + 10 > e then @@ -8802,7 +8516,6 @@ local name= o.name end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) function Gzip.new(data, name) local a = Archive.new("gzip", function(arc, o) return Gzip.encode(arc, o) @@ -8819,14 +8532,9 @@ return Gzip end __FILES["archive/iso"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660: --- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories; --- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files. --- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts --- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El --- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one. --- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored --- bytes), multi-session images (the first session). +-- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet, +-- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files +-- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8896,16 +8604,9 @@ return Iso end __FILES["archive/lha"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their --- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS --- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, --- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. --- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower --- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header --- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu --- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), --- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or --- at the first header found in the first 64 KB). +-- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3, +-- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2, +-- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -8955,7 +8656,7 @@ if isHeader(r:peek(22)) then end -- ------------------------------------------------------------------------------------------------ decode --- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) +-- "." / ".." collapsed as lhasa does local function path(s) s = string.gsub(s, "[\\\255]", "/") local parts = {} @@ -8967,7 +8668,6 @@ s = string.gsub(s, "[\\\255]", "/") return table.concat(parts, "/") .. (string.sub(s, -1) == "/" and #parts > 0 and"/" or"") end --- the extended headers from offset p (size field width w), until a zero size; returns the end offset @@ -9035,7 +8735,6 @@ local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } --- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker local function header(r, p) local limit = r:size() if p >= limit or r:sub(p, 1):u8() == 0 then @@ -9138,7 +8837,6 @@ local o= opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local p = 0 - -- a self-extracting stub: find the first header if not isHeader(r:peek(22)) then local head = r:peek(65536) local at = nil @@ -9280,7 +8978,7 @@ local items = Archive.entries(value) dirPart, base = full .. "/", "" end local h = Bytes.writer() - h:u16le(0) -- total size, patched + h:u16le(0) h:string(e.dir and"-lhd-" or"-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) @@ -9321,7 +9019,6 @@ local items = Archive.entries(value) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) function Lha.new() local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } @@ -9332,15 +9029,9 @@ return Lha end __FILES["archive/lz4"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the --- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api --- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy --- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed --- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified --- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks --- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; --- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: --- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. +-- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable +-- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes +-- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9402,7 +9093,6 @@ local function skippable(m) return m >= 0x184D2A50 and m <= 0x184D2A5F end --- room for k more bytes in the output (doubling, up to max) | false local function room(out, k) @@ -9418,7 +9108,6 @@ local need = out.n + k return true end --- one LZ4 frame at p -> the input offset after it | nil, Err local function frame(b, p, e, out, verify) if p + 7 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) @@ -9543,7 +9232,6 @@ local q = p + 4 return q, nil end --- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err function Lz4Format.decompress(src, offset, length, opts) local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then @@ -9613,7 +9301,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ encode --- compress(data, opts?) -> one LZ4 frame | nil, Err function Lz4Format.compress(data, opts) local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) if not b then @@ -9674,7 +9361,6 @@ local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) return w:finish(), nil end --- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame function Lz4Format.encode(value, opts) local data, err = Archive.streamData(value) if not data then @@ -9687,13 +9373,9 @@ return Lz4Format end __FILES["archive/macbinary"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags, --- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III --- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its --- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry --- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / --- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the --- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped). +-- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III +-- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile. +-- Supports: read, write III. Not supported: the secondary header's content (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9713,7 +9395,6 @@ local MacBinary = { } -- ------------------------------------------------------------------------------------------------ sniff --- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o @@ -9890,18 +9571,9 @@ return MacBinary end __FILES["archive/mpq"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the --- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset --- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block --- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block --- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded --- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 --- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks --- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive --- Format", and StormLib's documentation); no code taken. --- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET --- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, --- writing. +-- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports: +-- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib / +-- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -9976,7 +9648,6 @@ local out = buffer.create(want) return out, nil end --- one compressed sector (mask byte first) -> want bytes local function decompress(b, at, n, want) if n < 1 then return nil, Err.new(Err.CORRUPT, "empty compressed sector") @@ -10040,7 +9711,6 @@ local copy = buffer.create(len) return cur, nil end --- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) local function readFile(b, limit, blk, at, name, sectorSize, maxBytes) @@ -10141,7 +9811,6 @@ local function encode(_archive, _opts) return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") end --- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil local function findHeader(r) local size = r.limit - r.base local p = 0 @@ -10219,7 +9888,6 @@ local found = findHeader(r) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local mask = hashCount - 1 local pow2 = band(hashCount, mask) == 0 - -- lookup(name) -> block index (1-based) | nil local function lookup(name) local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) local start = (pow2 and{(band(h0, mask) )}or{(h0 % hashCount @@ -10243,7 +9911,6 @@ local f = blocks[bi].flags local blk = blocks[bi] return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) end - -- names: (listfile) and opts.names local names= {} for _, internal in __iter({ "(attributes)", "(signature)", "(user data)" }) do table.insert(names, internal) @@ -10304,7 +9971,6 @@ return blockData(bi, name) end -- ------------------------------------------------------------------------------------------------ extras --- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) Mpq.hash = Crypt.hash return Mpq @@ -10312,10 +9978,8 @@ end __FILES["archive/mpq/Crypt"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file --- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois --- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every --- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +-- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and +-- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32. local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot @@ -10338,7 +10002,7 @@ do end end --- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +-- name hash: ASCII upper case, '/' as '\' function Crypt.hash(name, kind) local s1, s2 = 0x7FED7FED, 0xEEEEEEEE local base = kind * 0x100 @@ -10355,7 +10019,7 @@ local s1, s2 = 0x7FED7FED, 0xEEEEEEEE return s1 end --- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +-- whole u32s; a trailing partial word is left as is function Crypt.decrypt(buf, at, n, key) local s2 = 0xEEEEEEEE local k = key % TWO32 @@ -10369,7 +10033,7 @@ function Crypt.decrypt(buf, at, n, key) end end --- base name of an archived path (the file key uses it) +-- the file key uses the base name function Crypt.baseName(name) return string.match(name, "([^\\/]*)$") or name end @@ -10378,11 +10042,9 @@ return Crypt end __FILES["archive/pak"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the --- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored --- bytes) and written from any Archive value. Written from the format description in the Quake source release --- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. --- Not supported: Daikatana's compressed PAK entries. +-- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte +-- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read +-- (lazy), write. Not supported: Daikatana's compressed entries. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10504,7 +10166,6 @@ local items, err = Archive.collect(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() function Pak.new(variant) local a = Archive.new("pak", encode) a.meta.source = { format = "pak", variant = variant or "quake" } @@ -10515,15 +10176,9 @@ return Pak end __FILES["archive/rpm"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature --- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in --- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with --- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload --- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed --- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not --- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package --- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio" --- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms. +-- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte +-- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed. +-- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10555,7 +10210,6 @@ local LEAD_MAGIC = "\237\171\238\219" local HEADER_MAGIC = "\142\173\232\1" local RPMFILE_GHOST = 64 --- the tags meta.rpm names local NAMES= { [1000] = "name", [1001] = "version", @@ -10589,7 +10243,6 @@ return r:peek(4) == LEAD_MAGIC and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- a header structure at p -> { [tag] = value }, end offset | nil, Err local function header(b, p, e) if p + 16 > e then return nil, Err.new(Err.TRUNCATED, "header past the end", p) @@ -10662,7 +10315,6 @@ if p + 16 > e then return tags, se end --- the file list of the header: { name, size, mode, mtime, link, user, group, flags } local function files(tags) local names= {} local bn, dn, di = tags[1117], tags[1118], tags[1116] @@ -10697,7 +10349,6 @@ local function strip(name) return (string.gsub(name, "^%.?/+", "")) end --- the payload: decompressed, then its cpio entries by stripped name local function payload(b, p, e, compressor, o) local n = e - p local opts= { maxBytes = o.maxBytes or 2 ^ 30 } @@ -10829,7 +10480,6 @@ __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end -- ------------------------------------------------------------------------------------------------ extras --- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err function Rpm.cpio(r, opts) local a, err = Rpm.decode(r, opts) if not a then @@ -10850,11 +10500,8 @@ return Rpm end __FILES["archive/tar"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value --- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + --- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which --- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). --- Not supported: sparse files, multi-volume archives. +-- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any +-- Archive. Not supported: sparse files, multi-volume archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -10961,7 +10608,6 @@ local items = Archive.entries(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() function TarFormat.new() local a = Archive.new("tar", encode) a.meta.source = { format = "tar" } @@ -10972,13 +10618,9 @@ return TarFormat end __FILES["archive/uu"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin <mode> <name>" block of a --- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode); --- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each --- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and --- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils --- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings --- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex). +-- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block); +-- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings +-- split over several files, yEnc (archive/yenc), BinHex (archive/binhex). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -11023,7 +10665,6 @@ local head = r:peek(4096) end -- ------------------------------------------------------------------------------------------------ decode --- the value of character c in a variant, or nil local function value(c, xx) if xx then return XX_VALUE[c] @@ -11034,7 +10675,6 @@ if xx then return nil end --- does a data line fit the variant: every character valid and the length matching the count character local function fits(line, xx) local n = value(string.byte(line, 1) or 0, xx) if not n then @@ -11052,7 +10692,6 @@ local n = value(string.byte(line, 1) or 0, xx) return true end --- decode the uu / xx lines of a block into a buffer (nil, message on a bad line) local function decodeLines(lines, xx, maxBytes) local total = 0 for _, l in __iter(lines) do @@ -11239,7 +10878,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant }) function Uu.new() local a = Archive.new("uu", encoder) a.meta.source = { format = "uu" } @@ -11250,15 +10888,9 @@ return Uu end __FILES["archive/vpk"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the --- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes --- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the --- numbered part files "<name>_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes --- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's --- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), --- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the --- Valve Developer Community VPK file format page; no code taken. --- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. +-- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, +-- embedded (index 0x7fff) or part-file data ("<name>_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file +-- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -11306,7 +10938,6 @@ local function encode(archive, opts) return Vpk.encode(archive, opts) end --- the part file `index` as a buffer (cached per archive) local function partLoader(opts) local cache= {} local prefix = "pak01" @@ -11558,7 +11189,6 @@ local items, err = Archive.collect(archive) end -- ------------------------------------------------------------------------------------------------ extras --- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() function Vpk.new(version) local a = Archive.new("vpk", encode) a.meta.source = { format = "vpk", version = version or 2 } @@ -11569,22 +11199,9 @@ return Vpk end __FILES["archive/wad"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the --- standard Archive and written from any Archive value, plus the lumps as game data: --- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map --- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer --- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image --- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) --- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) --- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) --- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene --- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) --- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps --- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again --- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom --- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. --- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, --- big-endian (Jaguar) WADs, compressed Jaguar lumps. +-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, +-- palettes, pictures, wall textures and maps. Entry names: "<map>/<lump>", repeats "<name>~<n>". Not supported: UDMF +-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -11709,7 +11326,6 @@ local kind = r:string(4) if isMapMarker then map, udmf = name, nextName == "TEXTMAP" end - -- namespaces local marker= false local pre = string.match(name, "^(%w+)_START$") local post = string.match(name, "^(%w+)_END$") @@ -11785,7 +11401,7 @@ local function info(a) return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil end --- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +-- the last lump named name (PWAD order: later lumps override) local function find(w, name, ns) local up = string.upper(name) local best= nil @@ -11808,20 +11424,17 @@ local up = string.upper(name) return best end --- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() function Wad.new(kind) local a = Archive.new("wad", encode) a.meta.source = { format = "wad", type = kind or "PWAD" } return a end --- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) function Wad.lumps(a) local w = info(a) return w and w.lumps end --- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err function Wad.palette(a, index) local w = info(a) if not w then @@ -11835,8 +11448,6 @@ local w = info(a) return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil end --- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) --- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. function Wad.image(a, name, opts) local w = info(a) if not w then @@ -11877,7 +11488,6 @@ local w = info(a) return img, nil end --- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } local function textureDefs(w) if w.textures then return w.textures @@ -11929,7 +11539,6 @@ if w.textures then return defs end --- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) function Wad.texture(a, name, opts) local w = info(a) if not w then @@ -11953,7 +11562,6 @@ local w = info(a) return img, nil end --- maps(a) -> { map names } in file order function Wad.maps(a) local w = info(a) local out= {} @@ -11969,7 +11577,6 @@ local w = info(a) return out end --- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) function Wad.mapData(a, name) local w = info(a) if not w then @@ -11995,9 +11602,6 @@ local w = info(a) return m, nil end --- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and --- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes --- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData function Wad.map(a, name, opts) local m, err = Wad.mapData(a, name) if not m then @@ -12045,14 +11649,9 @@ return Wad end __FILES["archive/wad/Map"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, --- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a --- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with --- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the --- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one --- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z --- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not --- supported. +-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with +-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and +-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP). local Types = __include("Types") local Polygon = __include("codecs/model/Polygon") @@ -12061,9 +11660,8 @@ local Map = {} local Scene = Types.Scene local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 local writef32, writeu32 = buffer.writef32, buffer.writeu32 --- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows --- ------------------------------------------------------------------------------------------------ parse +-- ------------------------------------------------------------------------------------------------ parse @@ -12092,7 +11690,6 @@ local function side(v) return (v == 0xFFFF and{nil }or{(v + 1 )})[1]end --- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) function Map.parse(lumps, hexen) for _, k in __iter({ "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" }) do if not lumps[k] then @@ -12190,9 +11787,8 @@ for _, k in __iter({ "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" }) do end -- ------------------------------------------------------------------------------------------------ sector outlines --- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; --- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; --- chains that do not close are dropped +-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest +-- right turn at forks; unclosed chains dropped local function loops(m) local edges= {} local nv = math.floor(#m.vertices / 2 @@ -12293,7 +11889,6 @@ end local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 --- scene(m, tex, name) -> Scene function Map.scene(m, tex, name) local batches= {} local order= {} @@ -12315,8 +11910,7 @@ local key = kind .. ":" .. tname end local V = m.vertices local nv = math.floor(#V / 2 -) -- floors and ceilings - local secLoops = loops(m) +) local secLoops = loops(m) for sec, ls in __iter(secLoops) do local s = m.sectors[sec] local flat= {} @@ -12347,7 +11941,6 @@ local key = kind .. ":" .. tname end end end - -- walls local function quad(tname, x1, y1, x2, y2, zb, zt, xoff, len, texTop, yoff) if tname == "-" or tname == "" or zt <= zb then return @@ -12409,7 +12002,6 @@ local key = kind .. ":" .. tname end end end - -- the scene local scene = Scene.new() scene.meta.up = "z" local mesh= { name = name, primitives = {} } @@ -12456,7 +12048,6 @@ local key = kind .. ":" .. tname table.insert(scene.meshes, mesh) scene.nodes[1] = { name = name, children = {}, mesh = 1 } scene.roots[1] = 1 - -- things, on the floor of the sector under them for i, th in __iter(m.things) do local z = th.z or 0 for sec, ls in __iter(secLoops) do @@ -12489,17 +12080,13 @@ end __FILES["archive/wad/Picture"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column --- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of --- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) --- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). --- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's --- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +-- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: +-- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c; +-- no code taken. Transparent pixels are 0. local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 local Picture = {} --- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) function Picture.header(b, at, n) if n < 8 then return nil, 0, 0, 0 @@ -12517,7 +12104,6 @@ if n < 8 then return w, h, readi16(b, at + 4), readi16(b, at + 6) end --- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) function Picture.decode(b, at, n, pal, out, w, h) local stop = at + n for x = 0, w - 1 do @@ -12552,7 +12138,6 @@ local stop = at + n return true, nil end --- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) function Picture.flatSize(n) if n == 4096 then return 64, 64 @@ -12573,15 +12158,12 @@ if n == 4096 then return nil, 0 end --- flat(b, at, w, h, pal, out): raw indexes, row by row function Picture.flat(b, at, w, h, pal, out) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end --- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), --- clipped (composite wall textures from patches) function Picture.blit(src, sw, sh, dst, dw, dh, ox, oy) local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do @@ -12599,12 +12181,9 @@ return Picture end __FILES["archive/xz"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one --- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block --- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters +-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). +-- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ -- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. --- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true: --- the api unwraps an inner archive (a .tar.xz loads as the tar). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12702,13 +12281,9 @@ return Xz end __FILES["archive/yenc"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive: --- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart --- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified --- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a --- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one --- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space --- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first). +-- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text +-- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a +-- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -12756,7 +12331,6 @@ local f= {} return f end --- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out) local function decodeData(src, i, j, out, o) local lim = buffer.len(out) local esc = false @@ -12781,7 +12355,6 @@ __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end return o end --- count the decoded bytes of the data lines [i, j) local function countData(src, i, j) local n, esc = 0, false for p = i, j - 1 do @@ -12970,7 +12543,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line }) function Yenc.new() local a = Archive.new("yenc", encoder) a.meta.source = { format = "yenc" } @@ -12981,11 +12553,9 @@ return Yenc end __FILES["archive/z"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one --- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a --- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed, --- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is --- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files. +-- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one +-- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z). +-- Not supported: pack (.z, 1F 1E) and compact (1F FF) files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13021,7 +12591,6 @@ if r:peek(2) ~= "\31\157" then end -- ------------------------------------------------------------------------------------------------ decode --- the entry name: the file name without .Z; .taz / .tz name a tar local function entryName(opts) local name = Archive.streamName(opts, { "z" }) local stem, ext = string.match(name, "^(.+)%.(%w+)$") @@ -13066,7 +12635,6 @@ local data, err = Archive.streamData(value) end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a .Z Archive holding one entry function Z.new(data, name) local a = Archive.new("z", encode) a.meta.stream = true @@ -13081,20 +12649,9 @@ return Z end __FILES["archive/zip"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. --- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new --- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, --- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated --- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. --- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, --- LZMA, zstd entries are listed but not readable), multi-disk archives. --- --- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) --- for _, e in a:list() do print(e.name, e.size, e.method) end --- local data = a:read("dir/file.txt") --- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } --- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) --- local b = Zip.create() -- an empty archive +-- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer. +-- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names; +-- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13160,7 +12717,6 @@ local s = r:peek(4) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Archive | nil, Err function Zip.decode(r, opts) local zip, err = Container.open(r) if not zip then @@ -13169,14 +12725,11 @@ local zip, err = Container.open(r) return new(zip, not (opts and opts.verify == false)), nil end --- create() -> an empty Archive function Zip.create() return new(nil, true) end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written --- here), or a plain table { [name] = buffer | string }. function Zip.encode(value, opts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") @@ -13214,9 +12767,7 @@ if type(value) ~= "table" then end -- ------------------------------------------------------------------------------------------------ extras --- the Archive methods (Types.Archive) --- list() -> { ArchiveEntry } in archive order (+ crc32, comment) function Archive.list(self) local out = {} for _, name in __iter(self._order) do @@ -13247,7 +12798,6 @@ local out = {} return out end --- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup function Archive.read(self, name) if type(name) ~= "string" then return nil, Err.new(Err.ARG, "read: name must be a string") @@ -13270,7 +12820,6 @@ if type(name) ~= "string" then return nil, Err.new(Err.ARG, "no entry " .. name) end --- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") function Archive.add(self, name, data, opts) local b= (type(data) == "string" and{(buffer.fromstring(data) )}or{(type(data) == "buffer" and{data }or{(buffer.create(0) )})[1]})[1] if self._items[name] == nil then @@ -13279,7 +12828,6 @@ function Archive.add(self, name, data, opts) self._items[name] = { data = b, opts = opts or {} } end --- remove(name) -> true when there was such an entry function Archive.remove(self, name) if self._items[name] == nil then return false @@ -13292,7 +12840,6 @@ if self._items[name] == nil then return true end --- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are function Archive.write(self, opts) local w = Container.writer() for _, name in __iter(self._order) do @@ -13321,12 +12868,9 @@ return Zip end __FILES["archive/zoo"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of --- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers), --- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit --- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read --- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not --- supported: writing, file generations beyond keeping the newest (older versions of a name get ";<version>"). +-- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW +-- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the +-- newest (older versions of a name get ";<version>"). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13520,9 +13064,8 @@ return Zoo end __FILES["archive/zst"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded --- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else --- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. +-- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd). +-- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data". -- Not supported: dictionaries, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -13585,10 +13128,9 @@ return Zst end __FILES["audio/aac"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams --- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected --- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by --- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8 +-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its +-- AAC-LC core. Not supported: writing, ADIF, LATM. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13616,7 +13158,6 @@ local AacFormat = { local readu8 = buffer.readu8 --- the size of an ID3v2 tag at p (0 if none) local function id3Size(b, p, limit) if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 @@ -13629,7 +13170,6 @@ if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 10 + s + footer end --- a few ID3v2.3 / 2.4 text frames -> tags local ID3_TAGS= { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", @@ -13680,7 +13220,6 @@ local b, p, limit = r.buf, r.pos, r.limit if not h then return 0 end - -- a second header right after the first makes it certain local h2 = Aac.adts(b, p + h.frameSize, limit) if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then return 0.9 @@ -13689,7 +13228,6 @@ local b, p, limit = r.buf, r.pos, r.limit end -- ------------------------------------------------------------------------------------------------ decode --- the frame index: offsets of every ADTS frame (resyncing over garbage) local function index(r, maxFrames) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) @@ -13698,14 +13236,14 @@ local b, limit = r.buf, r.limit while p + 7 <= limit do local __DARKLUA_CONTINUE_4=false repeat local h = Aac.adts(b, p, limit) if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then - h = nil -- a false sync inside the data + h = nil end if not h then p =p+ 1 __DARKLUA_CONTINUE_4=true break end if p + h.frameSize > limit then - break -- a truncated last frame + break end if not first then first = h @@ -13764,7 +13302,7 @@ local sr = d.sampleRate tags = tags, codec = "aac", } - -- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking + -- 1024 samples per ADTS frame; one frame of pre-roll for the overlap return Stream.packets(out, { count = nframes, start = function(i) @@ -13796,12 +13334,9 @@ return AacFormat end __FILES["audio/ac3"] = function() --!strict --- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through --- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) --- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block --- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and --- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). --- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no +-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default. +-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13822,7 +13357,7 @@ local Ac3Format = { } -- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ sniff --- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) +-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format @@ -13844,7 +13379,7 @@ local b, p, limit = r.buf, r.pos, r.limit end -- ------------------------------------------------------------------------------------------------ decode --- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +-- a header counts when the next one follows it, or the data ends local function index(r, maxFrames) local b, limit = r.buf, r.limit local p = r.base @@ -13858,7 +13393,7 @@ local __DARKLUA_CONTINUE_1=false repeat local h = Ac3.header(b, p, limit) if h and not first and p + h.frameSize + 8 <= limit then local h2 = Ac3.header(b, p + h.frameSize, limit) if not h2 then - h = nil -- a false sync word + h = nil end end if not h then @@ -13874,7 +13409,7 @@ __DARKLUA_CONTINUE_1=true break end end if p + h.frameSize > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, h.frameSize) @@ -13945,22 +13480,10 @@ return Ac3Format end __FILES["audio/adpcm"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in --- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by --- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such --- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs --- here are the layouts those containers use: --- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first --- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order --- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) --- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) --- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime --- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) --- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients --- live in a header: see audio/brstm and audio/adx). --- --- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) --- local raw = Adpcm.encode(a, { codec = "ima" }) +-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts. +-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt": +-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms. +-- Not supported: raw DSP / ADX (their coefficients live in a header). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -13997,7 +13520,7 @@ local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = tru -- ------------------------------------------------------------------------------------------------ sniff function Raw.sniff(_r) -return 0 -- no header: found by extension or opts.format only +return 0 end -- ------------------------------------------------------------------------------------------------ decode @@ -14102,17 +13625,9 @@ return Raw end __FILES["audio/adx"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in --- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), --- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder --- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), --- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, --- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and --- exponential (4) encoding types, AHX. --- --- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) --- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) +-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop +-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14341,13 +13856,9 @@ return Adx end __FILES["audio/aiff"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. --- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw --- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated --- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / --- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; --- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, --- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. +-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos / +-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit, +-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14377,12 +13888,10 @@ local Aiff = { - local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } local AIFC_VERSION = 0xA2805140 --- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) local function ext80(b, o) local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) local hi = bit32.byteswap(buffer.readu32(b, o + 2)) @@ -14398,7 +13907,6 @@ local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) return (se >= 0x8000 and{(-v )}or{v })[1]end --- the 10 bytes of x (> 0) as an 80-bit extended float local function writeExt80(w, x) if x <= 0 or x ~= x then w:fill(0, 10) @@ -14411,7 +13919,7 @@ local function writeExt80(w, x) while x < 2 ^ e do e =e- 1 end - local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local m = x * 2 ^ (63 - e) local hi = math.floor(m / 4294967296) local lo = m - hi * 4294967296 w:u16be(e + 16383) @@ -14419,7 +13927,6 @@ local function writeExt80(w, x) w:u32be(math.floor(lo)) end --- the sample format of a COMM chunk: Pcm format name | nil, message local function sampleFormat(comp, bits) if comp == "NONE" or comp == "twos" or comp == "" then if bits >= 1 and bits <= 8 then @@ -14460,7 +13967,7 @@ if comp == "NONE" or comp == "twos" or comp == "" then elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil elseif comp == "ima4" then - return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks + return "ima4", nil end return nil, "compression " .. string.format("%q", comp) end @@ -14474,7 +13981,6 @@ if r:remaining() < 12 or r:peek(4) ~= "FORM" then return (form == "AIFF" or form == "AIFC" )and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) @@ -14507,7 +14013,7 @@ local b = r.buf local ssnd= nil local ssndLen = 0 local tags= {} - -- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body) + -- a FORM size that undercounts still reads the last chunk's body for _, c in __iter(Chunks.walk(b, base + 12, limit, Chunks.IFF)) do local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start if p + 8 > formEnd then @@ -14592,7 +14098,6 @@ if fi.frames > 0 and not ssnd then return fi, nil end --- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err function Aiff.info(r) return parse(r) end @@ -14642,14 +14147,13 @@ local src, serr = Pcm.source(value) local aifc = o.aifc or comp ~= "NONE" local w = Bytes.writer(65536) w:string("FORM") - w:u32be(0) -- patched + w:u32be(0) w:string(aifc and"AIFC" or"AIFF") if aifc then w:string("FVER") w:u32be(4) w:u32be(AIFC_VERSION) end - -- text chunks from the tags for _, pair in __iter(TEXT_ORDER) do local id, key = pair[1], pair[2] local s = src.tags[key] @@ -14743,15 +14247,9 @@ return Aiff end __FILES["audio/ape"] = function() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict --- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), --- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end --- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). --- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 --- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. --- --- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 --- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them --- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause, +-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32 +-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14803,7 +14301,6 @@ local head = r:peek(4) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Ape.decode(r, opts) local dec, err = Ape.open(r, opts) if not dec then @@ -14818,7 +14315,6 @@ local limit = opts and opts.maxFrames or 2 ^ 28 end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Ape.open(r, opts) if type(r) == "buffer" then r = Bytes.reader(r ) @@ -14879,11 +14375,9 @@ return Ape end __FILES["audio/au"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. --- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), --- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); --- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). --- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7 +-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them. +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -14970,7 +14464,7 @@ local src, serr = Pcm.source(value) local w = Bytes.writer(65536) w:string(".snd") w:u32be(24 + alen) - w:u32be(0xFFFFFFFF) -- patched + w:u32be(0xFFFFFFFF) w:u32be(spec[1]) w:u32be(src.sampleRate) w:u32be(src.channels) @@ -15042,15 +14536,9 @@ return Au end __FILES["audio/brstm"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and --- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts --- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP --- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 --- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } --- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions --- (the whole stream plays), the track table (channels are not grouped). --- --- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) +-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255 +-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -15087,7 +14575,6 @@ local m = r:peek(4) return (bom == "\254\255" or bom == "\255\254" )and 1 or 0 end --- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect function Brstm.variant(r) local m = r:peek(4) return m == "RSTM" and"brstm" or(m == "CSTM" and"bcstm" or(m == "FSTM" and"bfstm" or nil @@ -15108,8 +14595,6 @@ local limit = opts and opts.maxFrames or 2 ^ 28 end -- ------------------------------------------------------------------------------------------------ open --- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file --- start); a read out of range records the error in .err and returns 0 local function view(r, be) local v = { err = nil } local size = r.limit - r.base @@ -15342,12 +14827,9 @@ return Brstm end __FILES["audio/caf"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear --- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, --- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown --- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / --- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: --- other compressed formats (UNSUPPORTED). +-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either +-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM +-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -15391,7 +14873,6 @@ for k, v in __iter(INFO_TAGS) do TAG_INFO[v] = k end --- mu-law / A-law -> linear 16-bit local ULAW, ALAW = table.create(256, 0), table.create(256, 0) for i = 0, 255 do local u = 255 - i @@ -15578,7 +15059,6 @@ if Caf.sniff(r) == 0 then end return p, nil end --- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err @@ -15676,7 +15156,6 @@ local f0 = (i - 1) * per } return src, nil end - -- packetised codecs local sizes = p.packets if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then @@ -15848,7 +15327,6 @@ local function chunk(w, typ, size) w:i64be(size) end --- encode(audio | decoder, opts?) -> buffer | nil, Err function Caf.encode(value, opts) local o= opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -15866,7 +15344,6 @@ local o= opts or {} if ch < 1 or ch > 64 or sr <= 0 then return nil, Err.new(Err.ARG, "bad sample rate / channels") end - -- the source frames local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if not isAudio and type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") @@ -16012,21 +15489,9 @@ return Caf end __FILES["audio/flac"] = function() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict --- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, --- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. --- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals --- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame --- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in --- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels --- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 --- verification on decode, chained Ogg streams, Ogg FLAC output. --- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) --- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end --- local i32, n = dec:readInt(4096) -- bit-exact integer samples --- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every +-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata +-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -16092,7 +15557,6 @@ local head = r:peek(4) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Flac.decode(r, opts) local dec, err = Flac.open(r, opts) if not dec then @@ -16107,7 +15571,6 @@ local limit = opts and opts.maxFrames or 2 ^ 28 end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err function Flac.encode(value, opts) local src, serr = Pcm.source(value) if not src then @@ -16152,7 +15615,6 @@ local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.met end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Flac.open(r, opts) if type(r) == "buffer" then r = Bytes.reader(r ) @@ -16177,9 +15639,7 @@ __FILES["audio/flac/Meta"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 --- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is --- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d. local VorbisComment = __include("codecs/audio/VorbisComment") local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -16326,7 +15786,6 @@ if p + 8 > e then return pic end --- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) function Meta.parse(b, pos, len) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" @@ -16371,7 +15830,7 @@ if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then end end elseif typ == 4 then - vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + vorbisComment(b, p, e, info) elseif typ == 6 then local pic = picture(b, p, e) if pic then @@ -16402,11 +15861,7 @@ __FILES["audio/flac/Stream"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through --- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, --- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed --- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an --- injected module). Nothing throws: open returns nil, message, code. +-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author). local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") local Frame = __include("codecs/audio/Flac/Frame") @@ -16442,12 +15897,10 @@ local PAD = Frame.PAD local Dec = {} Dec.__index = Dec --- the sample number of a frame local function sampleOf(self, h) return (h.variable and{h.number }or{(h.number * self._nominal )})[1]end --- a header that also matches the stream (guards the sync search against false syncs) local function plausible(self, h) if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then return false @@ -16481,7 +15934,6 @@ local function ensure(self, n) end end --- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. local function decodeAt(self, pos) local b, len = self._b, self._len while true do @@ -16515,7 +15967,7 @@ local function pull(self, maxFrames, asInt, dst) local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then - want = 0 -- negative or NaN + want = 0 end want = math.min(want, math.floor(2 ^ 26 / ch)) -- keeps the output buffer under 256 MB local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 @@ -16560,29 +16012,23 @@ local ch = self.channels return out, got end --- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is --- reused when big enough. function Dec.read(self, maxFrames, out) return pull(self, maxFrames, false, out) end --- The same as interleaved i32 integer samples (bit-exact, right-aligned) function Dec.readInt(self, maxFrames, out) return pull(self, maxFrames, true, out) end --- seconds, sample frame of the next frame read() returns function Dec.position(self) local s = self._fs + self._cur return s / self.sampleRate, s end --- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets --- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. function Dec.seekSample(self, t) t = math.floor(tonumber(t) or 0) if not (t >= 0) then - t = 0 -- negative or NaN + t = 0 end if self.frames > 0 and t >= self.frames then self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 @@ -16629,7 +16075,7 @@ t = math.floor(tonumber(t) or 0) self._cur = t - self._fs return true elseif self._fs > t then - return false -- a hole in the stream: we are at the next frame + return false end pos = self._pos else @@ -16645,7 +16091,6 @@ function Dec.seek(self, seconds) return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end --- Find the total length from the last frame (when STREAMINFO does not give it) local function scanLength(self) local len = self._len local step = math.max(65536, 2 * self._si.maxFrameSize) @@ -16685,7 +16130,6 @@ local p = 0 return p end --- opts.crc16 = false skips the per-frame CRC-16 check function Stream.open(buf, base, srcLen, opts) local b, len, container if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then @@ -16785,11 +16229,9 @@ return Stream end __FILES["audio/m4a"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading --- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless --- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); --- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs --- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. +-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays +-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 +-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -16842,7 +16284,6 @@ local brand = IsoBmff.sniff(r) return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly end -- ------------------------------------------------------------------------------------------------ decode --- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats @@ -16907,7 +16348,6 @@ return d:decode(buf, off, len) return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") end --- open(r, opts?) -> Types.Decoder | nil, Err function M4a.open(r, opts) local o= opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) @@ -16941,7 +16381,6 @@ local pd, perr = packetDecoder(t) end local p = pd local channels, sr = p.channels, p.sampleRate - -- media ticks -> sample frames local tickScale = sr / t.timescale local gapless = o.gapless ~= false local skip = (gapless and{(math.floor(t.skip * tickScale + 0.5) )}or{0 @@ -17005,7 +16444,6 @@ return p.pcm }) end --- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) function M4a.decode(r, opts) local dec, err = M4a.open(r, opts) if not dec then @@ -17020,7 +16458,6 @@ local dec, err = M4a.open(r, opts) end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A function M4a.encode(value, opts) local o= opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -17040,7 +16477,6 @@ local depth = e.config.bitDepth local ints = table.create(fl * ch, 0) local floor = math.floor local readf32 = buffer.readf32 - -- frames from an Audio buffer or a streaming Decoder local src, srcFrames = nil , 0 local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if isAudio then @@ -17127,20 +16563,9 @@ return M4a end __FILES["audio/mp3"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf --- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 --- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / --- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync --- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III --- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from --- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel --- extension, CRC checks, VBR / Xing output. --- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, --- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) --- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) +-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of +-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless, +-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -17186,7 +16611,6 @@ local Mp3 = { local MAX_FRAMES = 2 ^ 31 -- ------------------------------------------------------------------------------------------------ sniff --- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on function Mp3.sniff(r) local b, p, lim = r.buf, r.pos, r.limit local id3 = false @@ -17215,7 +16639,6 @@ local b, p, lim = r.buf, r.pos, r.limit end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts) -> Types.Audio (the whole stream, through open) function Mp3.decode(r, opts) local dec, err = Mp3.open(r, opts) if not dec then @@ -17241,7 +16664,6 @@ local ID3_FRAMES = { { "composer", "TCOM" }, } --- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write local function id3Tag(tags) local w = Bytes.writer(256) local seen= {} @@ -17290,7 +16712,6 @@ local w = Bytes.writer(256) return out:finish() end --- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err function Mp3.encode(value, opts) local src, serr = Pcm.source(value) if not src then @@ -17302,9 +16723,7 @@ local src, serr = Pcm.source(value) return nil, Err.new(Err.ARG, "layer must be 2 or 3") end local Enc = (layer == 3 and{Encode3 }or{Encode2 -})[1] -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else - -- the highest); other input rates go through codecs/audio/Resample - local rate = o.sampleRate or src.sampleRate +})[1] local rate = o.sampleRate or src.sampleRate if o.sampleRate and not Enc.RATES[o.sampleRate] then return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) end @@ -17337,7 +16756,6 @@ local src, serr = Pcm.source(value) if layer == 2 and mode == "joint" then mode = "stereo" end - -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s local bitrate = o.bitrate or ((mpeg1 and{(layer == 3 and 128 or 192) }or{(layer == 3 and 64 or 96)})[1]) if type(bitrate) == "number" and bitrate >= 1000 then bitrate =bitrate/ 1000 @@ -17362,7 +16780,6 @@ local src, serr = Pcm.source(value) end -- ------------------------------------------------------------------------------------------------ open --- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment) local function stringTags(t) local out= {} for k, v in __iter(t) do @@ -17373,7 +16790,6 @@ local out= {} return out end --- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err function Mp3.open(r, opts) local b = r.buf if r.base ~= 0 or r.limit ~= buffer.len(b) then @@ -17401,7 +16817,7 @@ local b = r.buf end -- ------------------------------------------------------------------------------------------------ extras -Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) +Mp3.Tags = Tags return Mp3 end @@ -17409,10 +16825,7 @@ __FILES["audio/mp3/Index"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame --- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so --- it knows in advance which frames give output and where each one's samples land. That makes the total length --- exact and seeking sample-accurate. Never throws. +-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir. local Header = __include("codecs/audio/Mpa/Header") local Core = __include("codecs/audio/Mpa/Core") @@ -17448,7 +16861,6 @@ Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode - local function grow(b, n) @@ -17497,7 +16909,6 @@ local __DARKLUA_CONTINUE_1=false repeat local remaining = stop - pos pos =pos+ i end if fs < 4 or fs > Core.MAX_FRAME then - -- cannot happen with a well-formed header, but never index an impossible frame prev = -1 pos =pos+ max(fs, 1) __DARKLUA_CONTINUE_1=true break @@ -17604,8 +17015,7 @@ end __FILES["audio/mp3/Stream"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!optimize 2 --- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact --- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws. +-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author). local Core = __include("codecs/audio/Mpa/Core") local Index = __include("audio/mp3/Index") @@ -17619,7 +17029,6 @@ local Stream = {} local Decoder = {} Decoder.__index = Decoder --- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) @@ -17696,7 +17105,6 @@ local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels end --- decodes frames until one has samples inside [minAbs, endAbs); false at the end local function fill(self) local idx = self._idx local n = idx.n @@ -17731,9 +17139,6 @@ local idx = self._idx return false end --- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. --- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a --- smaller out is ignored. function Decoder.read(self, maxFrames, out) local ch = self.channels local want = tonumber(maxFrames) or 4096 @@ -17742,7 +17147,7 @@ local ch = self.channels end want = floor(max(0, min(want, self.frames - self._pos))) if out and buffer.len(out) < want * ch * 4 then - out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + out = nil end local dst = out or buffer.create(want * ch * 4) local got = 0 @@ -17767,8 +17172,6 @@ local ch = self.channels return dst, got end --- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier --- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. function Decoder.seek(self, seconds) local hz = self.sampleRate local target = floor((tonumber(seconds) or 0) * hz + 0.5) @@ -17776,7 +17179,6 @@ function Decoder.seek(self, seconds) self:seekFrame(target) end --- Seeks to a sample frame (0 .. frames). function Decoder.seekFrame(self, target) target = tonumber(target) or 0 if target ~= target then @@ -17794,7 +17196,6 @@ function Decoder.seekFrame(self, target) self._cur = n return end - -- last frame starting at or before abs local lo, hi = 0, n - 1 while lo < hi do local mid = math.floor((lo + hi + 1) / 2 @@ -17822,12 +17223,10 @@ function Decoder.seekFrame(self, target) self._cur = s end --- Current position: (seconds, sample frame) function Decoder.position(self) return self._pos / self.sampleRate, self._pos end --- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) function Decoder.readAll(self) return self:read(max(0, self.frames - self._pos)) end @@ -17839,9 +17238,7 @@ end __FILES["audio/mp3/Tags"] = function() local __compat = __compat local buffer, bit32, utf8, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.__iter --!strict --!optimize 2 --- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / --- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way --- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3. local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local ru8 = buffer.readu8 @@ -17936,7 +17333,6 @@ local out = {} return table.concat(out) end --- trim trailing NULs / spaces, join multi-value NUL separators with " / " local function clean(s) s = string.gsub(s, "[%z%s]+$", "") s = string.gsub(s, "%z+", " / ") @@ -18005,7 +17401,6 @@ local function setField(tags, id, text) })[1] end end --- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags local function parseV2(b, o, size, tags) local ver = ru8(b, o + 3) local flags = ru8(b, o + 5) @@ -18097,9 +17492,6 @@ local function v1String(b, o, n) return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) end --- Parses tags and returns (tags, audio start, audio end) for the buffer b. --- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?, --- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } function Tags.parse(b) local len = buffer.len(b) local tags= { raw = {} } @@ -18157,12 +17549,9 @@ return Tags end __FILES["audio/mpc"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec --- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / --- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking --- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags --- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: --- writing, SV4 - SV6 (UNSUPPORTED), chapters. +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono / +-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags, +-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18184,7 +17573,6 @@ local Mpc = { } -- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ constants --- the size of an ID3v2 tag at p (0 if none) @@ -18255,24 +17643,9 @@ return Mpc end __FILES["audio/opus"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a --- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK --- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). --- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, --- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms --- pre-roll), damaged files (concealment). Output is always 48 kHz f32. --- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant --- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. --- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics --- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). --- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an --- optional output buffer; decode() fully decodes to an Audio. --- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... --- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio --- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets --- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) +-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD: +-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC; +-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18319,7 +17692,7 @@ local DOWNMIX = { local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 local MAX_PACKET = 5760 -- 120 ms --- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. +-- OpusHead (RFC 7845 section 5.1) @@ -18383,8 +17756,7 @@ if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then return head, nil end --- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined --- with "; "), the raw fields +-- OpusTags (RFC 7845 section 5.2) local function parseTags(b, off, size) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then return "", {}, {} @@ -18429,7 +17801,6 @@ Opus.parseTags = parseTags Opus.SAMPLE_RATE = SAMPLE_RATE -- ------------------------------------------------------------------------------------------------ sniff --- 1 when the file starts with an Ogg page whose first packet is an OpusHead function Opus.sniff(r) if r:peek(4) ~= "OggS" then return 0 @@ -18442,7 +17813,6 @@ if r:peek(4) ~= "OggS" then end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) function Opus.decode(r, opts) local dec, err = Opus.open(r, opts) if not dec then @@ -18452,7 +17822,6 @@ local dec, err = Opus.open(r, opts) end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) function Opus.encode(value, opts) return Encode.encode(value, opts) end @@ -18461,7 +17830,6 @@ end local Stream = {} Stream.__index = Stream --- Decodes the next packet into the pending buffer. Returns false at the end of the stream. local function decodeNext(self) local p = self.demux:nextPacket(self.serial) if p == nil then @@ -18495,8 +17863,6 @@ local p = self.demux:nextPacket(self.serial) return true end --- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if --- given and big enough) is filled instead of a new buffer. function Stream.read(self, maxFrames, into) local ch = self.channels local mf = (type(maxFrames) == "number" and maxFrames == maxFrames and{maxFrames }or{0 @@ -18511,7 +17877,6 @@ local __DARKLUA_CONTINUE_4=false repeat if self.pendPos >= self.pendLen then break end end - -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) local s = self.pendStart + self.pendPos if s < self.next then self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) @@ -18536,17 +17901,15 @@ __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end buffer.copy(trimmed, 0, out, 0, got * ch * 4) out = trimmed end - self.endSample = self.next -- the stream ended early (truncated file) + self.endSample = self.next end return out, got end --- current playback position in seconds function Stream.position(self) return (self.next - self.preSkip) / SAMPLE_RATE end --- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll function Stream.seek(self, seconds) local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 })[1] local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) @@ -18571,7 +17934,6 @@ function Stream.seek(self, seconds) self.next = target end --- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) function Opus.open(r, opts) local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = false } or nil) if not demux then @@ -18659,11 +18021,7 @@ return Opus end __FILES["audio/opus/Encode"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/audio/Opus/CeltEncoder: CELT-only packets (TOC config 31: --- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + --- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at --- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in --- rosetta. +-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") @@ -18684,7 +18042,6 @@ local Encode = {} local floor = math.floor --- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value, opts) local o= opts or {} local src, serr = Pcm.source(value) @@ -18701,12 +18058,11 @@ local o= opts or {} end local bitrate = o.bitrate or 64000 * ch if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then - bitrate =bitrate* 1000 -- kbit/s + bitrate =bitrate* 1000 end if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end - -- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats if rate ~= 48000 then local rs, rerr = Resample.source(src, 48000) if not rs then @@ -18728,8 +18084,7 @@ local o= opts or {} local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY local packets = math.floor((n48 + preSkip + FRAME - 1) / FRAME -) -- zero padding to whole frames - for i = n48 * ch + 1, packets * FRAME * ch do +) for i = n48 * ch + 1, packets * FRAME * ch do pcm[i] = 0 end local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), ch == 2 and 40 or 20, 1275 - 1) @@ -18760,7 +18115,6 @@ local o= opts or {} tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) - -- audio local toc = 31 * 8 + (ch == 2 and 4 or 0) for p = 0, packets - 1 do local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) @@ -18778,15 +18132,9 @@ return Encode end __FILES["audio/qoa"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in --- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order --- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its --- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): --- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel --- count or rate change mid-stream (Err.UNSUPPORTED). --- --- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder --- local file = Qoa.encode(audio) +-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and +-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode, +-- 1-8 channels. Not supported: channel count or rate changes mid-stream. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18901,7 +18249,6 @@ if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, h.err end local buf = r.buf - -- the frame index: offsets, first frames local offs, starts = {}, {} local p, total = r.base + 8, 0 local ch, rate = 0, 0 @@ -18965,13 +18312,9 @@ return Qoa end __FILES["audio/tta"] = function() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict --- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the --- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). --- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. --- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. --- --- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt --- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24 +-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected +-- files, TTA2, ID3v2 contents, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -18993,7 +18336,6 @@ local Tta = { } -- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ sniff --- the size of an ID3v2 tag at the reader's start (0 when none) @@ -19020,7 +18362,6 @@ return r:peek(4, id3Size(r)) == "TTA1" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Tta.decode(r, opts) local dec, err = Tta.open(r, opts) if not dec then @@ -19035,7 +18376,6 @@ local limit = opts and opts.maxFrames or 2 ^ 28 end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Tta.open(r, opts) if type(r) == "buffer" then r = Bytes.reader(r ) @@ -19090,18 +18430,9 @@ return Tta end __FILES["audio/vag"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same --- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow --- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono --- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / --- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. --- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame --- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game --- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). --- --- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) --- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) +-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp / +-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -19235,8 +18566,7 @@ if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" an end -- ------------------------------------------------------------------------------------------------ open --- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end --- flag 3), or nil +-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3 local function findLoop(buf, p, frames, il, ch) local ls, le = -1, -1 for k = 0, frames - 1 do @@ -19323,13 +18653,9 @@ return Vag end __FILES["audio/voc"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. --- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), --- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit --- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played --- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version --- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM --- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). +-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9 +-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9 +-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -19397,7 +18723,6 @@ local b, base, limit = r.buf, r.base, r.limit local truncated = false local tags= {} local p = base + hsize - -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) local function add(at, bytes, fmt, ch, sr) if channels == 0 then channels, rate = ch, sr @@ -19501,7 +18826,7 @@ if channels == 0 then local n = s.frames * channels if s.fmt then Pcm.Convert.decode(b, s.at, s.fmt , n, a.samples, o) - end -- silence: the buffer is already zero + end o =o+ n * 4 end a.tags = tags @@ -19562,7 +18887,7 @@ local src, serr = Pcm.source(value) blockAt = w:tell() blockFrames = 0 w:u8(9) - w:u24le(0) -- patched + w:u24le(0) w:u32le(src.sampleRate) w:u8(spec[3]) w:u8(src.channels) @@ -19603,17 +18928,9 @@ return Voc end __FILES["audio/vorbis"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau --- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct, --- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last --- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). --- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, --- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level --- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic --- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook --- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since --- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. --- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing). +-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT, +-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels, +-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -19637,7 +18954,6 @@ local Vorbis = { } -- ------------------------------------------------------------------------------------------------ constants --- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels) @@ -19659,7 +18975,6 @@ local m = Pcm.WAVE_FROM_VORBIS[ch] return id end --- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err local function headers(h1, h2, h3) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then @@ -19702,7 +19017,6 @@ local dec, err = Vorbis.open(r, opts) end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err function Vorbis.encode(value, opts) local src, serr = Pcm.source(value) if not src then @@ -19734,7 +19048,6 @@ end local Stream = {} Stream.__index = Stream --- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) local function push(self, arrays, g0, count, hi) local lo = math.max(g0, self.startG, self.skipTo) if hi > g0 + count then @@ -19756,7 +19069,6 @@ local t = table.create(self.channels) return t end --- decode packets until something is queued; false at the end of the stream local function decodeMore(self) local reader, st = self.reader, self.st while not self.ended do @@ -19855,7 +19167,6 @@ function Stream.position(self) return (self.next - self.startG) / self.sampleRate end --- back to the first audio packet local function restart(self) local r = self.reader r:rewind() @@ -20034,11 +19345,7 @@ local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = fals end -- ------------------------------------------------------------------------------------------------ extras --- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three --- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. --- local pd = Vorbis.packetDecoder(h1, h2, h3) --- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] --- pd:reset() -- after a seek +-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data function Vorbis.packetDecoder(h1, h2, h3) local function pk(b) return { data = b, offset = 0, size = buffer.len(b) } @@ -20077,15 +19384,8 @@ __FILES["audio/vorbis/Encode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification --- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the --- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a --- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- --- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer --- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then --- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian --- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact --- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048), +-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths. local Mdct = __include("codecs/audio/Mdct") local Pcm = __include("codecs/audio/Pcm") local VorbisComment = __include("codecs/audio/VorbisComment") @@ -20163,7 +19463,6 @@ local n = 0 return n end -- ------------------------------------------------------------------------------------------------ codebooks --- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) @@ -20188,7 +19487,6 @@ local n = #w return lens end local minw = total * 2 ^ -20 - -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues local order = table.create(n, 0) for i = 1, n do order[i] = i @@ -20204,8 +19502,8 @@ if weight[a] ~= weight[b] then end return a < b end) - local q1, h1 = order, 1 -- leaves, ascending - local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local q1, h1 = order, 1 + local q2, h2, t2 = table.create(n, 0), 1, 0 local nextId = n local function pop() local a = (h1 <= n and{q1[h1] }or{nil @@ -20237,7 +19535,7 @@ end return lens end --- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +-- the spec's codeword assignment (lowest free leaf, in entry order) local function assign(lens) local codes = table.create(#lens, 0) local available = table.create(33, 0) @@ -20284,7 +19582,6 @@ local w = table.create(entries, 0) return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } end --- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) local function vqBook(dims, h, scale, s, zeroBoost) local values = 2 * h + 1 local entries = values ^ dims @@ -20378,7 +19675,6 @@ do table.insert(xs, x) end table.sort(xs) - -- bisection order over the sorted list local queue = { { 1, #xs } } local qh = 1 while qh <= #queue do @@ -20500,7 +19796,7 @@ local lo, hi = LOW[j], HIGH[j] end end end - return 0 -- unreachable for t in range; fall back to the prediction + return 0 end -- ------------------------------------------------------------------------------------------------ headers @@ -20620,7 +19916,6 @@ local w = newW(8192) return finish(w) end -- ------------------------------------------------------------------------------------------------ encoder --- the residue of one partition: vectors of each pass for class c @@ -20715,7 +20010,6 @@ for c = 1, ch do local k = 0 local lastWanted = -1 -- the last packet index needed (known once the input ends) while true do - -- shift in the next 1024 input samples (zeros past the end) for c = 1, ch do local fr = frame[c] table.move(fr, N2 + 1, N, 1) @@ -20754,8 +20048,6 @@ for i = 0, take - 1 do lastWanted = math.floor((total + N2 - 1) / N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) ) end -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) - -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) - -- MDCT per channel local energy = 0 for c = 1, ch do local fr = frame[c] @@ -20897,7 +20189,6 @@ local lo = (idx > 1 and{(math.floor((POSTS[SORTED[idx - 1] ] + x) / 2 ))}or{0 return mux:finish(), nil end --- the codebooks (tests check the Huffman lengths are a valid prefix code) Encode.BOOKS = BOOKS return Encode @@ -20905,19 +20196,9 @@ end __FILES["audio/wav"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!optimize 2 --- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no --- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. --- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE --- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF --- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). --- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when --- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, --- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. --- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. --- --- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames --- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio --- local file = Wav.encode(audio, { sampleFormat = "s24" }) +-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit, +-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end); +-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -21048,8 +20329,7 @@ Decoder.__index = Decoder -local function trimTag(s) -- strip trailing NULs / spaces - +local function trimTag(s) local e = #s while e > 0 do local c = string.byte(s, e) @@ -21071,7 +20351,6 @@ return Riff.sniff(r) == "WAVE" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole file function Wav.decode(r, opts) local dec, err = Wav.open(r, opts) if not dec then @@ -21096,7 +20375,6 @@ local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTY local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } local BLOCK = 65536 -- frames per data piece when streaming a Decoder --- the body of the encoder: { buffer } pieces of the file | nil, Err local function encodeParts(value, opts, asParts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") @@ -21217,19 +20495,15 @@ if type(value) ~= "table" then return w:finish({ parts = asParts }) end --- encode(audio or decoder, opts?) -> buffer | nil, Err function Wav.encode(value, opts) return encodeParts(value, opts, false) end --- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other --- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB function Wav.encodeParts(value, opts) return encodeParts(value, opts, true) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range function Wav.open(r, _opts) if type(r) == "buffer" or type(r) == "string" then r = Bytes.reader((type(r) == "string" and{(buffer.fromstring(r) )}or{r })[1]) @@ -21455,8 +20729,6 @@ if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then end -- ------------------------------------------------------------------------------------------------ extras --- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples --- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). function Decoder.read(self, maxFrames, out) local ch = self.channels local req = math.floor(tonumber(maxFrames) or 0) @@ -21486,7 +20758,6 @@ and{out self._pos =self._pos+ want return dst, want end - -- block formats: decode a block into the cache, copy out of it local spb, ba = self._spb, self.blockAlign local cache = self._cache local done = 0 @@ -21517,7 +20788,6 @@ local done = 0 return dst, done end --- Moves to a time in seconds (clamped to the stream). function Decoder.seek(self, seconds) local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) if f ~= f then @@ -21526,7 +20796,6 @@ function Decoder.seek(self, seconds) self._pos = math.clamp(f, 0, self.frames) end --- Moves to a frame index (clamped). function Decoder.seekFrame(self, frame) local f = math.floor(tonumber(frame) or 0) if f ~= f then @@ -21535,12 +20804,10 @@ function Decoder.seekFrame(self, frame) self._pos = math.clamp(f, 0, self.frames) end --- Current position in seconds. function Decoder.position(self) return self._pos / self.sampleRate end --- Current position in frames. function Decoder.tell(self) return self._pos end @@ -21551,10 +20818,7 @@ __FILES["audio/wav/Codecs"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The --- ADPCM block decoders moved to codecs/audio/Adpcm. --- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) --- only calls them with ranges it has checked against the source length and the output size. +-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 @@ -21563,8 +20827,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b local Codecs = {} --- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, --- from src[off] to dst (f32) starting at sample index d. +-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed function Codecs.int(src, off, dst, d, count, bytes, be) local o = d * 4 if bytes == 1 then @@ -21614,7 +20877,6 @@ function Codecs.int(src, off, dst, d, count, bytes, be) end end --- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. function Codecs.float(src, off, dst, d, count, bytes, be, tmp) local o = d * 4 @@ -21645,7 +20907,6 @@ function Codecs.float(src, off, dst, d, count, bytes, be, end end --- 8-bit companded (A-law / mu-law) through a 256-entry f32 table function Codecs.law(src, off, dst, d, count, tbl) local o = d * 4 for i = 0, count - 1 do @@ -21653,13 +20914,10 @@ function Codecs.law(src, off, dst, d, count, tbl) end end --- copy frames from a block cache into the output: count f32 values function Codecs.copy(src, sOff, dst, dOff, count) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end --- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), --- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. function Codecs.quantize(src, s, dst, off, count, kind) local so = s * 4 if kind == "f32" then @@ -21724,19 +20982,9 @@ return Codecs end __FILES["audio/wavpack"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction --- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 --- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). --- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the --- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("<name>c") --- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking --- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file --- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. --- --- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... --- local f32, n = dec:read(4096) --- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them --- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's +-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as +-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -21775,7 +21023,6 @@ if r:peek(4) ~= "wvpk" then end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function WavPack.decode(r, opts) local dec, err = WavPack.open(r, opts) if not dec then @@ -21789,7 +21036,6 @@ local limit = opts and opts.maxFrames or 2 ^ 28 return Pcm.drain(d, d.source, limit) end -- ------------------------------------------------------------------------------------------------ open --- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence @@ -21867,7 +21113,6 @@ if not opts then return nil end --- open(r, opts?) -> Decoder | nil, Err function WavPack.open(r, opts) if type(r) == "buffer" then r = Bytes.reader(r ) @@ -21892,8 +21137,7 @@ if type(r) == "buffer" then local count = #idx.offsets local last = idx.starts[count] + idx.samples[count] local frames = (idx.total >= 0 and{(math.min(idx.total, last) )}or{last -})[1] -- the correction file: its frames by start sample - local cbuf = (info.hybrid and{(correctionFile(opts) )}or{nil +})[1] local cbuf = (info.hybrid and{(correctionFile(opts) )}or{nil })[1] local cfor= {} if cbuf then local cidx = index(cbuf, 0, buffer.len(cbuf)) @@ -21945,26 +21189,9 @@ return WavPack end __FILES["cad/step"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). --- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / --- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and --- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; --- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to --- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, --- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / --- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same --- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). --- --- B-rep bodies and tessellation come from an injected kernel, never required by rosetta: --- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, --- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } --- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } --- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / --- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / --- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, --- millimetres (meta.unit = 0.001). --- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), --- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). +-- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA +-- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the +-- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -22014,7 +21241,6 @@ local SCHEMAS = { } Step.SCHEMAS = SCHEMAS --- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself local function schemaOf(name) local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then @@ -22149,7 +21375,6 @@ if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" th end end end - -- entities by section, in id order local ids = {} for id, e in __iter(cad.entities) do if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then @@ -22203,7 +21428,6 @@ if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" th end -- ------------------------------------------------------------------------------------------------ extras --- get(cad, id | { ref = id }) -> the entity function Step.get(cad, id) if type(id) == "table" then id = id.ref @@ -22211,7 +21435,6 @@ if type(id) == "table" then return cad.entities[id] end --- ids(cad) -> the instance ids in ascending order function Step.ids(cad) local out = {} for id in __iter(cad.entities) do @@ -22221,7 +21444,6 @@ local out = {} return out end --- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending function Step.byType(cad, name) local n = string.upper(name) local out = {} @@ -22241,7 +21463,6 @@ local n = string.upper(name) return out end --- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) function Step.part(e, name) if not e then return nil @@ -22259,7 +21480,6 @@ if not e then return nil end --- add(cad, type, args) -> id: a new instance after the highest id function Step.add(cad, type, args) local top = 0 for id in __iter(cad.entities) do @@ -22273,7 +21493,6 @@ local top = 0 return id end --- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) function Step.real(t, key) local mt= getmetatable(t) if not mt then @@ -22284,12 +21503,10 @@ local mt= getmetatable(t) return t end --- new(schema?) -> an empty Cad ("AP214" by default) function Step.new(schema) return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } end --- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason Step.plugin = Brep.plugin local function textOf(cad) @@ -22300,7 +21517,6 @@ local buf, err = Step.encode(cad) return buffer.tostring(buf), nil end --- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err function Step.toBodies(cad, opts) local plug, perr = Brep.find(opts) if not plug then @@ -22317,7 +21533,6 @@ local plug, perr = Brep.find(opts) return bodies, res end --- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err function Step.fromBodies(bodies, opts) if type(bodies) ~= "table" then return nil, Err.new(Err.ARG, "needs a list of bodies") @@ -22333,7 +21548,6 @@ if type(bodies) ~= "table" then return Step.decode(Bytes.reader(buffer.fromstring(text))) end --- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err function Step.tessellate(value, opts) local plug, perr = Brep.find(opts) if not plug then @@ -22357,18 +21571,9 @@ return Step end __FILES["cad/step/Brep"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises --- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a --- Scene. Interpreted on purpose: the plug-in's errors unwind through here. --- --- The interface (every function may throw; results are checked): --- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, --- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) --- write(bodies: { Body }, opts) -> string bodies -> STEP text --- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based --- triples }, faceOf = { [triangle] = Face (face.color?) }? } --- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = --- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall. +-- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text; +-- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is. local Err = __include("core/Err") local Types = __include("Types") @@ -22388,7 +21593,7 @@ if c == nil then if type(c) == "table" then return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] end - return (c ).R, (c ).G, (c ).B -- Color3 + return (c ).R, (c ).G, (c ).B end) if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then return r, g, b @@ -22396,7 +21601,6 @@ if type(c) == "table" then return nil, nil, nil end --- plugin(p) -> the normalised interface, or nil + the reason function Brep.plugin(p) if type(p) ~= "table" then return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" @@ -22440,7 +21644,6 @@ or nil, return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" end --- find(opts) -> the plug-in from opts.brep or opts.plugins.brep function Brep.find(opts) local p = nil if type(opts) == "table" then @@ -22456,7 +21659,6 @@ local p = nil return plug, nil end --- read(plug, text, opts) -> bodies, result | nil, Err function Brep.read(plug, text, opts) local ok, res = pcall(plug.read, text, opts) if not ok then @@ -22468,7 +21670,6 @@ local ok, res = pcall(plug.read, text, opts) return res.bodies, res, nil end --- write(plug, bodies, opts) -> text | nil, Err function Brep.write(plug, bodies, opts) local w = plug.write if not w then @@ -22488,7 +21689,7 @@ local function xyz(p) if type(p) == "table" then return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 end - return (p ).X, (p ).Y, (p ).Z -- vector / Vector3 + return (p ).X, (p ).Y, (p ).Z end local function linear(c) @@ -22496,8 +21697,7 @@ c = math.clamp(c, 0, 1) return (c <= 0.04045 and((c / 12.92 ))or((((c + 0.055) / 1.055) ^ 2.4 )))end --- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by --- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +-- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written function Brep.scene(plug, bodies, opts) local tess = plug.tessellate if not tess then @@ -22554,7 +21754,6 @@ local P, N, I = mesh.positions, mesh.normals, mesh.indices end end local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) - -- triangles grouped by colour, in first-seen order local groups= {} local byMat= {} local faceOf = (type(mesh.faceOf) == "table" and{mesh.faceOf }or{{} @@ -22608,16 +21807,8 @@ end __FILES["cad/step/Parse"] = function() local __compat = __compat local type = __compat.type --!strict --!native --- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass --- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), --- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every --- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, --- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. --- --- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; --- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) --- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so --- the writer prints it back as a real; integral numbers without that mark are written as integers. +-- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). +-- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`). local Parse = {} local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor @@ -22640,7 +21831,6 @@ if not ctx.err then return nil end --- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) local function skip(ctx, i) local s, n = ctx.s, ctx.n while i <= n do @@ -22668,7 +21858,6 @@ local function isWord(c) return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end --- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none local function keyword(ctx, i) local s, n = ctx.s, ctx.n local j = i @@ -22685,7 +21874,6 @@ local s, n = ctx.s, ctx.n return string.upper(ssub(s, i, j - 1)), j end --- UTF-8 of a code point local function utf8char(cp) if cp < 0x80 then return schar(cp) @@ -22708,9 +21896,7 @@ local h = ssub(s, i, i + k - 1) return tonumber(h, 16) end --- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, --- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) --- pass through. +-- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through function Parse.unescape(raw) if not sfind(raw, "[\\']") then return raw @@ -22793,11 +21979,9 @@ local function markReal(t, key) mt.__reals[key] = true end --- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) local value -local function list(ctx, i, depth) -- i is just past "(" - +local function list(ctx, i, depth) local s = ctx.s local out = {} i = skip(ctx, i) @@ -22917,7 +22101,6 @@ return nv, (e ) + 1, real and nv == floor(nv) and nv == nv end Parse.value = value --- the simple record at i: NAME(params) -> type, args, next local function record(ctx, i) local word, j = keyword(ctx, i) if not word then @@ -22934,7 +22117,6 @@ local word, j = keyword(ctx, i) return word, args, k end --- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil local function expect(ctx, i, ch, what) i = skip(ctx, i) if sbyte(ctx.s, i) ~= ch then @@ -22950,7 +22132,6 @@ local function at(s, i, word) return ssub(s, i, i + #word - 1) == word end --- parse(s, opts) -> Result | nil, message, offset (1-based position in s) @@ -23183,17 +22364,14 @@ end __FILES["cad/step/Write"] = function() local __compat = __compat local type = __compat.type --!strict --!native --- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings --- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid --- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: --- failures return nil, message. +-- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). local Write = {} local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge local MAX_DEPTH = 100 --- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +-- Part 21 real: a '.' always, upper-case E function Write.real(v) if v ~= v or v == huge or v == -huge then return nil @@ -23228,7 +22406,6 @@ local out = table.create(k) return table.concat(out) end --- a string's Part 21 literal (with the quotes) function Write.str(s) if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" @@ -23255,7 +22432,6 @@ if c >= 32 and c < 127 then end i =i+ 1 else - -- a UTF-8 sequence -> code point local cp= nil local len = 1 if c >= 0xC2 and c < 0xE0 then @@ -23418,7 +22594,6 @@ local out = ctx.out end Write.value = value --- record(ctx, type, args) -> appends TYPE(args) function Write.record(ctx, t, args) if not isName(t) then ctx.err = "bad entity type " .. tostring(t) @@ -107723,16 +106898,8 @@ return Source end __FILES["containers/Archive"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data --- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder --- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be --- encoded by any writable archive format through its list() / read(). --- --- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err --- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 }) --- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end }) --- a:list() a:read("a.txt") a:add("c.txt", "text") a:write() --- +-- containers/Archive: the in-memory Archive value (Types.Archive) archive formats return. Entries hold their data or +-- a lazy loader; write() calls the encoder the format attached, and any Archive can be encoded by any archive writer. -- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them -- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. local Err = __include("core/Err") @@ -107758,7 +106925,6 @@ local Archive = {} local Methods = {} Methods.__index = Methods --- the public fields of an entry (no data / loader) local function public(e) local out= {} for k, v in __iter(e) do @@ -107777,7 +106943,6 @@ for i, e in __iter(self._entries) do return out end --- read(name) -> buffer | nil, Err (directories read as an empty buffer) function Methods.read(self, name) local e= self._byName[name] if not e then @@ -107799,7 +106964,6 @@ local e= self._byName[name] return buffer.create(0), nil end --- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name function Methods.add(self, name, data, opts) local b= (type(data) == "string" and{(buffer.fromstring(data) )}or{(type(data) == "buffer" and{data }or{(buffer.create(0) )})[1]})[1] local o = opts or {} @@ -107814,7 +106978,6 @@ function Methods.add(self, name, data, opts) Archive.put(self, e) end --- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) function Methods.write(self, opts) local enc= self._encode if not enc then @@ -107823,7 +106986,6 @@ local enc= self._encode return enc(self, opts) end --- new(format, encode?) -> an empty Archive function Archive.new(format, encode) return setmetatable({ kind = "archive", @@ -107835,7 +106997,6 @@ return setmetatable({ }, Methods) end --- put(archive, entry): append (or replace by name) an entry function Archive.put(a, e) local old = a._byName[e.name] if old then @@ -107849,8 +107010,6 @@ function Archive.put(a, e) a._byName[e.name] = e end --- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another --- format's): what encoders iterate. nil when the value is not an archive. function Archive.entries(value) if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then return nil @@ -107877,7 +107036,6 @@ local rok, b, err = pcall(value.read, value, e.name) return out end --- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) function Archive.slice(buf, at, n) return function() local out = buffer.create(n) @@ -107886,8 +107044,6 @@ local out = buffer.create(n) end end --- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read --- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) function Archive.collect(value) local items = Archive.entries(value) if not items then @@ -107908,8 +107064,6 @@ local items = Archive.entries(value) return out, nil end --- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value, --- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take. function Archive.files(value, name) if type(value) == "buffer" or type(value) == "string" then local b = (type(value) == "string" and{(buffer.fromstring(value) )}or{value @@ -107932,8 +107086,6 @@ if type(value) == "buffer" or type(value) == "string" then return out, nil end --- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or --- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err function Archive.streamData(value) if type(value) == "buffer" then return value, nil @@ -107964,8 +107116,7 @@ if type(value) == "buffer" then return Tar.write(list) end --- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store --- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date +-- MS-DOS date / time: stamp = date * 65536 + time (LHA / ARJ / ZIP); local time without a zone, read as UTC function Archive.fromDos(stamp) local time, date = stamp % 65536, math.floor(stamp / 65536 ) local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) @@ -107976,7 +107127,7 @@ local time, date = stamp % 65536, math.floor(stamp / 65536 return Types.Date.daysFromCivil(y, m, d) * 86400 + secs end --- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31) +-- MS-DOS dates cover 1980-01-01 .. 2107-12-31 function Archive.toDos(t) if type(t) ~= "number" or t ~= t or t < 315532800 then return 0x210000 -- 1980-01-01 00:00 @@ -107991,8 +107142,6 @@ if type(t) ~= "number" or t ~= t or t < 315532800 then return ((y - 1980) * 512 + m * 32 + d) * 65536 + (math.floor(rem / 3600)) * 2048 + ((math.floor(rem / 60)) % 60) * 32 + math.floor((rem % 60) / 2 )end --- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension --- (".tgz" -> ".tar"), else "data" function Archive.streamName(opts, exts) local name = (type(opts) == "table" and type(opts.name) == "string" and{opts.name }or{nil })[1] if not name then @@ -108016,20 +107165,9 @@ return Archive end __FILES["containers/AudioWrap"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone --- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another --- format). New in rosetta. --- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); --- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; --- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV; --- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); --- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; --- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); --- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); --- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; --- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). --- --- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +-- containers/AudioWrap: a video container's audio track as a stream an audio format reads (a format never requires +-- another). New in rosetta. PCM / WAVEFORMATEX -> WAV, adpcm_swf -> f32 WAV, mp1-3 / ac3 -> frames back to back, +-- flac -> fLaC + metadata blocks, opus / vorbis -> Ogg, aac -> ADTS. E-AC-3 is UNSUPPORTED. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -108075,7 +107213,6 @@ local total = (prefix and{(buffer.len(prefix) )}or{0 return out end --- ------------------------------------------------------------------------------------------------ WAV local PCM= { -- tag, bits, bytes swapped (big-endian source) pcm_u8 = { 1, 8, 0 }, pcm_s8 = { 1, 8, 0 }, @@ -108176,7 +107313,6 @@ local ch = track.channels or 1 return wav(f:finish(), data), nil end --- ------------------------------------------------------------------------------------------------ Ogg -- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) local function opusSamples(b) local n = buffer.len(b) @@ -108332,7 +107468,6 @@ if buffer.len(id) < 30 or buffer.len(setup) < 8 then return nil, nil end --- ------------------------------------------------------------------------------------------------ ADTS local function adts(track, packets) local c = track.config local profile, rateIndex, chanConfig @@ -108370,10 +107505,8 @@ local c = track.config return w:finish(), nil end --- ------------------------------------------------------------------------------------------------ trim --- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's --- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus --- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding) +-- trim: a container's codec delay (Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, as ffmpeg) +-- and end padding function AudioWrap.trim(dec, skip, length) if skip <= 0 and length == nil then return dec @@ -108429,8 +107562,6 @@ return math.max(0, dec:position() - skip / rate) return w end --- ------------------------------------------------------------------------------------------------ wrap --- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err function AudioWrap.wrap(dmx, track) if type(track) ~= "table" or track.kind ~= "audio" then return nil, nil, Err.new(Err.ARG, "not an audio track") @@ -108537,18 +107668,9 @@ return AudioWrap end __FILES["containers/Avi"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in rosetta. --- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk --- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets --- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). --- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. --- --- local avi, err = Avi.read(buf, base, limit) --- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf --- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute --- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() --- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) --- +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + OpenDML 1.02), read and written. New in rosetta. The chunk +-- index comes from the OpenDML super index (indx -> ix##), else idx1 (movi-relative or absolute, detected), else a +-- scan of the movi lists. Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an odml / dmlh header. -- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -108586,8 +107708,6 @@ local function u32(b, o) return readu32(b, o) end --- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not --- entered); returns where it stopped local function walk(b, p, limit, fn) while p + 8 <= limit do local id = readstring(b, p, 4) @@ -108731,7 +107851,6 @@ if n < 24 or depth > 2 then return false end --- read(buf, base, limit) -> File | nil, Err function Avi.read(b, base, limit) if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then return nil, Err.new(Err.CORRUPT, "not an AVI file", base) @@ -108879,8 +107998,6 @@ if id == "LIST" and ltype == "rec " then end return file, nil end --- ------------------------------------------------------------------------------------------------ writing --- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order @@ -108935,7 +108052,6 @@ local ns = #opts.streams local riffSize = w:tell() w:u32le(0) w:string("AVI ") - -- hdrl w:string("LIST") local hdrlSize = w:tell() w:u32le(0) @@ -109013,7 +108129,6 @@ local ns = #opts.streams w:u32le(4) w:u32le(frames) w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) - -- INFO local sw = (opts.software or "rosetta") .. "\0" if #sw % 2 == 1 then sw =sw.. "\0" @@ -109024,7 +108139,6 @@ local ns = #opts.streams w:string("ISFT") w:u32le(#sw) w:string(sw) - -- movi w:string("LIST") local moviSize = w:tell() w:u32le(0) @@ -109046,7 +108160,6 @@ for _, c in __iter(chunks) do table.insert(index, { id, key and 0x10 or 0, at - moviBase, n }) end w:setU32le(moviSize, w:tell() - moviSize - 4) - -- idx1 w:string("idx1") w:u32le(#index * 16) for _, e in __iter(index) do @@ -109058,11 +108171,9 @@ for _, c in __iter(chunks) do w:setU32le(riffSize, w:tell() - 8) return w:finish() end --- ------------------------------------------------------------------------------------------------ BITMAPINFO --- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | --- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; --- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +-- BITMAPINFOHEADER: the palette is the last (2^bits) * 4 bytes after the header (B, G, R, x; a trailing "BottomUp" +-- tag skipped), as the VfW codecs store it @@ -109109,16 +108220,9 @@ return Avi end __FILES["containers/Chunks"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional --- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a --- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing --- the loop. New in rosetta (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). --- --- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf) --- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG --- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end --- local c = Chunks.find(list, "SSND") --- +-- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and +-- padding): RIFF / RIFX / RF64, IFF / AIFF / AIFC, PNG (size first, CRC trailer), CAF (64-bit sizes). New in rosetta +-- (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). -- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in -- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). -- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one @@ -109175,7 +108279,6 @@ local v = readu32(b, o) return (be and{(bit32.byteswap(v) )}or{v })[1]end --- walk(b, p, limit, layout?) -> { Chunk } of [p, limit) function Chunks.walk(b, p, limit, layout) local L= layout or Chunks.RIFF local be = L.bigEndian == true @@ -109239,7 +108342,6 @@ local L= layout or Chunks.RIFF return list end --- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index function Chunks.find(list, id, from) for i = from or 1, #list do if list[i].id == id then @@ -109253,18 +108355,9 @@ return Chunks end __FILES["containers/Cpio"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment), --- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the --- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the --- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar --- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks --- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as --- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The --- archive formats (archive/cpio, archive/rpm's payload) build on it. --- --- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err --- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" }) --- +-- containers/Cpio: cpio, read and written, from cpio(5) (libarchive, GNU cpio) and POSIX.1-1988 (odc). Reads newc +-- (070701), crc (070702, byte sums verified), odc (070707), old binary in both byte orders; writes newc / crc / odc +-- padded to opts.block (512, as GNU cpio). A hard link group's data sits on its last link (as GNU cpio and bsdtar). -- Never throws: bad data returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -109316,7 +108409,6 @@ Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter local TRAILER = "TRAILER!!!" --- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset function Cpio.format(b, o) local n = buffer.len(b) if o + 6 <= n then @@ -109353,7 +108445,7 @@ local s = buffer.readstring(b, o, n) return tonumber(s, base) end --- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32) +-- the crc format's checksum: the sum of the data bytes mod 2^32 function Cpio.checksum(b, o, n) local s = 0 local i = o @@ -109370,7 +108462,6 @@ local s = 0 return s % 4294967296 end --- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err local function header(b, p, e, fmt) local h= {} local nameAt @@ -109433,7 +108524,6 @@ local v = buffer.readu16(b, p + i * 2) return h, nil end --- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err function Cpio.read(b, offset, length, opts) local o = offset or 0 local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) @@ -109531,7 +108621,6 @@ local o = offset or 0 end return out, { format = fmt } end --- ------------------------------------------------------------------------------------------------ writing @@ -109570,7 +108659,6 @@ if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then return string.rep("0", w - #s) .. s end --- write(entries, opts?) -> buffer | nil, Err function Cpio.write(entries, opts) local fmt = (opts and opts.format) or "newc" if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then @@ -109696,23 +108784,13 @@ end __FILES["containers/Demux"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). --- New in rosetta. A container parses its file once into an index of packets (track, pts, dts, duration, --- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives --- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file --- independently), a file-order cursor, keyframe seeking, packet copies on demand. --- --- local d = Demux.new("mkv", tracks, src, meta) --- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order --- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src --- d:finish() -- durations, per-track indexes --- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +-- New in rosetta. Packets are offset + length into the source buffer (or own bytes); per-track cursors are independent. local Types = __include("Types") local Demux = {} local D = {} D.__index = D --- new(format, tracks, src, meta?) -> an empty index @@ -109764,7 +108842,6 @@ return setmetatable({ }, D) end --- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) function D.add(self, track, pts, dts, duration, keyframe, offset, length) local i = self.n + 1 self.n = i @@ -109777,13 +108854,11 @@ function D.add(self, track, pts, dts, duration, keyframe, offset, length) self.len[i] = length end --- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes function D.addData(self, track, pts, dts, duration, keyframe, data) self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) self.data[self.n] = data end --- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) function D.setExtra(self, key, value) local e = self.extra[self.n] if not e then @@ -109793,8 +108868,6 @@ function D.setExtra(self, key, value) e[key] = value end --- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's --- frame rate), and the track / file durations (seconds) where the container gave none function D.finish(self) local byTrack= {} for _, t in __iter(self.tracks) do @@ -109854,7 +108927,6 @@ return self.pts[a] < self.pts[b] self.startTime = (start ~= math.huge and start > 0 and{start }or{0 })[1]end --- the Packet for index entry i (a copy of its bytes) function D._packet(self, i) local data = self.data[i] if not data then @@ -109886,7 +108958,6 @@ local data = self.data[i] return p end --- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end function D.read(self, track) if track == nil then local i = self.gcur @@ -109909,14 +108980,12 @@ if track == nil then return self:_packet(i) end --- packets(track?) -> an iterator of Packets from the current position (advancing it) function D.packets(self, track) return function() return self:read(track) end end --- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors function D.count(self, track) local list = self.byTrack[track] return (list and((#list ))or(0 @@ -109930,7 +108999,6 @@ local list = self.byTrack[track] return self:_packet(i) end --- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) function D.info(self, track, k) local list = self.byTrack[track] local i = list and list[k] @@ -109940,7 +109008,6 @@ local list = self.byTrack[track] return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] end --- rewind(track?): a track's cursor (or every cursor) back to the start function D.rewind(self, track) if track then self.cur[track] = 1 @@ -109952,7 +109019,6 @@ function D.rewind(self, track) self.gcur = 1 end --- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) function D.seek(self, seconds) local g = self.n + 1 for _, t in __iter(self.tracks) do @@ -109975,7 +109041,6 @@ function D.seek(self, seconds) self.gcur = g > self.n and 1 or g end --- track(kind) -> the first default track of the kind, else the first of the kind function D.track(self, kind) local first = nil for _, t in __iter(self.tracks) do @@ -109998,11 +109063,6 @@ local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 -- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, -- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and -- minimal-length value elements. --- --- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated --- for id, off, size in Ebml.children(buf, off, limit) do ... end --- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() --- -- Never throws: malformed input gives nil (readers) or stops iteration. local Bytes = __include("core/Bytes") @@ -110012,7 +109072,6 @@ local Ebml = {} Ebml.UNKNOWN = -1 --- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. function Ebml.vint(buf, pos, limit) if pos >= limit then return nil, nil @@ -110045,7 +109104,6 @@ if pos >= limit then return v, len end --- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil function Ebml.svint(buf, pos, limit) local v, len = Ebml.vint(buf, pos, limit) if v == nil or len == nil then @@ -110057,7 +109115,6 @@ local v, len = Ebml.vint(buf, pos, limit) return v - (2 ^ (7 * len - 1) - 1), len end --- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) function Ebml.id(buf, pos, limit) if pos >= limit then return nil, nil @@ -110074,7 +109131,6 @@ if pos >= limit then return v, len end --- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil function Ebml.header(buf, pos, limit) local id, il = Ebml.id(buf, pos, limit) if not id or not il then @@ -110087,8 +109143,6 @@ local id, il = Ebml.id(buf, pos, limit) return id, size, pos + il + sl end --- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the --- limit is clipped; a malformed header ends the iteration) function Ebml.children(buf, off, limit) local pos = off return function() @@ -110108,7 +109162,6 @@ if pos >= limit then end end --- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) function Ebml.uint(buf, off, len) local v = 0 for i = 0, math.min(len, 8) - 1 do @@ -110150,18 +109203,15 @@ local b = buffer.create(len) return b end --- ------------------------------------------------------------------------------------------------ writing local W = {} W.__index = W --- writer(capacity?) -> an EBML byte builder function Ebml.writer(capacity) return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) end --- idBytes(id) -> the ID's bytes as written local function writeId(w, id) if id >= 0x1000000 then w:u32be(id) @@ -110174,7 +109224,6 @@ local function writeId(w, id) end end --- size as a minimal vint (n bytes: force a length) local function writeSize(w, size, n) local len = n or 1 if not n then @@ -110194,7 +109243,6 @@ local function writeSize(w, size, n) end Ebml.writeSize = writeSize --- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) function Ebml.vintString(v, n) local w = Bytes.writer(8) writeSize(w, v, n) @@ -110205,7 +109253,6 @@ function W.tell(self) return self.w:tell() end --- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder function W.open(self, id) writeId(self.w, id) local at = self.w:tell() @@ -110215,7 +109262,6 @@ writeId(self.w, id) return at end --- close(handle): patches the size of the element opened at handle function W.close(self, at) local w = self.w local v = w:tell() - at - 8 @@ -110226,7 +109272,6 @@ function W.close(self, at) ) end end --- unknownSize(id): a master element with an unknown size (live streams) function W.openUnknown(self, id) writeId(self.w, id) self.w:u8(0x01) @@ -110283,7 +109328,6 @@ function W.string(self, id, s) self.w:string(s) end --- binary(id, buf, off?, len?) function W.binary(self, id, b, off, len) local o = off or 0 local n = len or (buffer.len(b) - o) @@ -110292,7 +109336,6 @@ function W.binary(self, id, b, off, len) self.w:bytes(b, o, n) end --- raw bytes (a pre-built element, block headers) function W.raw(self, s) self.w:string(s) end @@ -110300,13 +109343,11 @@ function W.rawBuffer(self, b, off, len) local o = off or 0 self.w:bytes(b, o, len or (buffer.len(b) - o)) end --- element header for a binary element whose payload follows in pieces: id + size function W.header(self, id, size) writeId(self.w, id) writeSize(self.w, size) end --- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space function W.void(self, n) self.w:u8(0xEC) if n - 2 < 127 then @@ -110330,17 +109371,9 @@ return Ebml end __FILES["containers/Fat"] = function() local __compat = __compat local buffer, bit32, utf8, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.__iter --!strict --- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories --- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names, --- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images --- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from --- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout. --- --- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message --- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/") --- local data, err = Fat.read(vol, entry) -- buffer | nil, message --- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image --- +-- containers/Fat: FAT12 / FAT16 / FAT32 over a byte range (BPB, chains, VFAT long names checksum-validated against +-- their 8.3 entry, NT lower-case flags; an MBR's first FAT partition) and a FAT12 floppy writer. New code, from +-- Microsoft's fatgen103 and the VFAT long-name layout. -- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by -- the cluster count (loops are errors). local Archive = __include("containers/Archive") @@ -110349,7 +109382,6 @@ local Fat = {} local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 --- ------------------------------------------------------------------------------------------------ open @@ -110485,7 +109517,6 @@ local o= opts or {} return nil, (o.partition and(("no partition " .. o.partition ))or("no FAT partition" ))end --- ------------------------------------------------------------------------------------------------ chains local function nextCluster(v, c) local f = v.base + v.fatOffset if v.bits == 12 then @@ -110511,7 +109542,6 @@ local f = v.base + v.fatOffset return bit32.band(readu32(v.b, p), 0x0FFFFFFF) end --- the clusters of a chain (nil, message when it leaves the volume or loops) local function chainOf(v, first, maxClusters) local out = {} local c = first @@ -110535,7 +109565,6 @@ local function clusterOffset(v, c) return v.base + v.dataOffset + (c - 2) * v.spc * v.bps end --- the bytes of a chain, up to size bytes (nil = the whole chain) local function readChain(v, first, size) local csize = v.spc * v.bps local maxClusters = (size and((math.ceil(size / csize) + 1 ))or(v.clusters @@ -110564,7 +109593,6 @@ local csize = v.spc * v.bps return out, nil end --- ------------------------------------------------------------------------------------------------ directories local function latin1(s) if not string.find(s, "[\128-\255]") then return s @@ -110590,7 +109618,6 @@ local function ucs2(b, o, n, out) end end --- the entries of one directory's bytes local function parseDir(d, prefix, out) local lfn= {} local lfnSum, lfnCount = -1, 0 @@ -110680,7 +109707,6 @@ local lfn= {} return subdirs end --- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents) function Fat.list(v, maxEntries) local out= {} local limit = maxEntries or 65536 @@ -110734,7 +109760,6 @@ if depth > 64 then return out, nil end --- read(vol, entry) -> the file's bytes function Fat.read(v, e) if e.dir or e.size == 0 then return buffer.create(0), nil @@ -110744,7 +109769,6 @@ if e.dir or e.size == 0 then end return readChain(v, e.cluster, e.size) end --- ------------------------------------------------------------------------------------------------ write @@ -110768,7 +109792,6 @@ local v = Archive.toDos(t) return math.floor(v / 65536), v % 65536 end --- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed local function shortName(name, used) @@ -110822,7 +109845,6 @@ s = string.upper((string.gsub(s, "[%s%.]", ""))) return " ___", 0, true end --- the directory entries (32 bytes each) of a node's children local function dirEntries(n, parentCluster, isRoot, label) local w = {} local function entry(raw, attr, nt, cluster, size, mtime) @@ -110887,7 +109909,6 @@ local w = {} return out end --- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths) function Fat.write(files, opts) local o= opts or {} local g = GEOMETRY[o.size or 1440] @@ -111012,7 +110033,6 @@ for _, c in __iter(n.children) do setFat(1, 0xFFF) buffer.copy(img, bps, fat) buffer.copy(img, (1 + g.fat) * bps, fat) - -- boot sector buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") buffer.writeu16(img, 11, bps) buffer.writeu8(img, 13, g.spc) @@ -111039,20 +110059,10 @@ return Fat end __FILES["containers/Iso9660"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary, --- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross --- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is --- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names --- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the --- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE --- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock --- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog --- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet --- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns --- the stored bytes), UDF, writing. --- --- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err --- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents) +-- containers/Iso9660: ISO 9660 (ECMA-119) images, read; from ECMA-119, SUSP / RRIP 1.12, Joliet and El Torito 1.0, no +-- code ported. Name sets: Rock Ridge, else Joliet (%/@, %/C, %/E), else plain (";1" and a trailing "." dropped); +-- multi-extent files joined, CL / RE / PL relocations resolved, El Torito catalog in info.boot. Not supported: zisofs +-- (read returns the stored bytes), interleaved files (Err.UNSUPPORTED), UDF, writing. local Err = __include("core/Err") local Types = __include("Types") local Text = __include("codecs/text/Text") @@ -111085,7 +110095,6 @@ local Iso9660 = {} local SECTOR = 2048 local S_TYPES= { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" } --- ------------------------------------------------------------------------------------------------ fields local function u16(b, o) return buffer.readu16(b, o) end @@ -111117,8 +110126,6 @@ local s = buffer.readstring(b, o, 16) local off = buffer.readi8(b, o + 16) return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 }) end --- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge --- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } } @@ -111156,7 +110163,6 @@ local out = {} return out end --- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs } local function rockRidge(b, base, limit, o, e, bs) local rr= {} local name= nil @@ -111228,8 +110234,6 @@ end elseif bit32.band(cf, 8) == 0 or #parts > 0 then end return rr end --- ------------------------------------------------------------------------------------------------ directories --- the records of a directory extent (without "." and "..") | nil, Err @@ -111298,7 +110302,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end return out, nil end --- the root record of a volume descriptor at vd -> lba, size local function root(b, vd) return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10) end @@ -111321,7 +110324,6 @@ local p = base + lba * bs return nil end --- ------------------------------------------------------------------------------------------------ El Torito local function boot(b, base, limit, vd, bs) if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then return nil @@ -111349,8 +110351,6 @@ if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then return info end --- ------------------------------------------------------------------------------------------------ read --- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err function Iso9660.read(b, offset, length, opts) local base = offset or 0 local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base))) @@ -111538,7 +110538,6 @@ __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break en return out, info end --- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err function Iso9660.extract(b, e, limit) if e.interleaved then return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name) @@ -111556,7 +110555,6 @@ if e.interleaved then return out, nil end --- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16 function Iso9660.valid(b, offset) local p = (offset or 0) + 16 * SECTOR return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001" @@ -111569,15 +110567,6 @@ local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__ite -- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) -- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, -- mov, heif, avif build on it. Written from the specifications; no third-party code. --- --- local IsoBmff = require("rosetta.containers.IsoBmff") --- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) --- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) --- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) --- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs --- local data = IsoBmff.itemData(r, items, id) -- an item's bytes --- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) --- -- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit -- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', -- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), @@ -111607,8 +110596,6 @@ local TOP= { styp = true, sidx = true, meta = true, uuid = true, PICT = true, } --- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, --- nil when it is not an ISO BMFF file function IsoBmff.sniff(r) local head = r:peek(12) if #head < 8 then @@ -111627,18 +110614,15 @@ local head = r:peek(12) return nil end --- parse(r, opts?) -> Movie | nil, Err function IsoBmff.parse(r, opts) return Demux.parse(r, opts) end --- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) function IsoBmff.tags(r, movie) local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") return Meta.tags(r.buf, ilst) end --- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) function IsoBmff.items(r, movie) local meta = Box.path(movie.boxes, "meta") if not meta then @@ -111647,12 +110631,10 @@ local meta = Box.path(movie.boxes, "meta") return Meta.items(r.buf, meta) end --- itemData(r, items, id) -> buffer | nil, Err function IsoBmff.itemData(r, items, id) return Meta.itemData(r.buf, r.base, r.limit, items, id) end --- sample(r, track, i) -> a copy of sample i (1-based) function IsoBmff.sample(r, t, i) if i < 1 or i > t.sampleCount then return nil @@ -111663,8 +110645,6 @@ if i < 1 or i > t.sampleCount then return out end --- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / --- dts / duration in their track's timescale ticks and a copy of the sample bytes. function IsoBmff.demux(r, opts) local movie, err = Demux.parse(r, opts) if not movie then @@ -111704,7 +110684,6 @@ if trackId then cursor[trackId] = i + 1 return packet(t, i) end - -- all tracks in file order local best= nil local bestOff = math.huge for _, t in __iter(movie.tracks) do @@ -111721,7 +110700,7 @@ if trackId then return packet(best, i) end end - -- seek(seconds): every track to its last sync sample at or before the time + -- every track to its last sync sample at or before the time function dmx.seek(_self, seconds) for _, t in __iter(movie.tracks) do local target = seconds * t.timescale @@ -111747,7 +110726,6 @@ if trackId then return dmx, nil end --- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) function IsoBmff.mux(spec) return Mux.mux(spec) end @@ -111799,7 +110777,6 @@ local function isIlstItem(parentType) return parentType == "ilst" end --- header(buf, p, limit) -> Box (without children) | nil, Err function Box.header(b, p, limit) if p + 8 > limit then return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) @@ -111836,8 +110813,6 @@ if p + 8 > limit then return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil end --- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A --- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. function Box.list(b, p, limit, parentType, depth) local d = depth or 0 local out= {} @@ -111890,7 +110865,6 @@ local d = depth or 0 return out, firstErr end --- child(box, type) -> the first child of that type function Box.child(box, typ) if not box or not box.children then return nil @@ -111903,7 +110877,6 @@ if not box or not box.children then return nil end --- children(box, type) -> every child of that type function Box.childrenOf(box, typ) local out = {} if box and box.children then @@ -111916,7 +110889,6 @@ local out = {} return out end --- path(boxes or box, "moov/trak/mdia") -> the first box along the path function Box.path(root, path) local cur= root for part in __iter(string.gmatch(path, "[^/]+")) do @@ -111938,7 +110910,6 @@ local cur= root return cur end --- version / flags of a full box function Box.fullHeader(b, box) if box.data + 4 > box.stop then return -1, 0 @@ -111951,12 +110922,9 @@ return Box end __FILES["containers/IsoBmff/Demux"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): --- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration --- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / --- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). --- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the --- reader's buffer. Never throws. +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8), +-- edit lists and fragments (mvex / trex, moof / traf / tfhd / tfdt / trun). The per-sample tables are columnar arrays, +-- offsets absolute in the reader's buffer. Never throws. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Box = __include("containers/IsoBmff/Box") @@ -111969,9 +110937,6 @@ return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) end local Demux = {} --- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the --- sample tables and the ISO facts - @@ -112062,7 +111027,6 @@ local n = 0 return n end --- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate function Demux.esds(b, box) local r = reader(b, box) r:skip(4) -- version / flags @@ -112102,7 +111066,6 @@ local r = reader(b, box) return oti, dsi, avg end --- the sample entry `e` of a track with handler `handler`: fills the codec facts into t local function sampleEntry(b, e, handler, t) local r = reader(b, e) r:skip(6) @@ -112205,7 +111168,6 @@ local esds = Box.child(holder, "esds") end end --- media handler / header / sample tables of one trak -> Track | nil, Err local function track(b, trak, movieTimescale, trex, o) local tkhd = Box.child(trak, "tkhd") local mdia = Box.child(trak, "mdia") @@ -112273,7 +111235,6 @@ local tkhd = Box.child(trak, "tkhd") if not stbl then return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) end - -- sample descriptions local stsd = Box.child(stbl, "stsd") if stsd and stsd.data + 8 <= stsd.stop then local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") @@ -112282,7 +111243,6 @@ local tkhd = Box.child(trak, "tkhd") end t.sampleEntries = entries end - -- edit list local elst = Box.path(trak, "edts/elst") if elst then local r = reader(b, elst) @@ -112325,7 +111285,6 @@ end end end end - -- sample sizes local maxSamples = o.maxSamples or 2 ^ 25 local sizes = t.sizes local count = 0 @@ -112384,7 +111343,6 @@ end end end end - -- decode times local dts, durs = t.dts, t.durations local stts = Box.child(stbl, "stts") if stts and count > 0 then @@ -112418,7 +111376,6 @@ end dts[i], durs[i] = 0, 0 end end - -- composition offsets local ctts = Box.child(stbl, "ctts") if ctts and count > 0 then local r = reader(b, ctts) @@ -112445,7 +111402,6 @@ end t.cts = cts end end - -- sync samples local stss = Box.child(stbl, "stss") if stss then local r = reader(b, stss) @@ -112459,7 +111415,6 @@ end t.sync = sync end end - -- chunk offsets + sample-to-chunk -> sample offsets local stco = Box.child(stbl, "stco") local co64 = Box.child(stbl, "co64") local chunks= {} @@ -112566,12 +111521,10 @@ local r = reader(b, box) t.sampleDescription = nil end end - -- fragment defaults t.trex = trex[t.id] return t, nil end --- the movie fragments (moof) after the moov: appends their samples to the tracks local function fragments(b, fileBase, top, byId, o) local maxSamples = o.maxSamples or 2 ^ 25 for _, moof in __iter(top) do @@ -112691,7 +111644,6 @@ __DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break en return nil end --- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) @@ -112847,7 +111799,6 @@ if size == 0 then r:fail(Err.CORRUPT, "bad iloc field size " .. size) return 0 end --- ------------------------------------------------------------------------------------------------ HEIF items @@ -112919,7 +111870,6 @@ local n, d = r:i32be(), r:u32be() return p end --- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) function Meta.items(b, meta) local out= { items = {}, order = {}, properties = {} } local pitm = Box.child(meta, "pitm") @@ -113069,8 +112019,6 @@ out.items[id] = it return out, nil end --- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit --- bound the file in the buffer function Meta.itemData(b, base, limit, items, id) local it = items.items[id] if not it then @@ -113112,7 +112060,6 @@ local it = items.items[id] return out, nil end --- ------------------------------------------------------------------------------------------------ iTunes tags -- ilst item -> standard tag name local TAG= { ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", @@ -113144,7 +112091,6 @@ local GENRES = { "Musical", "Rock & Roll", "Hard Rock", } --- tags(buf, ilst) -> Tags, { Picture } function Meta.tags(b, ilst) @@ -113212,7 +112158,6 @@ __DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break en return tags, pics end --- ------------------------------------------------------------------------------------------------ ilst writer local function box(w, typ, body) local start = w:tell() w:u32be(0) @@ -113242,8 +112187,6 @@ local v = tonumber(s or "") return math.clamp(math.floor(v), 0, 65535) end --- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' --- freeform com.apple.iTunes items) and cover pictures function Meta.writeIlst(w, tags, pictures) box(w, "ilst", function() local keys = {} @@ -113322,7 +112265,7 @@ __DARKLUA_CONTINUE_16=true until true if not __DARKLUA_CONTINUE_16 then break en end) end --- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +-- udta / meta (hdlr mdir) / ilst function Meta.writeUdta(w, tags, pictures) box(w, "udta", function() box(w, "meta", function() @@ -113345,11 +112288,9 @@ return Meta end __FILES["containers/IsoBmff/Mux"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak --- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks --- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample --- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + --- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +-- containers/IsoBmff/Mux: writes a progressive ISO BMFF / MP4 / M4A file (ISO/IEC 14496-12): ftyp, moov first ("fast +-- start"), the samples interleaved in chunks in one mdat, udta / meta / ilst tags; co64 past 4 GB. Audio and video +-- sample entries with their configuration box, plus raw child boxes. Never throws: bad specs return nil, Err.ARG. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Meta = __include("containers/IsoBmff/Meta") @@ -113498,7 +112439,6 @@ local function sampleEntry(w, t) end) end --- runs of equal values: { { count, value } } local function runs(n, value) @@ -113727,7 +112667,6 @@ return math.floor(ticks * mts / p.t.timescale + 0.5) end) end --- mux(spec) -> buffer | nil, Err function Mux.mux(spec) if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") @@ -113822,7 +112761,6 @@ local ta = a.time / prep[a.track].t.timescale end end local co64 = mdatSize > 4294967295 - 2 ^ 24 - -- ftyp local w = Bytes.writer(mdatSize + 4096) box(w, "ftyp", function() w:string(spec.brand or "isom") @@ -113872,10 +112810,6 @@ local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__ite -- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey -- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the -- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). --- --- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) --- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil --- -- Never throws. local readu8, writeu32 = buffer.readu8, buffer.writeu32 @@ -113938,8 +112872,7 @@ local pal = buffer.create(1024) return pal end --- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size --- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +-- Cinepak's grey flag selects its own grey mode, so no grey palette is made for it function QtPalette.read(b, start, stop, codec) if start + 86 > stop or stop > buffer.len(b) then return nil, nil @@ -113993,11 +112926,6 @@ local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buf -- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with -- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix -- seconds) and comment. Writers pair them back with collect(). --- --- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" }) --- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string --- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes --- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped) -- New code. Never throws. local Err = __include("core/Err") local Archive = __include("containers/Archive") @@ -114045,7 +112973,6 @@ for i, u in __iter(ROMAN) do FROM_UNICODE[u] = 127 + i end --- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through) function MacFile.name(s) if not string.find(s, "[\128-\255]") then return s @@ -114058,7 +112985,6 @@ if not string.find(s, "[\128-\255]") then return table.concat(out) end --- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes) function MacFile.roman(s) if not string.find(s, "[\128-\255]") or not utf8.len(s) then return s @@ -114077,8 +113003,6 @@ if type(s) ~= "string" then return string.sub(s .. "\0\0\0\0", 1, 4) end --- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and --- there is a resource fork) and, when non-empty, the resource fork entry function MacFile.put(a, f, noData) local common = { macType = f.type, @@ -114101,8 +113025,6 @@ function MacFile.put(a, f, noData) end end --- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a --- buffer or a string (one data fork named name, default "data") function MacFile.collect(value, name) local files, err = Archive.files(value, name) if not files then @@ -114156,7 +113078,6 @@ local readu8 = buffer.readu8 local MpegEs = {} --- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil function MpegEs.findStart(b, p, limit) local i = p while i + 3 <= limit do @@ -114177,7 +113098,6 @@ end local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } --- info(b, off, limit) -> the first sequence header's facts | nil @@ -114213,7 +113133,6 @@ local p = MpegEs.findStart(b, off, limit) return info end --- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 function MpegEs.pictureType(b, off, limit) local p = MpegEs.findStart(b, off, limit) local count = 0 @@ -114228,8 +113147,6 @@ local p = MpegEs.findStart(b, off, limit) return 0, 0 end --- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture --- coding extension (3 = frame when there is none: MPEG-1) function MpegEs.pictureStructure(b, p, limit) local q = MpegEs.findStart(b, p + 4, limit) local count = 0 @@ -114249,9 +113166,6 @@ local q = MpegEs.findStart(b, p + 4, limit) return 3 end --- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its --- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures --- is one unit (fields = 2) function MpegEs.pictures(b, off, limit) local out= {} local unitStart= nil @@ -114300,7 +113214,6 @@ unitStart, seq, gop = nil, false, false return out end --- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) function MpegEs.h264Key(b, off, limit) local p = MpegEs.findStart(b, off, limit) local count = 0 @@ -114328,12 +113241,7 @@ local __compat = __compat local buffer = __compat.buffer --!strict -- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private -- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, -- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). --- --- local ps, err = MpegPs.read(buf, base, limit) --- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or --- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance --- --- Never throws: malformed packets are skipped and counted in ps.errors. +-- Never throws: malformed packets are skipped (ps.errors). Private stream 1 sub-streams are keyed 0xBD00 + their id. local Err = __include("core/Err") local MpegEs = __include("containers/MpegEs") @@ -114368,7 +113276,6 @@ local a = readu8(b, p) ) return v end --- read(buf, base, limit) -> File | nil, Err function MpegPs.read(b, base, limit) local file= { streams = {}, order = {}, mpeg2 = false, errors = 0 } local types= {} @@ -114551,16 +113458,8 @@ __FILES["containers/MpegTs"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native -- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same --- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a --- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections --- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity --- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. --- --- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } --- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed --- --- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is --- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. +-- author; no third-party code); changed: the unit queue keeps an explicit tail (#q on a table with holes at its front +-- loses units under LuaJIT's border rule). Never throws: bad input is skipped and counted in `stats`. local Crc32 = __include("core/Crc32") local MpegTs = {} @@ -114722,7 +113621,6 @@ local self = setmetatable({ return self end --- PSI --------------------------------------------------------------------------------------------------------- local function addStream(self, pid, streamType, program, language) local info = CODECS[streamType] @@ -114809,7 +113707,6 @@ local function sectionBytes(self, pid, s, src, from, to) end buffer.copy(s.buf, s.len, src, from, n) s.len =s.len+ n - -- every complete section in the buffer while s.active and s.len >= 3 do if readu8(s.buf, 0) == 0xFF then s.active = false -- stuffing: no more sections until the next unit start @@ -114854,7 +113751,6 @@ local function sectionPayload(self, pid, pusi, b, pos, stop) sectionBytes(self, pid, s, b, pos, stop) end --- PES --------------------------------------------------------------------------------------------------------- local function completePes(self, pid, st) st.active = false @@ -115066,7 +113962,6 @@ end return end end --- packets ----------------------------------------------------------------------------------------------------- local function packet(self, b, pk) local stats = self.stats @@ -115122,7 +114017,6 @@ local function packet(self, b, pk) return -- adaptation field only: the counter does not advance end end - -- continuity counter local ccError = false local last = self._cc[pid] if last ~= nil and not discontinuity then @@ -115142,8 +114036,6 @@ local function packet(self, b, pk) end end --- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for --- pull(). Returns false for a bad argument. function Demuxer.push(self, data, offset, len) local src if type(data) == "string" then @@ -115162,7 +114054,6 @@ if type(data) == "string" then if n < 0 then return false end - -- append to the pending bytes local need = self._pendLen + n if need > buffer.len(self._pend) then local cap = buffer.len(self._pend) @@ -115228,7 +114119,6 @@ do local __DARKLUA_VAR0= self.stats __DARKLUA_VAR0.skippedBytes =__DARKLUA_VA return true end --- The next completed unit (any PID), or nil. function Demuxer.pull(self) local q = self._queue local h = self._qhead @@ -115247,8 +114137,6 @@ h =h+ 1 return u end --- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next --- unit start). Units still queue up for pull(). function Demuxer.flush(self) local pids = {} for pid, st in __iter(self._pes) do @@ -115263,7 +114151,6 @@ function Demuxer.flush(self) self._pendLen = 0 end --- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). function Demuxer.reset(self) self._pendLen = 0 for _, st in __iter(self._pes) do @@ -115282,7 +114169,6 @@ function Demuxer.reset(self) self._qtail = 0 end --- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). function Demuxer.streamFor(self, kind) for _, s in __iter(self.streams) do if s.kind == kind then @@ -115292,9 +114178,6 @@ for _, s in __iter(self.streams) do return nil end --- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / --- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / --- audio (PES stream_id). Never throws; a bad argument gives empty lists. function MpegTs.demux(data, opts) @@ -115346,7 +114229,6 @@ local d = MpegTs.new() } end --- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). function MpegTs.concat(units) local n = 0 for _, u in __iter(units) do @@ -115368,24 +114250,9 @@ __FILES["containers/Ogg"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 --- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and --- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture --- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); --- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad --- input gives nil, err). --- --- local demux, err = Ogg.open(buf) --- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end --- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator --- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil --- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) --- --- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) --- local s = mux:stream(serial?) -- one logical stream --- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages --- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes --- local file = mux:finish() -- every stream ends with an eos page +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer (absorbed from ogg-luau be9f604, same author, no third-party +-- code) and the muxer (Ogg/Mux, new). Packets are reassembled across pages per serial; seeking bisects byte offsets +-- to the page holding a granule. Never throws. local Err = __include("core/Err") local Page = __include("containers/Ogg/Page") local Mux = __include("containers/Ogg/Mux") @@ -115398,7 +114265,6 @@ Ogg.Page = Page Ogg.Mux = Mux Ogg.muxer = Mux.new --- Reader: the packet cursor of one logical stream @@ -115443,7 +114309,6 @@ return setmetatable({ }, Reader) end --- Load the next page of this serial; false at the end of the data function Reader._nextPage(self) local b, d = self.buf, self.demux while true do @@ -115496,7 +114361,6 @@ local b, d = self.buf, self.demux end end --- The next packet, or nil at the end of the stream function Reader.nextPacket(self) if self.ended then return nil @@ -115574,7 +114438,6 @@ if self.ended then end end --- Back to the start of the stream (the identification packet comes next) function Reader.rewind(self) self.pagePos = self.start self.page = nil @@ -115585,7 +114448,6 @@ function Reader.rewind(self) self.ended = false end --- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them function Reader._at(self, p) self:rewind() self.pagePos = p.offset @@ -115604,10 +114466,7 @@ function Reader._at(self, p) self.ended = false end --- Seek so that the next packet is the first one that starts at or before granule g: positions after the last --- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the --- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start --- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +-- seekGranule: after the last page with granule <= g (bisection, then a short scan); before every granule rewinds (-1) function Reader.seekGranule(self, g) local b, d = self.buf, self.demux local serial = self.serial @@ -115653,13 +114512,9 @@ while true do return best.granule, nil end --- Demux local Demux = {} Demux.__index = Demux --- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied --- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = --- true lists every bos page in the file (chained streams), not just the first group function Ogg.open(src, opts) local buf if type(src) == "buffer" then @@ -115726,7 +114581,6 @@ if type(src) == "buffer" then return d, nil end --- Scan backwards from the end for each stream's last granule function Demux._scanLast(self) if self._lastDone then return @@ -115749,7 +114603,6 @@ function Demux._scanLast(self) end end --- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } function Demux.streams(self) self:_scanLast() return self._streams @@ -115760,7 +114613,6 @@ self:_scanLast() return self._bySerial[serial] end --- The serial of the first stream of a codec, or nil function Demux.find(self, codec) for _, s in __iter(self._streams) do if s.codec == codec then @@ -115770,7 +114622,6 @@ for _, s in __iter(self._streams) do return nil end --- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err function Demux.reader(self, serial) local r = self._readers[serial] if r then @@ -115805,7 +114656,6 @@ function Demux.rewind(self, serial) end end --- for p in demux:packets(serial) do ... end (continues from the stream's current position) function Demux.packets(self, serial) local r = self:reader(serial) return function() @@ -115813,7 +114663,6 @@ local r = self:reader(serial) })[1] end end --- Copy a packet's bytes into a fresh buffer of its own function Ogg.copy(p) local c = buffer.create(p.size) buffer.copy(c, 0, p.data, p.offset, p.size) @@ -115831,14 +114680,6 @@ local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, _ -- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last -- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages -- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. --- --- local mux = Mux.new({ pageSize = 4096 }) --- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) --- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page --- s:packet(tags, 0, { flush = true }) --- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) --- local out = mux:finish() -- closes every stream with an eos page --- -- Never throws: a bad argument returns false, Err. local Err = __include("core/Err") local Page = __include("containers/Ogg/Page") @@ -115852,7 +114693,6 @@ Mux.__index = Mux local Stream = {} Stream.__index = Stream --- new(opts?) -> Mux @@ -115875,7 +114715,6 @@ local size = opts and opts.pageSize or 4096 }, Mux) end --- stream(serial?) -> Stream (serials must be unique in the file) function Mux.stream(self, serial) local sr = serial or self.nextSerial self.nextSerial = math.max(self.nextSerial, sr + 1) @@ -115905,7 +114744,6 @@ local c = 0 return c end --- close the page being built (also when empty, for eos) function Stream._flush(self, eos) local nseg = #self.lacing local n = 27 + nseg + self.dataLen @@ -115946,8 +114784,6 @@ function Stream._flush(self, eos) end end --- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet --- (-1: unknown, not recommended); offset / length select a range of data. function Stream.packet(self, data, granule, opts, offset, length) if self.ended then return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) @@ -116004,14 +114840,12 @@ if type(data) == "string" then return true, nil end --- flush(): close the current page now (if it holds anything) function Stream.flush(self) if not self.ended and #self.lacing > 0 then self:_flush(false) end end --- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) function Mux.finish(self) for _, s in __iter(self.streams) do if not s.ended then @@ -116036,10 +114870,9 @@ __FILES["containers/Ogg/Page"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header --- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, --- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. --- +-- containers/Ogg/Page: Ogg pages (RFC 3533): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the crc field read as +-- zero), header parsing and the capture-pattern resync. Absorbed from ogg-luau be9f604 (same author, no third-party +-- code). Never throws: invalid or truncated data gives nil. -- A page header (27 bytes + segment table): -- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) -- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data @@ -116067,7 +114900,6 @@ local Page = {} local CRC = Crc32.MSB_TABLE Page.CRC_TABLE = CRC --- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc local function crcRange(b, from, to, crc) for i = from, to - 1 do crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) @@ -116075,7 +114907,7 @@ for i = from, to - 1 do return crc end --- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +-- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed) function Page.crc32(b, offset, len) local o = offset or 0 local n = len or (buffer.len(b) - o) @@ -116085,8 +114917,6 @@ local o = offset or 0 return crcRange(b, o, o + n, 0) end --- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", --- "version", "crc"). verify = false skips the CRC check. function Page.parse(b, pos, verify) local size = buffer.len(b) if pos < 0 or pos + 27 > size then @@ -116137,8 +114967,6 @@ local size = buffer.len(b) }, nil end --- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the --- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. function Page.find(b, pos, limit, verify) local size = buffer.len(b) local lim = math.min(limit or size, size - 27 + 1) @@ -116157,7 +114985,6 @@ local size = buffer.len(b) return nil end --- The last valid page starting at an offset in [floor, pos] (searching backwards). function Page.findBack(b, pos, floor, verify) local size = buffer.len(b) local lo = math.max(floor or 0, 0) @@ -116176,7 +115003,6 @@ local size = buffer.len(b) return nil end --- The identification of a codec from a stream's first packet (the bos page's packet) function Page.codec(b, off, len) local function is(s, at) if at + #s > len then @@ -116214,18 +115040,6 @@ local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, _ -- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently -- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from -- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. --- --- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer --- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false --- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf --- local c = Riff.find(f, "fmt ") --- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type) --- --- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX) --- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } }) --- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB --- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB --- -- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past -- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a -- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of @@ -116238,7 +115052,6 @@ local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buff local Riff = {} --- ------------------------------------------------------------------------------------------------ read @@ -116270,7 +115083,6 @@ local v = readu32(b, o) return (be and{(bit32.byteswap(v) )}or{v })[1]end --- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil function Riff.sniff(r) local magic = r:peek(4) if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then @@ -116280,8 +115092,6 @@ local magic = r:peek(4) return (#form == 4 and{form }or{nil })[1]end --- walk(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2, --- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64) local function walk(b, p, limit, be, opts, ds64) local layout= { bigEndian = be, @@ -116301,7 +115111,6 @@ or nil, return (Chunks.walk(b, p, limit, layout) ) end --- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. function Riff.read(src, opts) local r = (type(src) == "buffer" and{(Bytes.reader(src) )}or{src })[1] if type(r) ~= "table" or type(r.buf) ~= "buffer" then @@ -116359,7 +115168,6 @@ local r = (type(src) == "buffer" and{(Bytes.reader(src) )}or{src return f, nil end --- find(file, id, from?) -> the first chunk with that id (after index from), and its index function Riff.find(f, id, from) for i = (from or 0) + 1, #f.chunks do if f.chunks[i].id == id then @@ -116369,7 +115177,6 @@ for i = (from or 0) + 1, #f.chunks do return nil, nil end --- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil function Riff.listType(f, c) if c.avail < 4 then return nil @@ -116377,7 +115184,6 @@ if c.avail < 4 then return readstring(f.buf, c.offset, 4) end --- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type) function Riff.list(f, c, opts) if c.avail < 4 then return {} @@ -116385,12 +115191,10 @@ if c.avail < 4 then return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) end --- body(file, chunk) -> a Reader over the chunk's available body function Riff.body(f, c) return Bytes.reader(f.buf, c.offset, c.avail) end --- u16 / u32 in the file's byte order (for chunk bodies) function Riff.u16(f, o) if f.bigEndian then return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) @@ -116401,11 +115205,9 @@ function Riff.u32(f, o) return u32(f.buf, o, f.bigEndian) end --- ------------------------------------------------------------------------------------------------ write local Writer = {} Writer.__index = Writer --- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file @@ -116424,8 +115226,6 @@ return setmetatable({ }, Writer) end --- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a --- list of buffers written one after the other (a data chunk bigger than one buffer) function Writer.chunk(self, id, body, offset, length) local parts = {} local n = 0 @@ -116443,7 +115243,6 @@ function Writer.chunk(self, id, body, offset, length) table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) end --- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style) function Writer.list(self, listType, items) local w = Bytes.writer() w:string(string.sub(listType .. " ", 1, 4)) @@ -116465,7 +115264,6 @@ function Writer.list(self, listType, items) self:chunk("LIST", w:finish()) end --- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied) function Writer.finish(self, opts) local total = 4 -- the form type local big = false @@ -116556,18 +115354,9 @@ return Riff end __FILES["containers/Tar"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles --- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, --- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, --- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar --- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, --- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX --- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- --- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). --- --- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } --- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) --- +-- containers/Tar: tar (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written; from POSIX pax(1) (IEEE Std +-- 1003.1-2017) and the GNU tar manual. Reads v7 / ustar / GNU / pax headers ('x' / 'g', 'L' / 'K', base-256, signed +-- checksums); writes ustar + pax, or GNU 'L' / 'K'. Not supported: sparse files, multi-volume (listed as "S" / "M"). -- Never throws: bad data returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") @@ -116635,7 +115424,6 @@ local u, s = 0, 0 return u, s end --- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum function Tar.valid(b, o) if o + BLOCK > buffer.len(b) or zeros(b, o) then return false @@ -116672,7 +115460,6 @@ if l < #len + 3 or p + l - 1 > #s then return true end --- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err function Tar.read(b, offset, length, opts) @@ -116817,7 +115604,6 @@ __DARKLUA_CONTINUE_5=true break __DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end return out, nil end --- ------------------------------------------------------------------------------------------------ writing @@ -116862,7 +115648,6 @@ local body = " " .. key .. "=" .. value .. "\n" return tostring(n) .. body end --- one header block (the checksum filled in) local function header(name, typ, size, e, prefix, link, gnu) local h = buffer.create(BLOCK) field(h, 0, 100, name) @@ -116897,7 +115682,6 @@ if #path <= 100 then return nil, nil end --- write(entries, opts?) -> buffer | nil, Err function Tar.write(entries, opts) local fmt = (opts and opts.format) or "pax" local w = Bytes.writer(BLOCK * (2 * #entries + 2)) @@ -116985,24 +115769,10 @@ end __FILES["containers/Zip"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --!optimize 2 --- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from --- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an --- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor --- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, --- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly --- (codecs/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/Deflate compress, stored --- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. --- --- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader --- for _, e in zip:list() do print(e.name, e.size) end --- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked --- --- local w = Zip.writer() --- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds --- local file = w:finish({ comment = "..." }) --- --- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native --- code it reaches (Deflate, Crc32) does not throw either. +-- containers/Zip: ZIP (PKWARE APPNOTE 6.3), read and written. The reader is absorbed from zip-luau 121d4b0 (same +-- author, no third-party code): EOCD search, ZIP64, prefix shifts (self-extractor stubs), stored / deflated entries, +-- data descriptors. The writer is new: stored / deflated, UTF-8 names, DOS times, raw entry copies, ZIP64 when needed. +-- Never throws: corrupt archives and bad arguments return nil, Err. local Err = __include("core/Err") local Types = __include("Types") local Bytes = __include("core/Bytes") @@ -117012,7 +115782,6 @@ local Deflate = __include("codecs/compress/Deflate") local Zip = {} Zip.version = "1.1.0" --- ------------------------------------------------------------------------------------------------ read @@ -117070,7 +115839,6 @@ local Archive = {} Archive.__index = Archive --- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) function Zip.isZip(buf) local b = (type(buf) == "string" and{(buffer.fromstring(string.sub(buf, 1, 4)) )}or{buf })[1] return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) @@ -117238,8 +116006,6 @@ local p = cdOff + delta }, Archive) end --- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a --- part of a bigger buffer) function Zip.open(src) local b if type(src) == "string" then @@ -117264,14 +116030,11 @@ if type(src) == "string" then return res, err end --- every entry (directories included), in central directory order function Archive.list(self) return self.entries end --- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename --- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and --- macOS "__MACOSX/" / "._" files never match by basename. +-- lookup: exact, then case-insensitive, then by basename (never __MACOSX/ or ._ files); "\\" and "/" are the same function Archive.find(self, name) local n = normalize(name) local e = self._exact[n] @@ -117312,8 +116075,8 @@ local n = buffer.len(b) return out end --- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers --- get the local extra length wrong) +-- data offset candidates: the local header's lengths, then the central directory's (some writers get the local +-- extra length wrong) function Zip._starts(b, e) local o = e.offset local starts = {} @@ -117330,7 +116093,6 @@ local o = e.offset return starts end --- read(entry | name, verify = true) -> buffer | nil, Err function Archive.read(self, entry, verify) local e= (type(entry) == "string" and{(self:find(entry) )}or{entry })[1] if not e then @@ -117375,7 +116137,6 @@ if not e then return nil, Err.new((firstErr and string.find(firstErr, "CRC", 1, true) and{Err.CHECKSUM }or{code})[1], e.name .. ": " .. tostring(firstErr)) end --- readString(entry | name, verify?) -> string | nil, Err function Archive.readString(self, entry, verify) local out, err = self:read(entry, verify) if not out then @@ -117384,11 +116145,9 @@ local out, err = self:read(entry, verify) return buffer.tostring(out), nil end --- ------------------------------------------------------------------------------------------------ write local Writer = {} Writer.__index = Writer --- writer() -> Writer @@ -117448,7 +116207,6 @@ local function isAscii(s) return string.find(s, "[\128-\255]") == nil end --- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) function Writer.add(self, name, data, opts) if type(name) ~= "string" or name == "" or #name > 65535 then return false, Err.new(Err.ARG, "add: bad entry name") @@ -117498,7 +116256,6 @@ if type(data) == "string" then return true, nil end --- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err function Writer.addRaw(self, e, archive, newName) local b = archive.buf local start= nil @@ -117529,7 +116286,6 @@ local b = archive.buf return true, nil end --- finish(opts?) -> the archive | nil, Err function Writer.finish(self, opts) local comment = opts and opts.comment or "" if #comment > 65535 then @@ -117647,19 +116403,14 @@ local __compat = __compat local buffer = __compat.buffer --!strict --!native -- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; -- no third-party code). Never throws: the range is clamped. --- --- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it) --- Adler32.string(s, adler?) -> u32 local readu8 = buffer.readu8 --- Adler-32 of buf[off, off + len), continuing adler (default 1) local function adler32(buf, off, len, adler) local a0 = adler or 1 local a, b = a0 % 65536, math.floor(a0 / 65536 ) local i, e = off, off + len while i < e do - -- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far - -- more, but keeping the sums small keeps them exact and cheap. + -- zlib NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32 local stop = math.min(e, i + 5552) while i < stop do a =a+ readu8(buf, i) @@ -117672,7 +116423,6 @@ local a0 = adler or 1 return b * 65536 + a end --- clamp (offset, length) to the buffer local function range(buf, offset, length) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) @@ -117701,12 +116451,6 @@ local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat -- Used by tiled map data, glTF / SVG / CSS data: URIs, plist <data>, YAML !!binary, FBX, the Brotli static tables. -- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a -- lone last character is an error. Never throws. --- --- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input) --- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length) --- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message" --- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg --- local uri = Base64.dataUri(buf, "image/png") local Base64 = {} @@ -117734,7 +116478,6 @@ buffer.writeu8(DEC, string.byte("="), 65) local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length) function Base64.encode(data, opts, offset, length) local buf= (type(data) == "string" and{(buffer.fromstring(data) )}or{data })[1] local total = buffer.len(buf) @@ -117742,7 +116485,7 @@ local buf= (type(data) == "string" and{(buffer.fromstring(data) )}or{data local n = math.clamp(length or (total - o), 0, total - o) local enc = (opts and opts.url and{ENC_URL }or{ENC })[1] local pad = not (opts and opts.pad == false) - local wrap = (opts and opts.wrap and opts.wrap >= 4 and{(math.floor(opts.wrap / 4 ))}or{0 -- groups per line + local wrap = (opts and opts.wrap and opts.wrap >= 4 and{(math.floor(opts.wrap / 4 ))}or{0 })[1] local full = math.floor(n / 3 ) local rest = n - full * 3 local textLen = full * 4 + (rest == 0 and 0 or(pad and 4 or rest + 1)) @@ -117789,7 +116532,6 @@ local buf= (type(data) == "string" and{(buffer.fromstring(data) )}or{data return buffer.tostring(out) end --- decode(s) -> buffer | nil, message function Base64.decode(s) local src= (type(s) == "string" and{(buffer.fromstring(s) )}or{s })[1] local n = buffer.len(src) @@ -117826,8 +116568,7 @@ local src= (type(s) == "string" and{(buffer.fromstring(s) )}or{s return res, nil end --- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[<mime>][;params][;base64],<data>" (percent-encoded data --- when not base64) +-- RFC 2397: data:[<mime>][;params][;base64],<data> (percent-encoded data when not base64) function Base64.decodeDataUri(uri) if string.sub(uri, 1, 5) ~= "data:" then return nil, "not a data: URI" @@ -117856,7 +116597,6 @@ return string.char((tonumber(h, 16) )) return buffer.fromstring(decoded), mime end --- dataUri(buf, mime?) -> "data:<mime>;base64,..." function Base64.dataUri(buf, mime) return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) end @@ -117868,25 +116608,14 @@ local __compat = __compat local buffer = __compat.buffer --!strict --!native -- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data -- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. --- -- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. --- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see --- codecs/compress/Deflate/Inflate) and uses these for headers. --- -- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). --- --- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader --- local v = br:read(5); if br.err then return nil, br.err end --- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() --- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path --- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) local Err = __include("core/Err") local Bytes = __include("core/Bytes") local readu8, blen = buffer.readu8, buffer.len local floor = math.floor --- 2^n for n = 0..32 local POW = table.create(33, 0) for i = 0, 32 do POW[i + 1] = 2 ^ i @@ -117894,7 +116623,6 @@ end local Bits = {} Bits.POW = POW --- ------------------------------------------------------------------------------------------------ readers @@ -117974,14 +116702,12 @@ function Lsb.skip(self, n) end Lsb.read(self, n) end --- align(): drop the bits up to the next byte boundary function Lsb.align(self) local k = self.cnt % 8 if k > 0 then Lsb.read(self, k) end end --- bytePos(): the offset of the first byte not yet (even partly) consumed function Lsb.bytePos(self) return self.pos - floor(self.cnt / 8) end @@ -118062,14 +116788,12 @@ local n = blen(buf) return (setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) ) end --- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader function Bits.lsbReader(buf, offset, length) return reader(Lsb, buf, offset, length) end function Bits.msbReader(buf, offset, length) return reader(Msb, buf, offset, length) end --- ------------------------------------------------------------------------------------------------ writers @@ -118100,7 +116824,6 @@ function LsbW.write(self, v, n) end self.acc, self.cnt = acc, cnt end --- align(): pad with zero bits to a byte boundary function LsbW.align(self) if self.cnt > 0 then self.out:u8(self.acc) @@ -118143,8 +116866,7 @@ function MsbW.finish(self) MsbW.align(self) return self.out:finish() end --- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, --- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). +-- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits function Bits.msbPut(w, v, n) @@ -118165,7 +116887,6 @@ function Bits.msbPut(w, v, n) w.acc, w.cnt, w.pos = acc, cnt, p end --- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter function Bits.lsbWriter(capacity) return (setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) ) end @@ -118180,19 +116901,8 @@ local __compat = __compat local buffer, bit32, typeof, type = __compat.buffer, _ --!native -- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a -- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. --- -- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor --- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads: --- --- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length) --- local magic, w, h = r:string(4), r:u32be(), r:u32be() --- if r.err then return nil, r.err end --- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end --- --- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) --- w:string("abcd"); w:u32be(width); local out = w:finish() --- --- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads. local Err = __include("core/Err") local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 @@ -118206,11 +116916,9 @@ local scratch = bcreate(8) -- reinterpret casts for big-endian floats local Bytes = {} --- ------------------------------------------------------------------------------------------------ Reader local Reader = {} Reader.__index = Reader --- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer @@ -118229,7 +116937,6 @@ local n = blen(buf) return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil }, Reader) end --- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)` function Reader.fail(self, code, message) if not self.err then self.err = Err.new(code, message, self.pos) @@ -118237,7 +116944,6 @@ if not self.err then return nil, self.err end --- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end function Reader.need(self, n) if self.pos + n <= self.limit and n >= 0 then return true @@ -118262,7 +116968,6 @@ function Reader.eof(self) return self.pos >= self.limit end --- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED function Reader.seek(self, offset) if offset < 0 or self.base + offset > self.limit then self.pos = self.limit @@ -118283,7 +116988,6 @@ if self:need(n) then return false end --- align(n): skip to the next multiple of n (relative to the reader's start) function Reader.align(self, n) local r = (self.pos - self.base) % n if r == 0 then @@ -118292,7 +116996,6 @@ local r = (self.pos - self.base) % n return self:skip(n - r) end --- integers function Reader.u8(self) local p = self.pos if p + 1 > self.limit then @@ -118391,7 +117094,6 @@ function Reader.i32be(self) local v = self:u32be() return (v >= 2147483648 and((v - TWO32 ))or(v ))end --- 64-bit integers as doubles (exact below 2^53) function Reader.u64le(self) local lo = self:u32le() return lo + self:u32le() * TWO32 @@ -118409,7 +117111,6 @@ local hi = self:i32be() return hi * TWO32 + self:u32be() end --- floats local function half(h) local s = h >= 32768 and-1 or 1 local e = bit32.band(bit32.rshift(h, 10), 31) @@ -118460,7 +117161,6 @@ local hi = self:u32be() return readf64(scratch, 0) end --- strings function Reader.string(self, n) local p = self.pos if n < 0 or p + n > self.limit then @@ -118471,14 +117171,12 @@ local p = self.pos return readstring(self.buf, p, n) end --- fixed(n): an n-byte field, cut at the first NUL function Reader.fixed(self, n) local s = self:string(n) local z = string.find(s, "\0", 1, true) return (z and{(string.sub(s, 1, z - 1) )}or{s })[1]end --- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED function Reader.cstring(self, max) local p = self.pos local e = (max and{(math.min(self.limit, p + max) )}or{self.limit @@ -118496,7 +117194,6 @@ local p = self.pos return readstring(buf, p, q - p) end --- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error function Reader.match(self, s) local p, n = self.pos, #s if p + n > self.limit or readstring(self.buf, p, n) ~= s then @@ -118506,7 +117203,6 @@ local p, n = self.pos, #s return true end --- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error function Reader.peek(self, n, at) local p = self.pos + (at or 0) if p < self.base or p >= self.limit then @@ -118515,7 +117211,6 @@ local p = self.pos + (at or 0) return readstring(self.buf, p, math.min(n, self.limit - p)) end --- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end function Reader.peekU8(self, at) local p = self.pos + (at or 0) if p < self.base or p >= self.limit then @@ -118524,7 +117219,6 @@ local p = self.pos + (at or 0) return readu8(self.buf, p) end --- bytes(n) -> a new buffer with a copy of the next n bytes function Reader.bytes(self, n) local p = self.pos if n < 0 or p + n > self.limit then @@ -118537,8 +117231,6 @@ local p = self.pos return b end --- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is --- left, and the parent records TRUNCATED. function Reader.slice(self, n) local p = self.pos local l = math.max(0, math.min(n, self.limit - p)) @@ -118550,19 +117242,15 @@ local p = self.pos return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil }, Reader) end --- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without --- moving the cursor function Reader.sub(self, offset, length) local o = math.clamp(self.base + offset, self.base, self.limit) local l = math.clamp(length or (self.limit - o), 0, self.limit - o) return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil }, Reader) end --- ------------------------------------------------------------------------------------------------ Writer local Writer = {} Writer.__index = Writer --- writer(capacity?) -> Writer @@ -118575,7 +117263,6 @@ function Bytes.writer(capacity) return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) end --- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf) function Writer.reserve(self, n) local p = self.pos local cap = blen(self.buf) @@ -118671,12 +117358,10 @@ function Writer.string(self, s) writestring(self.buf, p, s) self.pos = p + n end --- cstring(s): s and a NUL function Writer.cstring(self, s) self:string(s) self:u8(0) end --- bytes(b, offset?, length?): copy a buffer range function Writer.bytes(self, b, offset, length) local o = offset or 0 local n = length or (blen(b) - o) @@ -118690,7 +117375,6 @@ function Writer.fill(self, v, n) self.pos = p + n end --- patch fields written earlier (lengths, CRCs) at an absolute offset < pos function Writer.setU32le(self, at, v) writeu32(self.buf, at, v) end @@ -118704,7 +117388,6 @@ function Writer.setU8(self, at, v) writeu8(self.buf, at, v) end --- finish() -> a buffer of exactly the written bytes (the writer can keep going) function Writer.finish(self) local b = bcreate(self.pos) bcopy(b, 0, self.buf, 0, self.pos) @@ -118714,8 +117397,6 @@ end Bytes.Reader = Reader Bytes.Writer = Writer --- ------------------------------------------------------------------------------------------------ arguments --- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else function Bytes.toBuffer(v) if type(v) == "string" then return buffer.fromstring(v) @@ -118723,8 +117404,6 @@ if type(v) == "string" then return (type(v) == "buffer" and{v }or{nil })[1]end --- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string, --- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end) function Bytes.span(what, input, offset, length) local b = Bytes.toBuffer(input) if not b then @@ -118747,11 +117426,9 @@ end __FILES["core/Crc16"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code. --- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0, --- MacBinary II / III headers) --- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC) --- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer. +-- core/Crc16: the 16-bit CRCs old archive formats use, table driven. New code. ccitt: CRC-16/XMODEM (0x1021, MSB first, +-- init 0, no final XOR; BinHex 4.0, MacBinary II / III). arc: CRC-16/ARC (0x8005 reflected = 0xA001, init 0; LHA, Zoo, +-- ARC). Never throws: the range is clamped. local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift local readu8 = buffer.readu8 @@ -118802,14 +117479,7 @@ __FILES["core/Crc32"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native -- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. --- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; --- no third-party code). Never throws: the range is clamped. --- --- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) --- Crc32.string(s, crc?) -> u32 --- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no --- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF) --- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2) +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; no third-party code). Never throws. local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -118844,8 +117514,6 @@ for n = 0, 255 do T7[n + 1] = c end --- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion --- happens inside), so crc(b, crc(a)) == the CRC of a .. b. local function crc32(buf, off, len, crc) local c = bxor(crc or 0, 0xFFFFFFFF) local i, e = off, off + len @@ -118878,7 +117546,6 @@ local c = bxor(crc or 0, 0xFFFFFFFF) return bxor(c, 0xFFFFFFFF) end --- clamp (offset, length) to the buffer local function range(buf, offset, length) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) @@ -118896,10 +117563,10 @@ function Crc32.string(s, crc) return crc32(buffer.fromstring(s), 0, #s, crc) end --- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) Crc32.raw = crc32 --- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks +-- MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected, raw register, no inversions): Ogg pages (init 0), +-- MPEG-2 PSI sections and bzip2 blocks (init 0xFFFFFFFF) local MSB = table.create(256, 0) for n = 0, 255 do local c = lshift(n, 24) @@ -118910,7 +117577,6 @@ for n = 0, 255 do end Crc32.MSB_TABLE = MSB --- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range) function Crc32.msb(buf, off, len, init) local c = init or 0 for i = off, off + len - 1 do @@ -118926,9 +117592,6 @@ local __compat = __compat local type, __iter = __compat.type, __compat.__iter -- -- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). -- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". -- Never throws: --!native modules may require it. --- --- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos) --- if err.code == Err.UNSUPPORTED then ... end local Err = {} -- codes @@ -118957,24 +117620,16 @@ local s = (e.format and((e.format .. ": " .. e.code ))or(e.code return s .. ": " .. e.message end --- new(code, message, offset?) -> Err function Err.new(code, message, offset) return (setmetatable({ code = code, message = message, offset = offset, format = nil }, Meta) ) end --- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) local KIND= {} for _, c in __iter({ "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" }) do KIND[c] = c KIND[string.lower(c)] = c end --- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns --- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the --- message decides: a "<code>: ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; --- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; --- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes --- through unchanged. function Err.from(message, offset, kind) if Err.is(message) then return message @@ -118998,13 +117653,10 @@ elseif string.find(msg, "truncated", 1, true) or string.find(msg, "past the end" return Err.new(code , msg, offset) end --- is(v) -> true when v is an Err function Err.is(v) return type(v) == "table" and getmetatable(v) == Meta end --- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to --- tag errors with the format name. function Err.wrap(e, format) if not Err.is(e) then e = Err.new(Err.CORRUPT, tostring(e)) @@ -119021,9 +117673,6 @@ __FILES["core/Input"] = function() local __compat = __compat local buffer, typeof, type = __compat.buffer, __compat.typeof, __compat.type --!strict -- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files -- through the host adapter the API passes in (core never requires host itself). --- --- local buf, err, name = Input.resolve(src, opts, host) --- -- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path -- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). -- name: the path (for the extension fallback) or opts.name. Never throws. @@ -119031,7 +117680,6 @@ local Err = __include("core/Err") local Input = {} --- looksLikePath(s) -> true for short strings without NUL / newline bytes @@ -119042,7 +117690,6 @@ function Input.looksLikePath(s) return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") end --- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err function Input.resolve(src, opts, host) local o = opts or {} local t = type(src) @@ -119070,7 +117717,6 @@ local o = opts or {} return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil end --- extension(name) -> the lower-case extension without the dot ("png"), or nil function Input.extension(name) if not name then return nil @@ -119079,8 +117725,6 @@ if not name then return (ext and{(string.lower(ext) )}or{nil })[1]end --- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive --- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) function Input.sibling(opts, uri) if type(opts) ~= "table" then return nil @@ -119107,11 +117751,6 @@ local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!optimize 2 -- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); -- not for security. --- --- local h = Md5.new() --- h:update(buf, offset?, length?) -- any number of times --- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) --- Md5.hex(digest) / Md5.of(buf) -> hex string -- Never throws (ranges are clamped to the buffer). local Md5 = {} @@ -119249,7 +117888,6 @@ return { } end --- hex(digest) -> 32 lower-case hex digits function Md5.hex(d) local out = table.create(#d) for i = 1, #d do @@ -119258,7 +117896,6 @@ local out = table.create(#d) return table.concat(out) end --- of(buf, offset?, length?) -> hex digest function Md5.of(buf, offset, length) local h = Md5.new() h:update(buf, offset, length) @@ -119271,27 +117908,18 @@ __FILES["core/Sniff"] = function() --!strict -- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and -- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. --- --- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 --- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score --- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped --- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too --- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file local Sniff = {} --- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 function Sniff.magic(r, s, at, score) return (r:peek(#s, at) == s and{score or 1 }or{0 })[1]end --- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) function Sniff.dropBom(s) return (string.sub(s, 1, 3) == "\239\187\191" and{(string.sub(s, 4) )}or{s })[1]end --- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) function Sniff.text(r, n, trim) local s = r:peek(n) if string.sub(s, 1, 3) == "\239\187\191" then @@ -119307,12 +117935,9 @@ return Sniff end __FILES["data/cbor"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / --- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, --- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), --- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences --- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, --- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. +-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double +-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences +-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -119399,9 +118024,9 @@ local w = Bytes.writer() end -- ------------------------------------------------------------------------------------------------ extras -Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.tagged = Codec.tagged Cbor.isTagged = Codec.isTagged -Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.simple = Codec.simple Cbor.isSimple = Codec.isSimple Cbor.undefined = Codec.undefined @@ -119410,8 +118035,7 @@ end __FILES["data/cbor/Codec"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict --!native --- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, --- message, offset. +-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -119426,14 +118050,13 @@ end } local SimpleMeta = { __tostring = function(s) return "cbor.simple(" .. s.value .. ")" end } --- tagged(tag, value) -> { tag, value }: a tag this library does not interpret function Codec.tagged(tag, value) return (setmetatable({ tag = tag, value = value }, TaggedMeta) ) end function Codec.isTagged(v) return type(v) == "table" and getmetatable(v) == TaggedMeta end --- simple(n) -> an unassigned simple value (0..19, 32..255) +-- unassigned simple values: 0..19, 32..255 function Codec.simple(n) return (setmetatable({ value = n }, SimpleMeta) ) end @@ -119444,7 +118067,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() return "undefined" end })) --- decimal text of a big-endian unsigned byte string (any length) local function bigText(s) local limbs = {} -- base 1e7, little-endian for i = 1, #s do @@ -119468,7 +118090,6 @@ local limbs = {} -- base 1e7, little-endian end return table.concat(out) end --- text + 1 for a decimal string local function incText(s) local digits= (table.create(#s) ) for i = 1, #s do @@ -119500,9 +118121,9 @@ end -local BREAK = {} -- the 0xFF stop code, inside indefinite items +local BREAK = {} -- 0xFF break stop code --- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +-- additional information 31: indefinite length local function arg(st, ai) local r = st.r if ai < 24 then @@ -119579,7 +118200,7 @@ local n = 0 n = n * 256 + string.byte(s, i) end if n >= 9007199254740992 then - -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + -- read back from the exact text: correctly rounded, unlike the running sum local text = bigText(s) if t == 3 then text = incText(text) @@ -119757,7 +118378,6 @@ if n == nil then if v == BREAK then return nil, "unexpected break" end - -- bignum content arrives as a buffer: hand the tag its bytes if (n == 2 or n == 3) and type(v) == "buffer" then return tag(st, n, buffer.tostring(v)) end @@ -119765,7 +118385,6 @@ if n == nil then end end --- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) function Codec.decode(r, opts) local o= opts or {} local st= { @@ -119820,7 +118439,6 @@ local function head(w, major, n) end end --- the half-float bits of x when x is exactly representable, else nil local function toHalf(x) if x ~= x then return 0x7E00 @@ -119833,7 +118451,7 @@ if x ~= x then if a == 0 then return sign end - local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local m, e = math.frexp(a) local exp = e - 1 + 15 if exp >= 31 then return nil @@ -119964,7 +118582,6 @@ if Types.isObject(v) then return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v, opts) local o= opts or {} local st= { @@ -119986,12 +118603,9 @@ return Codec end __FILES["data/csv"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any --- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded --- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column --- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only --- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters --- other than the doubled quote, multi-byte delimiters. +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or +-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode +-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120067,7 +118681,6 @@ local line = string.match(s, "^[^\r\n]*") or "" return best end --- rows(s, opts) -> { { string } } | nil, Err function Csv.parse(s, opts) local o= opts or {} local q = o.quote or '"' @@ -120085,7 +118698,7 @@ local o= opts or {} local row= {} local n = #s local i = 1 - local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + local rowEmpty = true while true do local c = byte(s, i) local field @@ -120128,7 +118741,6 @@ if c == qb then rowEmpty = false i =i+ 1 else - -- end of the row: CRLF / LF / CR / end of data if c == 13 and byte(s, i + 1) == 10 then i =i+ 2 elseif c ~= nil then @@ -120303,13 +118915,9 @@ return Csv end __FILES["data/ini"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. --- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, --- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at --- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a --- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level --- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested --- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. +-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports: +-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline +-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120396,9 +119004,8 @@ local o= opts or {} if trimmed == "" then lastKey = nil elseif string.match(trimmed, "^[;#]") then - -- a comment line (configparser: also when indented); it does not end a continuation + -- configparser: comment lines may be indented and do not end a continuation elseif lastKey and indent > lastIndent then - -- continuation of the previous value local v = trimmed if o.inlineComments then v = string.match(v, "^(.-)%s+[;#]") or v @@ -120554,9 +119161,8 @@ return Ini end __FILES["data/json"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). --- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON +-- Lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120647,11 +119253,9 @@ return JsonFormat end __FILES["data/msgpack"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the --- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as --- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a --- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for --- non-integers unless opts.float32). Not supported: nothing in the spec. +-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as +-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the +-- smallest forms. Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -120731,7 +119335,6 @@ if opts and opts.all then end -- ------------------------------------------------------------------------------------------------ extras --- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) Msgpack.ext = Codec.ext Msgpack.isExt = Codec.isExt @@ -120740,8 +119343,7 @@ end __FILES["data/msgpack/Codec"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with --- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -120749,7 +119351,7 @@ local Codec = {} local TWO32 = 4294967296 --- an extension value: { type = -128..127, data = buffer } +-- ext type: -128..127 local ExtMeta = { __tostring = function(e) return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" end } @@ -120760,13 +119362,11 @@ function Codec.isExt(v) return type(v) == "table" and getmetatable(v) == ExtMeta end --- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact local function u64text(hi, lo) if hi == 0 then return string.format("%d", lo) end local digits = {} - -- long division by 10 on four 16-bit limbs local l = { math.floor(hi / 65536), hi % 65536, math.floor(lo / 65536), lo % 65536 } while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do local rem = 0 @@ -120795,7 +119395,6 @@ local function int64(st, signed) local r = st.r local hi, lo = r:u32be(), r:u32be() if signed and hi >= 0x80000000 then - -- negative: two's complement local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo if nlo == TWO32 then nlo = 0 @@ -120979,7 +119578,6 @@ if b == 0xCC then return nil, string.format("reserved type byte 0x%02x", b) end --- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) function Codec.decode(r, opts) local o= opts or {} local st= { @@ -121165,7 +119763,6 @@ if Types.isObject(v) then return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v, opts) local o= opts or {} local st= { @@ -121187,12 +119784,9 @@ return Codec end __FILES["data/nbt"] = function() --!strict --- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and --- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and --- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / --- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression --- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. --- Not supported: nothing in the format. +-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT +-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info). +-- Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -121242,18 +119836,16 @@ if value == nil then end -- ------------------------------------------------------------------------------------------------ extras -NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.info = Nbt.info NbtFormat.Nbt = Nbt return NbtFormat end __FILES["data/plist"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is --- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> --- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> --- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past --- 2^63. Note: Luau has one number type, so a real with an integral value is written back as <integer>. +-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib), +-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral +-- reals write back as <integer>. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -121550,7 +120142,7 @@ if Types.isObject(v) then end -- ------------------------------------------------------------------------------------------------ extras -Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.uid = Binary.uid Plist.isUid = Binary.isUid return Plist @@ -121558,11 +120150,7 @@ end __FILES["data/plist/Binary"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in --- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte --- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, --- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles --- are errors. Never throws: errors return nil, message. +-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. local Types = __include("Types") local Binary = {} @@ -121600,7 +120188,6 @@ if c < 0x80 then return string.char(0xF0 + math.floor(c / 262144), 0x80 + (math.floor(c / 4096)) % 64, 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) end --- decode(buf, base, len, opts) -> value | nil, message function Binary.decode(b, base, len, opts) @@ -121688,7 +120275,6 @@ if marker == 0x00 then if h >= 0x80000000 and nib == 3 then v = (h - TWO32) * TWO32 + l elseif opts and opts.bigInts == "string" and h >= 0x200000 then - -- exact decimal text of h * 2^32 + l local digits = {} local limbs = { math.floor(h / 65536), h % 65536, math.floor(l / 65536), l % 65536 } while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do @@ -121830,9 +120416,7 @@ return Binary end __FILES["data/snbt"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over --- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt --- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. -- Not supported: the 1.21.5 bool(...) / uuid(...) operations. -- ------------------------------------------------------------------------------------------------ requires @@ -121895,13 +120479,9 @@ return SnbtFormat end __FILES["data/toml"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, --- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range --- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules --- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / --- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to --- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral --- values are written as integers). +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0 +-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer / +-- float distinction (integral values write as integers). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -121920,8 +120500,7 @@ local Toml = { } -- ------------------------------------------------------------------------------------------------ sniff --- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, --- so this stays low and the extension decides +-- INI looks the same: a [table] or key = value start scores low and the extension decides @@ -121967,10 +120546,7 @@ return Toml end __FILES["data/toml/Decode"] = function() local __compat = __compat local utf8, __iter = __compat.utf8, __compat.__iter --!strict --- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with --- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control --- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and --- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset). local Text = __include("codecs/text/Text") local Types = __include("Types") @@ -122000,7 +120576,6 @@ errMsg, errAt = msg, at - 1 return nil end - -- input checks: BOM, UTF-8, control characters, bare CR if sub(s, 1, 3) == "\239\187\191" then s = sub(s, 4) end @@ -122048,7 +120623,6 @@ local t = Types.object({}, {}) local function ws(i) return (match(s, "^[ \t]*()", i) ) end - -- whitespace, newlines and comments (inside arrays) local function wsnl(i) while true do i = (match(s, "^[ \t\n]*()", i) ) @@ -122082,7 +120656,6 @@ if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then return fail("bad escape", p) end - -- strings: value, next | nil local function basic(i) local parts = {} local j = i + 1 @@ -122172,7 +120745,6 @@ local j = i + 3 return sub(s, j, e - 1) .. string.rep("'", extra), q end - -- a (dotted) key: { parts }, next | nil local function key(i) local keys= {} while true do @@ -122210,7 +120782,6 @@ if c == 34 then end end - -- numbers and datetimes local function number(i) local tok = match(s, "^[%+%-]?[%w_%.]+", i) if not tok then @@ -122524,7 +121095,6 @@ i = ws(i) end ni =ni+ 1 end - -- walk to the parent local t = root for j = 1, #keys - 1 do local k = keys[j] @@ -122604,11 +121174,7 @@ return Decode end __FILES["data/toml/Encode"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables --- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as --- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date --- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, --- message. +-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws. local Types = __include("Types") local Json = __include("codecs/text/Json") @@ -122641,7 +121207,6 @@ if find(k, "^[%w_%-]+$") then return quote(k) end --- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays local function isMap(t) if Types.isObject(t) then return true @@ -122661,7 +121226,6 @@ local function isDate(v) return Types.Date.is(v) end --- an array of tables: non-empty, every element a map local function isAot(v) if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then return false @@ -122801,7 +121365,6 @@ if st.seen[t] then return true end --- encode(t, opts) -> text | nil, message function Encode.encode(t, opts) if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then return nil, "the top level must be a table with string keys" @@ -122820,9 +121383,8 @@ return Encode end __FILES["data/xml"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: --- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not --- supported: external entities / DTDs, validation. +-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an +-- element. Not supported: external entities / DTDs, validation. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -122877,13 +121439,9 @@ return XmlFormat end __FILES["data/yaml"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / --- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as --- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null --- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. --- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). --- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; --- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases +-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style. +-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -122925,7 +121483,6 @@ local head = r:peek(256) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err function Yaml.decode(r, opts) local text = buffer.readstring(r.buf, r.base, r.limit - r.base) local docs, code, msg, at = Parse.run(text, opts) @@ -122943,7 +121500,6 @@ local text = buffer.readstring(r.buf, r.base, r.limit - r.base) end -- ------------------------------------------------------------------------------------------------ encode --- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) function Yaml.encode(value, opts) local s, err = Emit.encode(value, opts) if not s then @@ -122956,11 +121512,7 @@ return Yaml end __FILES["data/yaml/Emit"] = function() local __compat = __compat local utf8, type, __iter = __compat.utf8, __compat.type, __compat.__iter --!strict --- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when --- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars --- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as --- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad --- values (cycles, functions, collection keys) return nil, message. +-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools). local Types = __include("Types") local Base64 = __include("core/Base64") local Parse = __include("data/yaml/Parse") @@ -123053,7 +121605,6 @@ if s == "" or YAML11[s] then return true end --- a string as a scalar on a line at indentation ind (for block scalars) local function str(s, ind, key) if plainOk(s) then return s @@ -123081,7 +121632,6 @@ local isArray = Types.isArray local keyLess = Types.keyLess --- count references to tables (anchors for those seen twice); false on a cycle local function count(st, v, onStack) @@ -123107,7 +121657,6 @@ if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) the return true end --- scalar text for a non-collection value, or nil local function scalar(st, v, ind, key) local tv = type(v) if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then @@ -123127,7 +121676,6 @@ local tv = type(v) end local write --- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) function write(st, v, depth) local ind = string.rep(" ", st.step * (depth + 1)) @@ -123201,19 +121749,16 @@ local t = write(st, v, 0) if not t then return nil end - -- the top level: drop the separator write() put before the first line if string.sub(t, 1, 1) == "\n" then return string.sub(t, 2) end local body = string.sub(t, 2) if string.sub(body, 1, 1) == "&" then - -- "&id001\n- a": an anchored top-level collection return body end return body end --- encode(v, opts) -> text | nil, message function Emit.encode(v, opts) local o= opts or {} local st= { @@ -123257,13 +121802,7 @@ return Emit end __FILES["data/yaml/Parse"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): --- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with --- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared --- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless --- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core --- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a --- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it. local Text = __include("codecs/text/Text") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -123324,7 +121863,6 @@ if p ~= 1 and byte(s, p - 1) ~= 10 then return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) end --- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) local function skip(s, p) local n = #s while p <= n do @@ -123344,7 +121882,6 @@ local n = #s return p end --- the number of leading spaces on p's line, and whether a tab comes before p on it local function lineIndent(s, p) local q = p while q > 1 and byte(s, q - 1) ~= 10 do @@ -123363,7 +121900,6 @@ local function noTabs(s, p, ind) end end --- skip spaces / tabs on the line local function skipLine(s, p) return (match(s, "^[ \t]*()", p) ) end @@ -123378,7 +121914,6 @@ end local utf8char = Text.utf8char -- ------------------------------------------------------------------------------------------------ resolution --- the core schema: a plain scalar's value function Parse.resolve(t, nullv) if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then return nullv @@ -123426,7 +121961,6 @@ local function base64(t) return (Base64.decode(t)) end --- a scalar's value given its tag (nil = untagged, "!" = non-specific) local function scalarValue(st, raw, plain, tag, p) if tag == nil then return (plain and{(Parse.resolve(raw, st.null) )}or{raw @@ -123495,7 +122029,6 @@ local function collectionTag(st, tag, kind, p) end end --- expansion size of a value (nodes), memoized local function size(st, v) if type(v) ~= "table" or v == st.null then return 1 @@ -123512,7 +122045,6 @@ if type(v) ~= "table" or v == st.null then return total end -- ------------------------------------------------------------------------------------------------ properties --- anchors / tags at p -> props?, the position after them (and the spaces after them) @@ -123606,8 +122138,7 @@ local s = st.s end -- ------------------------------------------------------------------------------------------------ scalars --- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. --- Lines holding only spaces / tabs count as empty. +-- line folding: lines holding only spaces / tabs count as empty local function fold(s, p) local empties = 0 local q = p + 1 @@ -123643,7 +122174,6 @@ local ESC= { [80] = "\226\128\169", } --- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote local function quoted(st, p, ind) local s = st.s local dq = byte(s, p) == 34 @@ -123714,15 +122244,13 @@ if cp > 0x10FFFF then end end --- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind --- (block context); flow: the flow-context rules (stops at , [ ] { }). +-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { } local function plain(st, p, ind, flow) local s = st.s local parts= {} local i = p local lastEnd = p while true do - -- one line's worth local j = i local stopAt = nil while true do @@ -123750,7 +122278,6 @@ local s = st.s if stopAt or byte(s, j) == nil then return table.concat(parts), lastEnd end - -- a continuation line? local f, q = fold(s, j) local r = skipLine(s, q) local c = byte(s, r) @@ -123765,7 +122292,6 @@ local s = st.s end end --- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it local function blockScalar(st, p, ind) local s = st.s local folded = byte(s, p) == 62 @@ -123787,7 +122313,7 @@ local s = st.s end local nl = find(s, "\n", q, true) local lines= {} - local trailing = 0 -- empty lines after the last content line + local trailing = 0 if not nl then return "", #s + 1 end @@ -123826,7 +122352,6 @@ if explicit then indent = ind + 1 end end - -- the lines local r = ls local pendingEmpty = 0 local endPos = ls @@ -123883,7 +122408,7 @@ if #lines == 0 then empties = 0 end end - trailing =trailing+ empties -- empty lines after the last content line (or all of them) + trailing =trailing+ empties body = table.concat(out) end if not folded then @@ -123924,7 +122449,6 @@ local function enter(st, p) end end --- a flow node at p (after skip) -> value, next, wasEmpty local function flowNode(st, p, ind) local s = st.s local props, q = properties(st, p) @@ -123946,7 +122470,6 @@ if c == 42 then -- * local t, r = quoted(st, q, ind) return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then - -- an empty node return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), ((props and{q }or{p})[1]), true elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then corrupt("unexpected character in a flow collection", q) @@ -124076,7 +122599,7 @@ end -- ------------------------------------------------------------------------------------------------ block local blockNode --- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +-- implicit key: on one line, followed by ':' and a space or the end of the line local function implicitKey(st, p) local s = st.s @@ -124105,7 +122628,6 @@ local s = st.s end return nil, nil elseif c == 91 or c == 123 then - -- a flow collection used as a key? local e = find(s, "\n", p, true) or #s + 1 local line = sub(s, p, e - 1) if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then @@ -124150,7 +122672,7 @@ if c == 42 then end k, q = alias(st, p) q = skipLine(s, q) - q =q+ 1 -- the ':' + q =q+ 1 elseif c == 34 or c == 39 then local t, r = quoted(st, p, -1) if find(sub(s, p, r - 1), "\n", 1, true) then @@ -124170,7 +122692,6 @@ end return checkKey(st, k, p), q end --- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null local function nextLineNode(st, ind, p, seqAt, mapParent) local s = st.s local r = skip(s, p) @@ -124184,7 +122705,6 @@ local s = st.s return st.null, p end --- the value after a ':' (at p, just past it) of a mapping at column mc local function mapValue(st, mc, p, explicit) local s = st.s local r = skipLine(s, p) @@ -124302,7 +122822,6 @@ if c == nil or c == 10 or (c == 35 and r > p + 1) then return t, q end --- the node at q after its properties (props may be nil); start = where the properties began local function afterProps(st, ind, start, q, props, inline, mapParent) local s = st.s local tag = props and props.tag @@ -124369,9 +122888,6 @@ local s = st.s return finish(st, props, scalarValue(st, text, true, tag, q)), e end --- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the --- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's --- indentation may follow properties that end their line. function blockNode(st, ind, p, inline, mapParent) local s = st.s local props, q = properties(st, p) @@ -124511,7 +123027,6 @@ if q > n or docMarker(s, q) then p = q else if explicit and not find(sub(s, p, q), "\n", 1, true) then - -- content on the "---" line local ok, _, q2 = pcall(properties, st, q) local c = byte(s, q2) if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then @@ -124540,7 +123055,6 @@ __DARKLUA_CONTINUE_23=true until true if not __DARKLUA_CONTINUE_23 then break en return docs end --- run(text, opts) -> docs | nil, code, message, offset function Parse.run(text, opts) local o= opts or {} local s = text @@ -124581,15 +123095,9 @@ return Parse end __FILES["font/bdf"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the --- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in --- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), --- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to --- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for --- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and --- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font --- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. --- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1 +-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes +-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -124805,7 +123313,6 @@ local o= opts or {} local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil local px = strike.size - -- the font bounding box local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, g in __iter(strike.glyphs) do if g.width > 0 and g.height > 0 then @@ -124826,7 +123333,6 @@ local o= opts or {} string.format("SIZE %d 75 75", px), string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), } - -- the default glyph: the strike's default, else glyph 0 local defaultIndex = (strike.default or 0) + 1 local props= { { "FAMILY_NAME", quote(family) }, @@ -124878,13 +123384,9 @@ return Bdf end __FILES["font/bmfont"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict --- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and --- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize --- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are --- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the --- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / --- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. --- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). +-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont +-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. +-- Not supported: packed multi-channel glyphs (read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -124922,7 +123424,6 @@ local Bmfont = { - function Bmfont.sniff(r) @@ -124940,7 +123441,6 @@ local head = r:peek(64) end -- ------------------------------------------------------------------------------------------------ decode --- the Font value local Face = {} Face.__index = Face @@ -124959,10 +123459,9 @@ local ca, cb = self._chars[a], self._chars[b] return self._kern[ca.id * 2097152 + cb.id] or 0 end function Face.outline(_self, _g) -return nil -- bitmap font +return nil end --- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil function Face.loadPages(self, loader) local load = loader or self.meta.pageLoader if type(load) ~= "function" then @@ -124982,8 +123481,6 @@ end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 --- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; --- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. function Face.rasterize(self, g, px) local c = self._chars[g] if not c then @@ -125020,7 +123517,6 @@ local c = self._chars[g] return img end --- the Font value of a description local function face(d, variant) local f= setmetatable({ kind = "font", @@ -125123,7 +123619,6 @@ if type(font) ~= "table" or font.kind ~= "font" then local d = type(font.meta) == "table" and font.meta.bmfont or nil local pages = font.pages if d == nil then - -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") @@ -125141,7 +123636,6 @@ if type(font) ~= "table" or font.kind ~= "font" then if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end - -- the page images into opts.files, under the names the descriptor gives them local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then @@ -125189,9 +123683,6 @@ local out = {} return out end --- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are --- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are --- kept (rounded to pixels). function Bmfont.bake(font, opts) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") @@ -125320,12 +123811,7 @@ return Bmfont end __FILES["font/bmfont/Parse"] = function() local __compat = __compat local bit32, utf8, __iter = __compat.bit32, __compat.utf8, __compat.__iter --!strict --- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one --- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation --- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the --- descriptor has no nesting that matters, no text content). --- --- Never throws on bad input: parse functions return nil, message. +-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html). local Bytes = __include("core/Bytes") local Parse = {} @@ -125350,7 +123836,7 @@ local Parse = {} -local LIMIT = 1000000 -- chars / kernings +local LIMIT = 1000000 local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } @@ -125375,7 +123861,6 @@ local function new() return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } end --- one tag's attributes (already split into key -> string) into the description local function apply(d, tag, a) if tag == "info" then d.info.face = a.face or "" @@ -125779,12 +124264,9 @@ return Parse end __FILES["font/eot"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, --- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and --- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot --- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, --- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C --- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. +-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header +-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes. +-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126014,12 +124496,8 @@ return Eot end __FILES["font/fon"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the --- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE --- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first --- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI --- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). --- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as +-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252. -- Not supported: vector FNT (Err.UNSUPPORTED), writing. -- ------------------------------------------------------------------------------------------------ requires @@ -126065,7 +124543,6 @@ local h = r:peek(64) end -- ------------------------------------------------------------------------------------------------ decode --- one FNT resource -> Font local function fnt(r) local version = r:u16le() local total = r:u32le() @@ -126160,7 +124637,6 @@ local version = r:u16le() }), nil end --- the RT_FONT resources of an NE executable: { { offset, length } } local function neFonts(r, ne) local rt = r:sub(ne + 0x24, 2):u16le() local t = r:sub(ne + rt) @@ -126190,7 +124666,7 @@ local rt = r:sub(ne + 0x24, 2):u16le() return out, nil end --- the RT_FONT (8) resources of a PE executable: { { offset, length } } +-- RT_FONT: resource type 8 local function peFonts(r, pe) local h = r:sub(pe + 4, 20) h:skip(2) @@ -126205,7 +124681,6 @@ local h = r:sub(pe + 4, 20) if opt.err or rsrcRva == 0 then return {}, nil end - -- the section holding the resources local secs = r:sub(pe + 24 + optSize, nsec * 40) local base, rva0 = -1, 0 for _ = 1, nsec do @@ -126304,15 +124779,9 @@ return Fon end __FILES["font/hershey"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph --- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", --- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths --- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster --- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of --- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i --- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph --- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: --- writing, the Hershey "occidental" index files (.hmp), filled rendering. +-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character +-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up. +-- Not supported: writing, .hmp index files, filled rendering. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126398,7 +124867,6 @@ local gl = self._glyphs[g + 1] return out end --- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) function Face.rasterize(self, g, px) local gl = self._glyphs[g + 1] if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then @@ -126506,13 +124974,8 @@ return Hershey end __FILES["font/pcf"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the --- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), --- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad --- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. --- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets --- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver --- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. +-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver +-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126545,7 +125008,6 @@ end --- a reader positioned after a table's format word, with the integer readers for its byte order local function open(r, t) @@ -126598,7 +125060,6 @@ local o= opts or {} if r.err then return nil, r.err end - -- properties local props= {} local pt = open(r, tables[PROPERTIES]) if pt then @@ -126629,14 +125090,12 @@ if off < 0 or off >= strSize then return nil, Err.new(Err.TRUNCATED, "properties table") end end - -- accelerators: ascent / descent local ascent, descent= nil, nil local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) if at then at.r:skip(8) ascent, descent = i32(at), i32(at) end - -- metrics local mt = open(r, tables[METRICS]) if not mt then return nil, Err.new(Err.CORRUPT, "no METRICS table") @@ -126659,7 +125118,6 @@ if off < 0 or off >= strSize then if mt.r.err then return nil, Err.new(Err.TRUNCATED, "metrics table") end - -- bitmaps local bt = open(r, tables[BITMAPS]) if not bt then return nil, Err.new(Err.CORRUPT, "no BITMAPS table") @@ -126709,7 +125167,6 @@ if off < 0 or off >= strSize then local px = Bitmap.unpack(bits, offsets[k], w, h, stride) glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } end - -- encodings local encodings= {} local default= nil local et = open(r, tables[BDF_ENCODINGS]) @@ -126740,7 +125197,6 @@ if off < 0 or off >= strSize then end end end - -- glyph names local nt = open(r, tables[GLYPH_NAMES]) if nt then local n = u32(nt) @@ -126798,16 +125254,9 @@ return Pcf end __FILES["font/psf"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 --- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and --- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry --- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map --- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell --- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: --- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through --- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps --- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd --- project's psf documentation (Andries Brouwer). +-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF / +-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the +-- cell height. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -126902,7 +125351,7 @@ local o= opts or {} end local map= {} local sequences = {} - local unicodeTable= {} -- per glyph: code points and { sequence } tables, in file order + local unicodeTable= {} if hasTable then local t = r:sub(glyphAt + count * size) for i = 0, count - 1 do @@ -126940,7 +125389,6 @@ __DARKLUA_CONTINUE_3=true break inSeq = true __DARKLUA_CONTINUE_3=true break end - -- UTF-8 local n = b < 0x80 and 0 or(b >= 0xF0 and 3 or(b >= 0xE0 and 2 or(b >= 0xC0 and 1 or-1 ))) if n < 0 then return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") @@ -127007,7 +125455,6 @@ local o= opts or {} if n == 0 then return nil, Err.new(Err.ARG, "no glyphs") end - -- the cell local width = 0 for _, g in __iter(glyphs) do width = math.max(width, g.advance, g.left + g.width) @@ -127040,7 +125487,6 @@ local o= opts or {} end buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) end - -- the Unicode table: each glyph's code point and the extra mappings onto it local cps= {} for i = 1, count do cps[i] = {} @@ -127128,11 +125574,9 @@ return Psf end __FILES["font/ttf"] = function() --!strict --- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. --- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. +-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype +-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap / +-- colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -127173,7 +125617,6 @@ local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) end -- ------------------------------------------------------------------------------------------------ extras --- count(r) -> the number of fonts in the file (1 unless a collection) function Ttf.count(r) return TrueType.count(r.buf, r.base) end @@ -127182,14 +125625,9 @@ return Ttf end __FILES["font/type1"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the --- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, --- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, --- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring --- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph --- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through --- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple --- Master and CID-keyed (Type 9 / 11) fonts, writing. +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font +-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames. +-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -127224,7 +125662,6 @@ local h = r:peek(64) end -- ------------------------------------------------------------------------------------------------ decode --- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA local function sections(r) local b = r.buf local n = r:size() @@ -127387,7 +125824,6 @@ local o= opts or {} local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) local ptext = buffer.tostring(priv) local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 - -- Subrs local subrs= {} local function charstring(p, len) local raw = binaryAt(priv, p, len) @@ -127424,7 +125860,6 @@ if i > 65535 then p = e + n end end - -- CharStrings local names= {} local charstrings= {} local byName= {} @@ -127434,8 +125869,7 @@ if i > 65535 then if not s then break end - local e = e0 -- stop at the end of the dictionary - + local e = e0 if string.find(string.sub(ptext, p, s), "%send%s") then break end @@ -127464,7 +125898,6 @@ local cs = charstring(e, n) charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] byName[names[1] ], byName[names[nd + 1] ] = 0, nd end - -- the encoding local encoding= {} if string.find(clear, "/Encoding%s+StandardEncoding") then for code, gname in __iter(GlyphNames.STANDARD) do @@ -127489,7 +125922,6 @@ local cs = charstring(e, n) cmap[cp] = k - 1 end end - -- font matrix / bbox local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") local scale = 0.001 if fm then @@ -127552,15 +125984,8 @@ return Type1 end __FILES["font/type1/Charstring"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted --- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side --- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, --- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; --- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, --- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the --- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored. local Charstring = {} --- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result @@ -127571,7 +125996,7 @@ function Charstring.run(cs, ctx) local cmds= {} local stack= {} local sp = 0 - local ps= {} -- the PostScript stack callothersubr / pop use + local ps= {} local x, y = 0, 0 local advance, sbx = 0, 0 local open = false @@ -127837,9 +126262,8 @@ return Charstring end __FILES["font/woff"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended --- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through +-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -127867,7 +126291,6 @@ return r:peek(4) == "wOFF" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err function Woff.sfnt(r, opts) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local base = r.base @@ -127971,9 +126394,8 @@ return Woff end __FILES["font/woff2"] = function() --!strict --- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. +-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms, +-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -128002,7 +126424,6 @@ return r:peek(4) == "wOF2" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err function Woff2.sfnt(r, opts) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local at = r.base @@ -128030,12 +126451,7 @@ return Woff2 end __FILES["font/woff2/Rebuild"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table --- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, --- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx --- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). --- --- Never throws: malformed data returns nil, message. +-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx). local Bytes = __include("core/Bytes") local Brotli = __include("codecs/compress/Brotli") @@ -128070,7 +126486,6 @@ local v = 0 end return nil end --- a cursor over a stream inside the decompressed block local function stream(b, p, n) @@ -128108,7 +126523,6 @@ local function withSign(flag, v) return (band(flag, 1) ~= 0 and{v }or{(-v )})[1]end --- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat local function glyf(b, p, n, maxBytes) local h = stream(b, p, n) su16(h) -- reserved @@ -128163,7 +126577,6 @@ return band(readu8(b, bboxBits + math.floor(g / 8)), rshift(0x80, g % 8)) ~= 0 return nil, "empty glyph with a bounding box" end elseif nc > 0 then - -- simple glyph local ends = table.create(nc, 0) local total = 0 for c = 1, nc do @@ -128394,7 +126807,6 @@ local s = stream(b, p, n) return out:finish(), nil end --- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") function Rebuild.sfnt(r, maxBytes) if not r:match("wOF2") then return nil, "bad signature", "corrupt" @@ -128464,7 +126876,6 @@ return nil, "brotli: " .. tostring(e.message), e.code == "LIMIT" and"limit" or"c if buffer.len(data) < streamTotal then return nil, "decompressed stream shorter than the tables", "corrupt" end - -- the tables, glyf / loca / hmtx rebuilt local byTag= {} for _, e in __iter(dir) do byTag[e.tag] = e @@ -128582,11 +126993,6 @@ __FILES["host"] = function() local __compat = __compat local typeof, type = __compat.typeof, __compat.type --!strict -- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE -- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). --- --- local host = require("rosetta.host") --- print(host.name) -- "roblox" | "love" | "luajit" | "luau" --- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO --- -- where there is no file system) local Err = __include("core/Err") @@ -128620,9 +127026,7 @@ elseif name == "luajit" then else host = (__include("host/Luau") ) end --- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine --- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only --- allows more traces; set _G.ROSETTA_NO_JIT_TUNE = true before requiring the library to leave them alone. +-- LuaJIT: the big decoders outgrow the default 1000 traces / 8 MB of mcode; _G.ROSETTA_NO_JIT_TUNE = true skips this. if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536") end @@ -128633,10 +127037,7 @@ end __FILES["host/Love"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for --- paths outside them; converts the standard types to LÖVE objects: --- host.toImageData(img) -> love ImageData (rgba8) --- host.fromImageData(imageData) -> Image (rgba8) --- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit) +-- paths outside them. ImageData is rgba8; SoundData is 16-bit. local Err = __include("core/Err") local Types = __include("Types") @@ -128675,7 +127076,6 @@ local fs = love().filesystem return buffer.fromstring(s), nil end --- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io function Host.writeFile(path, data) local s = buffer.tostring(data) if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then @@ -128706,7 +127106,6 @@ if love().filesystem.getInfo(path, "file") then return false end --- toImageData(img) -> ImageData | nil, Err function Host.toImageData(img) if img.format ~= "rgba8" then return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) @@ -128723,7 +127122,6 @@ if F and B.toffi then return love().image.newImageData(img.width, img.height, "rgba8", bytes) end --- fromImageData(imageData) -> Image (rgba8 copy) function Host.fromImageData(id) local w, h = id:getDimensions() local img = Types.Image.new(w, h, "rgba8") @@ -128738,11 +127136,9 @@ if F and B.toffi and id:getFormat() == "rgba8" then return img end --- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end). function Host.toSoundData(a) local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate if samples == nil then - -- a Decoder: read everything local parts, total = {}, 0 while true do local out, n = a:read(65536) @@ -128857,12 +127253,7 @@ end __FILES["host/Roblox"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the --- standard types to engine objects: --- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first) --- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh --- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours) --- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh --- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime). +-- standard types to EditableImage / EditableMesh. local Err = __include("core/Err") local Types = __include("Types") @@ -128882,7 +127273,6 @@ function Host.exists(_path) return false end --- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8". function Host.toEditableImage(img) if img.format ~= "rgba8" then return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) @@ -128898,25 +127288,8 @@ if img.format ~= "rgba8" then ei:WritePixelsBuffer(Vector2.zero, size, img.pixels) return ei end --- ---------------------------------------------------------------------------------------------------------- meshes --- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One --- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client --- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through --- AssetService:CreateEditableMeshAsync), destroy it, then build the next. --- --- local prims = F.ops.mesh.merge(scene, { byMaterial = true }) --- for _, prim in prims do --- for _, page in assert(F.host.meshPages(prim)) do --- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs --- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em)) --- part.Position = Vector3.new(centre[1], centre[2], centre[3]) --- end --- end --- --- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y") --- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV --- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted. --- the index of each corner (0-based vertex numbers) or nil, Err +-- EditableMesh limits (measured in Studio): ~20k triangles and 60k vertices each, 8 growable per client. +-- Roblox is y-up, right-handed, counter-clockwise front faces, as glTF; EditableMesh colours are sRGB, COLOR_0 linear. @@ -128982,8 +127355,6 @@ if type(prim) ~= "table" or type(prim.attributes) ~= "table" or type(prim.attrib })[1] return math.floor(n / 3), nil end --- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces --- counted when doubleSided) and maxVertices. function Host.meshPages(prim, opts) local tris, err = checkPrim(prim) if err then @@ -129052,8 +127423,6 @@ c = math.clamp(c, 0, 1) return (c <= 0.0031308 and((c * 12.92 ))or((1.055 * c ^ (1 / 2.4) - 0.055 )))end --- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for --- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours). function Host.pageData(prim, page, opts) local _, err = checkPrim(prim) if err then @@ -129096,7 +127465,6 @@ local _, err = checkPrim(prim) positions[j + 2] = ((getP )(v, 1) - oy) * sy positions[j + 3] = ((getP )(v, 2) - oz) * sz if normals then - -- normals of a scaled mesh scale by the inverse local x, y, z = (getN )(v, 0) / sx, (getN )(v, 1) / sy, (getN )(v, 2) / sz local len = math.sqrt(x * x + y * y + z * z) if len > 0 then @@ -129131,9 +127499,6 @@ local _, err = checkPrim(prim) }, nil end --- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole --- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart --- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then. function Host.toEditableMesh(prim, page, opts) local o= opts or {} local pg = page @@ -129188,7 +127553,6 @@ local em = o.editableMesh if C and cids then local k = (i - 1) * 4 local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4] - -- equal colours share one id (voxel palettes, flat-coloured models) local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5)) local id = palette[key] if not id then @@ -129247,13 +127611,9 @@ return Host end __FILES["image/ani"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; --- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, --- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) --- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames --- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors --- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a --- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). +-- image/ani: Windows animated cursor (RIFF "ACON": anih header, rate / seq chunks, LIST fram of ICO / CUR chunks). +-- Supports: the steps as img.frames (seq order; rate or iDispRate in 1/60 s jiffies), CUR hotspots, INFO title / +-- author; icons through opts.decodeImage / opts.encodeImage. Not supported: raw frame bitmaps (AF_ICON clear). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -129315,7 +127675,6 @@ local f, ferr = Riff.read(r) if not decodeImage then return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") end - -- the icon chunks local icons= {} for _, c in __iter(f.chunks) do if c.id == "LIST" and Riff.listType(f, c) == "fram" then @@ -129346,7 +127705,7 @@ local f, ferr = Riff.read(r) local im = icons[idx + 1] if not im then if s >= #icons and not seq then - break -- fewer icons than steps: keep what is there + break end return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) end @@ -129432,16 +127791,9 @@ return Ani end __FILES["image/blp"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written --- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. --- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: --- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual --- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); --- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); --- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha --- type 0 / 1 / 7), uncompressed BGRA. --- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). --- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). +-- image/blp: Blizzard BLP textures (BLP1 Warcraft III, BLP2 World of Warcraft), from the wowdev.wiki BLP page. +-- Supports: mip 0 of BLP1 JPEG (4 components: BGRA, no colour conversion) / palette and BLP2 palette (1 / 4 / 8-bit +-- alpha, LSB first) / DXT1 / DXT3 / DXT5 / BGRA; writes BLP2 BGRA + mips. Not supported: BLP0 (.b00 mips), BLP2 JPEG. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -129474,13 +127826,11 @@ local m = r:peek(4) )end -- ------------------------------------------------------------------------------------------------ decode --- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha local function swap(v, a) local b, g, r = v % 256, (math.floor(v / 256)) % 256, (math.floor(v / 65536)) % 256 return r + g * 256 + b * 65536 + a * 16777216 end --- alpha of pixel i from a packed plane at p of depth bits local function alphaAt(b, p, depth, i) if depth == 8 then return readu8(b, p + i) @@ -129623,7 +127973,6 @@ if (not v2 and kind == 0) or (v2 and kind == 0) then end -- ------------------------------------------------------------------------------------------------ encode --- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) local function halve(px, w, h) local nw, nh = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) local out = buffer.create(nw * nh * 4) @@ -129701,17 +128050,9 @@ end __FILES["image/bmp"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!optimize 2 --- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a --- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 --- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or --- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), --- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the --- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit --- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). --- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance --- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with --- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. --- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. +-- image/bmp: Windows / OS/2 BMP; absorbed from bmp-luau b86aed6 (same author), new encoder. Supports: headers 12 / +-- 16..64 / 40 / 52 / 56 / 108 / 124, 1..32 bpp, BITFIELDS / ALPHABITFIELDS, RLE8 / RLE4, both row orders, Pillow's +-- leniency and mask scaling; writes 8 / 24 / 32 bpp as Pillow. Not supported: embedded JPEG / PNG, OS/2 Huffman, RLE24. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -129755,7 +128096,6 @@ local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "p local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz --- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) local function whole(r) if r.base == 0 and r.limit == buffer.len(r.buf) then return r.buf @@ -129771,7 +128111,6 @@ function Bmp.sniff(r) if r:peek(2) ~= "BM" then return 0 end - -- a known header size: a strong match; "BM" alone is weak local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then return 0.9 @@ -129780,7 +128119,6 @@ if r:peek(2) ~= "BM" then end -- ------------------------------------------------------------------------------------------------ decode --- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err local function parseHeader(buf) local n = buffer.len(buf) if n < 18 then @@ -129828,13 +128166,11 @@ local n = buffer.len(buf) return info end --- info(r) -> Info | nil, Err: the header without decoding the pixels function Bmp.info(r) return parseHeader(whole(r)) end --- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate --- the top bits instead, which can differ by 1). m = 0 -> { empty }. +-- v * 255 // m, as Pillow (browsers replicate the top bits, which can differ by 1) local function scaleTable(m, empty) local t = buffer.create(m + 1) if m == 0 then @@ -129847,7 +128183,7 @@ local t = buffer.create(m + 1) return t end --- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +-- a mask wider than 16 bits keeps its top 16 local function channel(mask, empty) if mask == 0 then return 0, 0, scaleTable(0, empty) @@ -129867,7 +128203,6 @@ if mask == 0 then return sh, m, scaleTable(m, empty) end --- decode(r, opts?) -> rgba8 Image | nil, Err function Bmp.decode(r, opts) local buf = whole(r) local info, herr = parseHeader(buf) @@ -129937,7 +128272,6 @@ local buf = whole(r) end end - -- palette local entrySize = hs == 12 and 3 or 4 local declared = (hs >= 36 and{(readu32(buf, 46) )}or{0 })[1] local palCount = 0 @@ -130035,7 +128369,6 @@ local buf = whole(r) end -- ------------------------------------------------------------------------------------------------ encode --- encode(img, opts?) -> buffer | nil, Err function Bmp.encode(img, opts) if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") @@ -130131,19 +128464,9 @@ return Bmp end __FILES["image/dds"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new --- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / --- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the --- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the --- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six --- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there --- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / --- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by --- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. --- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 --- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the --- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), --- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. +-- image/dds: DirectDraw Surface (Microsoft DDS guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10). Supports: DXGI +-- formats with a pixel layout, legacy FourCC and bit-mask formats, mips, cube maps, arrays, volumes; writes rgba8 / BC1 +-- / BC3 / BC4 / BC5 / rgba16 / rgbaf32. Not supported: planar video (NV12, P010), P8, R1_UNORM, stencil formats. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -130181,7 +128504,6 @@ local Dds = { - local DXGI= { [1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i", [5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i", @@ -130250,7 +128572,6 @@ local function u32(b, o) return buffer.readu32(b, o) end --- info(r) -> Info | nil, Err (the headers only) function Dds.info(r) local b, o, n = r.buf, r.base, r.limit - r.base if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then @@ -130360,7 +128681,6 @@ local b, o, n = r.buf, r.base, r.limit - r.base if not d then return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) end - -- the common masks map onto named texel formats (fast paths, sane names) local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) local named = ({ ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", @@ -130397,7 +128717,6 @@ local b, o, n = r.buf, r.base, r.limit - r.base return info, nil end --- the bytes of one surface of format f local function surfaceSize(info, w, h) if info.format == "masked" then return (info.masked ).bytes * w * h @@ -130491,7 +128810,6 @@ end local BYTES_PF= { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } local DX10_OUT= { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } --- the surface bytes of one image in format f local function surface(img, f, opts) local w, h, px = img.width, img.height, img.pixels if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then @@ -130580,7 +128898,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "n ) if pf ~= needs then return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) end - -- surfaces: the frames (array / cube faces) or the image local images= { img } if img.frames and #img.frames > 1 then images = {} @@ -130630,19 +128947,9 @@ return Dds end __FILES["image/exr"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ --- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and --- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts --- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), --- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any --- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image --- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. --- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear --- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) --- for colour, round(clamp(a, 0, 1) * 255) for alpha. --- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only --- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / --- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). +-- image/exr: OpenEXR (openexr.com file layout docs; PIZ after OpenEXR, BSD-3-Clause: licenses/openexr-LICENSE.md). +-- Supports: single / multipart, scanline / tiled (mip / rip level 0, mips), NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT +-- / UINT, subsampling, layers; writes scanlines. Not supported: deep, PXR24 / B44(A) / DWA / HTJ2K / ZSTD. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -130722,7 +129029,6 @@ local function f32(b, o) return readf32(b, o) end --- one attribute value of a known type local function value(b, p, size, typ) if typ == "chlist" then local list= {} @@ -130777,7 +129083,6 @@ if typ == "chlist" then return raw end --- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err local function header(b, p, limit) local attrs= {} local types= {} @@ -130810,7 +129115,6 @@ local attrs= {} end end --- level sizes of a tiled part local function levelSize(n, l, roundUp) local d = 2 ^ l return math.max(1, (roundUp and{(math.ceil(n / d) )}or{(math.floor(n / d))})[1]) @@ -130832,7 +129136,6 @@ local c = 1 return count(w), count(h) end --- chunk count of a part (single-part files: computed) local function chunkCount(pt) local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 if not pt.tiled then @@ -130918,7 +129221,6 @@ local b, base, limit = r.buf, r.base, r.limit if multi then p =p+ 1 end - -- offset tables for _, pt in __iter(info.parts) do local n = (type(pt.attrs.chunkCount) == "number" and{pt.attrs.chunkCount }or{((LINES[pt.compression] and{(chunkCount(pt) )}or{0})[1]) })[1] if n < 0 or n > 2 ^ 24 then @@ -130937,15 +129239,12 @@ local b, base, limit = r.buf, r.base, r.limit return info, nil end --- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err function Exr.info(r) return parse(r) end --- bytes of a sample kind local SIZE = { [0] = 4, 2, 4 } --- number of multiples of s in [a, b] local function samples(a, b, s) return math.floor(b / s )- math.floor((a - 1) / s )end @@ -130959,7 +129258,6 @@ local px = buffer.create(pw * ph * 16) end return px end --- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) local function block(part, target, data, dp, y0, y1, x0, bw, plane, pw, ph, ox, oy) local p = dp for y = y0, y1 do @@ -131004,7 +129302,6 @@ local p = dp return nil end --- the raw bytes of a block (uncompressed size raw) local function unpack(b, comp, part, p, size, raw, y0, y1, x0, bw) if size == raw or comp == 0 then if size < raw then @@ -131074,7 +129371,6 @@ if info.deep or (part.type and string.find(part.type, "deep")) then if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel -> output component local prefix = (opts and opts.layer and((opts.layer .. "." ))or("" )) local target= {} local hasRgb = false @@ -131097,7 +129393,6 @@ if info.deep or (part.type and string.find(part.type, "deep")) then end end local multi = info.multipart - -- offsets: single-part tables with holes are rebuilt from the chunk sequence local offsets = part.offsets local bad = false for _, o in __iter(offsets) do @@ -131143,7 +129438,7 @@ if info.deep or (part.type and string.find(part.type, "deep")) then ) end end - local planes= { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local planes= { [0] = newPlane(w, h) } local tiles = part.tiles local roundUp = tiles ~= nil and tiles[4] == 1 local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 @@ -131315,7 +129610,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf return nil, Err.new(Err.ARG, "pixelType must be half or float") end local level = opts and opts.level or 6 - -- the float values local n = w * h local fl = buffer.create(n * 16) if img.format == "rgbaf32" then @@ -131341,8 +129635,7 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf local sz = kind == 1 and 2 or 4 local lpb = LINES[comp] local nblocks = math.floor((h + lpb - 1) / lpb -) -- header - local hw = Bytes.writer(512) +) local hw = Bytes.writer(512) hw:string(MAGIC) hw:u32le(2) local cl = Bytes.writer() @@ -131416,9 +129709,7 @@ __FILES["image/exr/Codec"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- --- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), --- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +-- image/exr/Codec: OpenEXR RLE / ZIP / ZIPS blocks and sample conversion (after ImfZip / ImfRle, BSD-3-Clause). local Deflate = __include("codecs/compress/Deflate") local Half = __include("codecs/image/Half") @@ -131427,7 +129718,6 @@ local Codec = {} local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 local HALF = Half.TABLE --- undoes the predictor and the interleave of t (n bytes) -> a new buffer local function reconstruct(t, n) local prev = (n > 0 and{(readu8(t, 0) )}or{0 })[1] for i = 1, n - 1 do @@ -131445,7 +129735,6 @@ local prev = (n > 0 and{(readu8(t, 0) )}or{0 return out end --- rle(src, p, n, outSize) -> the raw block | nil, message function Codec.rle(src, p, n, outSize) local t = buffer.create(outSize) local o, stop = 0, p + n @@ -131475,7 +129764,6 @@ local t = buffer.create(outSize) return reconstruct(t, outSize), nil end --- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) function Codec.unzip(src, p, n, outSize) local t, err = Deflate.zlib(src, p, n, outSize) if not t then @@ -131487,7 +129775,6 @@ local t, err = Deflate.zlib(src, p, n, outSize) return reconstruct(t, outSize), nil end --- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) function Codec.zip(raw, level) local n = buffer.len(raw) local t = buffer.create(n) @@ -131509,8 +129796,6 @@ local n = buffer.len(raw) return (Deflate.zlibCompress(t, { level = level }) ) end --- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into --- dst (f32) at byte offset d, step bytes apart; returns the source offset after them function Codec.samples(src, p, count, kind, dst, d, step) if kind == 1 then for i = 0, count - 1 do @@ -131535,10 +129820,7 @@ __FILES["image/exr/Piz"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor --- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman --- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit --- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +-- image/exr/Piz: OpenEXR PIZ decompressor (after ImfPizCompressor / ImfHuf / ImfWav, BSD-3-Clause). local Piz = {} local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 @@ -131550,7 +129832,6 @@ local DECBITS = 14 local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 -- ------------------------------------------------------------------------------------------------ Huffman --- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) local function unpackTable(src, p, limit, im, iM, len) local c, lc = 0, 0 local function bits(n) @@ -131603,7 +129884,6 @@ while lc < n do return p end --- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message local function huffman(src, p, n, out, nRaw) if n == 0 then return (nRaw == 0 and{nil }or{"empty Huffman data" @@ -131670,7 +129950,6 @@ end end end end end - -- decode MSB-first from a zero-padded copy local nbytes = math.floor((nBits + 7) / 8 ) local data = buffer.create(nbytes + 8) buffer.copy(data, 0, src, q, nbytes) @@ -131745,7 +130024,6 @@ end end end -- ------------------------------------------------------------------------------------------------ wavelet --- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) local function wav2Decode(t, base, nx, ox, ny, oy, mx) local w14 = mx < 16384 local n = math.min(nx, ny) @@ -131811,9 +130089,6 @@ if w14 then ) end end -- ------------------------------------------------------------------------------------------------ decode --- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. --- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and --- ySampling. @@ -131847,7 +130122,6 @@ local total = 0 buffer.copy(bitmap, minNZ, src, p, cnt) p =p+ cnt end - -- reverse LUT local lut = buffer.create(USHORT_RANGE * 2) local k = 0 for i = 0, USHORT_RANGE - 1 do @@ -131882,7 +130156,6 @@ local total = 0 for i = 0, total - 1 do writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) end - -- planes -> scanlines local o = 0 local cursor = table.clone(starts) for y = minY, maxY do @@ -131902,20 +130175,9 @@ return Piz end __FILES["image/gif"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image --- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames --- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / --- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames --- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize --- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with --- alpha < 128 as the transparent index. --- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" --- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). --- --- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every --- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the --- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as --- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). +-- image/gif: GIF87a / GIF89a, from the GIF89a spec (CompuServe 1990). Supports: every image, interlace, LZW code sizes +-- 1..8, transparency, GCE delays / disposal, NETSCAPE2.0 / ANIMEXTS1.0 loops, comments; writes quantized frames. Not +-- supported: the plain text extension, the aspect ratio, the user input flag, blend "source" frames. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -131950,7 +130212,6 @@ local Gif = { - local readu8 = buffer.readu8 local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } local DISPOSE_CODE= { none = 1, background = 2, previous = 3 } @@ -131962,7 +130223,6 @@ local s = r:peek(6) end -- ------------------------------------------------------------------------------------------------ decode --- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list local function colorTable(b, p, n) local t = buffer.create(1024) local list= (table.create(n) ) @@ -132013,14 +130273,12 @@ local maxPixels = opts and opts.maxPixels or 2 ^ 26 local comments= {} local loops= nil local total = 0 - -- the pending Graphic Control Extension local delay, dispose, trans = 0, 0, -1 local truncated = false local interlacedAny = false local localTables = 0 local minCode = 8 local limit = r.limit - -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) local function subBlocks() local p = r.pos local n = 0 @@ -132190,7 +130448,6 @@ local p = r.pos break end else - -- junk between blocks: stop here, keeping what was read if #frames == 0 then return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) end @@ -132243,7 +130500,6 @@ for i = 0, n - 1 do return false end --- palette list -> padded table bytes (power of two entries, >= 2) and its size code local function writeTable(w, pal) local bits = 1 while bit32.lshift(1, bits) < #pal do @@ -132284,7 +130540,6 @@ if not validImage(img) then return nil, Err.new(Err.ARG, "method must be mediancut or octree") end local dither = opts and opts.dither or false - -- the frames to write: { image, x, y, delay, dispose } local list= {} if type(img.frames) == "table" and #(img.frames ) > 0 then for i, f in __iter(img.frames) do @@ -132305,13 +130560,11 @@ if not validImage(img) then if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then return nil, Err.new(Err.ARG, "loops must be 0..65536") end - -- palettes local shared = (opts and opts.globalPalette) or not animated local qopts= { method = method, dither = dither } local globalPal= nil local globalTrans = false if shared then - -- every frame's pixels together local npx = 0 for _, f in __iter(list) do npx =npx+ f.image.width * f.image.height @@ -132440,15 +130693,12 @@ __FILES["image/gif/Decode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to --- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every --- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas. local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Decode = {} --- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from --- 2, every 2nd from 1) +-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1 local function interlacedRow(fh) local map = table.create(fh, 0) local r = 0 @@ -132463,8 +130713,6 @@ local map = table.create(fh, 0) return map end --- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the --- transparent one already alpha 0) function Decode.toRgba(indexes, fw, fh, interlaced, palette, out) local rows = (interlaced and{(interlacedRow(fh) )}or{nil })[1] for y = 0, fh - 1 do @@ -132476,7 +130724,6 @@ function Decode.toRgba(indexes, fw, fh, interlaced, palette, out) end end --- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) function Decode.draw(canvas, cw, ch, frame, fx, fy, fw, fh) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) @@ -132492,7 +130739,6 @@ function Decode.draw(canvas, cw, ch, frame, fx, fy, fw, fh) end end --- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) function Decode.clear(canvas, cw, ch, fx, fy, fw, fh) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) @@ -132508,14 +130754,9 @@ return Decode end __FILES["image/hdr"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. --- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of --- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution --- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. --- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: --- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a --- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). --- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), from the Radiance file format notes and rgbe.c. Supports: "#?" headers, +-- 32-bit_rle_rgbe, EXPOSURE (kept, not applied), the eight orientations, flat / old / new RLE; writes -Y +X new RLE. +-- Not supported: 32-bit_rle_xyze, PRIMARIES / COLORCORR (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -132566,7 +130807,6 @@ function Hdr.decode(r, opts) local maxPixels = opts and opts.maxPixels or 2 ^ 26 local b, limit = r.buf, r.limit local p = r.base - -- header lines up to the first empty one local function line() local s = p while p < limit and buffer.readu8(b, p) ~= 10 do @@ -132696,7 +130936,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf local o= opts or {} local px = img.pixels if bpp == 4 then - -- rgba8 through the inverse of the decoder's display curve local lut = table.create(256, 0) for v = 0, 255 do lut[v + 1] = (v / 255) ^ 2.2 @@ -132746,17 +130985,13 @@ __FILES["image/hdr/Codec"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes --- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE --- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then --- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and --- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +-- image/hdr/Codec: Radiance RGBE scanlines (Graphics Gems II; rgbe.c): mantissa * 2^(e - 136), no +0.5, as stb_image. local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 local frexp = math.frexp local Codec = {} --- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +-- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes function Codec.readLine(b, p, limit, w, row) if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then @@ -132840,7 +131075,6 @@ if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, return p, nil end --- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step function Codec.toFloat(row, n, out, base, step) for i = 0, n - 1 do local q = i * 4 @@ -132860,7 +131094,6 @@ function Codec.toFloat(row, n, out, base, step) end end --- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) function Codec.fromFloat(px, y, w, row) for x = 0, w - 1 do local q = (y * w + x) * 16 @@ -132907,7 +131140,6 @@ function Codec.fromFloat(px, y, w, row) end end --- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 function Codec.writeLine(row, w, out, o) writeu8(out, o, 2) writeu8(out, o + 1, 2) @@ -132917,7 +131149,6 @@ writeu8(out, o, 2) for c = 0, 3 do local cur = 0 while cur < w do - -- find the next run of at least 4 local begRun = cur local runCount = 0 local oldRun = 0 @@ -132932,14 +131163,12 @@ writeu8(out, o, 2) end end end - -- a short run just before the long one if oldRun > 1 and oldRun == begRun - cur then writeu8(out, o, 128 + oldRun) writeu8(out, o + 1, readu8(row, cur * 4 + c)) o =o+ 2 cur = begRun end - -- raw bytes up to the run while cur < begRun do local n = math.min(begRun - cur, 128) writeu8(out, o, n) @@ -132965,15 +131194,9 @@ return Codec end __FILES["image/icns"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: --- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha --- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any --- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), --- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists --- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns --- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage --- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / --- 48 / 128 with masks. +-- image/icns: Apple icon images (icns resource type). Supports: is32 / il32 / ih32 / it32 (icns RLE) with s8mk / l8mk / +-- h8mk / t8mk masks, ic04 / ic05 ARGB, 1-bit ics# / ICN# / ich# / icm#, PNG entries through opts.decodeImage; writes +-- PNG or RLE entries. Not supported: JPEG 2000 entries, 4 / 8-bit palette entries, nested dark-mode / TOC chunks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133024,7 +131247,6 @@ return Sniff.magic(r, "icns") end -- ------------------------------------------------------------------------------------------------ decode --- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) local function unrle(b, p, stop, out, channels, count) for _, ch in __iter(channels) do local i = 0 @@ -133194,7 +131416,6 @@ table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", bl end -- ------------------------------------------------------------------------------------------------ encode --- the icns RLE of one channel (count bytes, step 4 from ch) into w local function rle(w, px, ch, count) local i = 0 while i < count do @@ -133304,16 +131525,9 @@ return Icns end __FILES["image/ico"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every --- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or --- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are --- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); --- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png --- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as --- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it --- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. --- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS --- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. +-- image/ico: Windows icons and cursors (ICO / CUR), from Microsoft's ICO documentation. Supports: every entry as a BMP +-- DIB (1..32-bit, AND mask) or PNG (opts.decodeImage), CUR hotspots; writes 32-bit DIB or PNG entries. Not supported: +-- resizing to icon sizes, DIB compression (BI_BITFIELDS read as 5-5-5 / BGRA), 2-colour planes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133590,18 +131804,14 @@ __FILES["image/ico/Dib"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from --- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit --- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha --- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are --- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +-- image/ico/Dib: ICO / CUR DIBs: XOR bitmap (1..32-bit, bottom-up, 4-byte rows) + 1-bit AND mask (1 = transparent). local Pixels = __include("codecs/image/Pixels") local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} --- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +-- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides function Dib.decode(b, p, e, w, h, bpp, pal, palN, out) local stride = (math.floor((w * bpp + 31) / 32)) * 4 local maskStride = (math.floor((w + 31) / 32)) * 4 @@ -133650,8 +131860,6 @@ local stride = (math.floor((w * bpp + 31) / 32)) * 4 return true, nil end --- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). --- out needs room for w * h * 4 + maskStride * h bytes. function Dib.encode(px, w, h, out, o) for y = h - 1, 0, -1 do for x = 0, w - 1 do @@ -133689,14 +131897,9 @@ return Dib end __FILES["image/ilbm"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks --- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a --- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), --- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or --- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH --- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else --- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer --- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). +-- image/ilbm: IFF ILBM / PBM (EA IFF 85 "ILBM", Amiga ROM Kernel Manual). Supports: 1..8 planes + CMAP, EHB (CAMG +-- 0x80), HAM6 / HAM8 (CAMG 0x800; 4-bit v -> v * 17, ilbmtoppm shifts), 24 / 32 planes, PBM, masking 1 / 2, ByteRun1, +-- NAME / ANNO / AUTH. Not supported: ANIM, RGBN / RGB8 / ACBM / DEEP, SHAM / PCHG (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -133782,7 +131985,6 @@ local b, o, limit = r.buf, r.base, r.limit end local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham - -- palette local pal = buffer.create(1024) local ncol = 0 if cmap then @@ -133815,7 +132017,6 @@ local v = readu8(b, cmap.offset + i * 3 + k) buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) end end - -- the body, decompressed local rowBytes = (chunky and((w + w % 2 ))or(((math.floor((w + 15) / 16)) * 2 ))) local total = (chunky and((rowBytes * h ))or((rowBytes * (planes + (masking == 1 and 1 or 0)) * h ))) local raw = buffer.create(total) @@ -134015,22 +132216,9 @@ return Ilbm end __FILES["image/jpeg"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG --- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical --- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the --- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi --- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images --- (coded 4:2:0 from the planes as they are). --- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit --- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt --- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's --- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt --- scans decode as far as they go (meta.truncated = true). --- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or --- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta; --- byte-identical to cjpeg for the same settings. --- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit --- or CMYK encoding. +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81) over codecs/image/Jpeg (from jpeg-luau 1.0, same author; bit-exact with +-- djpeg, byte-identical with cjpeg; IJG parts: licenses/libjpeg-turbo-LICENSE.md). Supports: SOF0/1/2/9/10, 8 / 12-bit, +-- scaled decodes, EXIF / ICC / COM / JFIF density. Not supported: lossless (SOF3), hierarchical, DNL, 2 components. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -134075,7 +132263,6 @@ local s = r:peek(3) end -- ------------------------------------------------------------------------------------------------ decode --- info(r) -> Info | nil, Err (reads the headers up to the frame header) function Jpeg.info(r) return Codec.info(r.buf, r.base, r.limit - r.base) end @@ -134084,7 +132271,7 @@ function Jpeg.decode(r, opts) if opts ~= nil and type(opts) ~= "table" then return nil, Err.new(Err.ARG, "options must be a table") end - local o = opts or {} -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + local o = opts or {} -- two JPEGs back to back are an image and a preview, as in MPF return Codec.decode(r.buf, r.base, r.limit - r.base, { scale = o.scale, @@ -134096,7 +132283,6 @@ return Codec.decode(r.buf, r.base, r.limit - r.base, { end -- ------------------------------------------------------------------------------------------------ encode --- the APP1 / APP2 / COM segments and the JFIF density from img.meta local function metaSegments(meta) local segments = {} if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then @@ -134166,17 +132352,9 @@ return Jpeg end __FILES["image/ktx"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL --- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the --- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every --- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip --- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are --- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is --- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. --- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 --- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, --- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and --- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. +-- image/ktx: Khronos KTX 1.1 / KTX 2.0. Supports: KTX1 (GL compressed and uncompressed, big-endian), KTX2 (VkFormat BCn +-- / ETC2 / EAC / uncompressed; Zstd and ZLIB supercompression), mips, cubes, arrays, 3D, KTXorientation; writes +-- uncompressed KTX2. Not supported: Basis Universal (BasisLZ / UASTC), ASTC, PVRTC. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -134456,7 +132634,6 @@ local b, o, n = r.buf, r.base, r.limit - r.base return info, nil end --- info(r) -> Info | nil, Err (the headers only) function Ktx.info(r) local id = r:peek(12) if id == ID2 then @@ -134467,7 +132644,6 @@ local id = r:peek(12) return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) end --- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image local function swapped(b, p, n, size) local out = buffer.create(n) buffer.copy(out, 0, b, p, n) @@ -134519,7 +132695,6 @@ local info, ierr = Ktx.info(r) local w, h, d = info.width, info.height, info.depth for level = 0, info.levels - 1 do local want = level == 0 or wantMips - -- the level's data: buf, offset, the image stride and row pitch local lb, lp = b, 0 local rowPitch= nil local imgSize = (Texture.size(fmt, w, h) ) @@ -134659,7 +132834,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end -- ------------------------------------------------------------------------------------------------ encode --- format -> VkFormat, bytes per texel, component bytes, kind local OUT= { rgba8 = { 37, 4, 1 }, rgba16 = { 91, 8, 2 }, @@ -134749,7 +132923,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "n if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then return nil, Err.new(Err.ARG, "zlib level must be 1..9") end - -- level data: the images of every layer / face per level local levelData= {} local raw= {} local cur = table.clone(images) @@ -134769,7 +132942,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "n end levelData[lv] = lb end - -- key / value data local kvw = Bytes.writer() local pairs_= { { "KTXwriter", "rosetta" } } if opts and opts.keyValue then @@ -134840,11 +133012,9 @@ return Ktx end __FILES["image/pcx"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit --- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the --- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross --- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as --- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. +-- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 +-- planes (EGA), 2 / 4-bit packed, 8-bit with the 256-colour end palette, 8-bit x 3 / 4 planes, RLE across scan lines, +-- uncompressed, DPI; writes 8-bit palette or 24 / 32-bit planes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -134952,7 +133122,6 @@ local b, o, limit = r.buf, r.base, r.limit p =p+ n truncated = n < total end - -- palettes local pal = buffer.create(1024) local function setPal(i, rr, gg, bb) buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) @@ -135024,7 +133193,6 @@ local b, o, limit = r.buf, r.base, r.limit end -- ------------------------------------------------------------------------------------------------ encode --- RLE of one plane row into w local function rleRow(out, src, p, n) local i = 0 while i < n do @@ -135108,16 +133276,9 @@ return Pcx end __FILES["image/png"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. --- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), --- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha --- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). --- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / --- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not --- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode --- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. --- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are --- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every +-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not +-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -135151,7 +133312,6 @@ local Png = { - local SIGNATURE = "\137PNG\r\n\26\n" local VALID = { [0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true }, @@ -135172,7 +133332,6 @@ function Png.sniff(r) return r:peek(8) == SIGNATURE and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- the IHDR at r's start: Header | nil, Err @@ -135207,7 +133366,6 @@ local b, o, n = r.buf, r.base, r.limit - r.base return h, nil end --- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) function Png.info(r) return header(r) end @@ -135226,8 +133384,6 @@ end local DISPOSE= { [0] = "none", [1] = "background", [2] = "previous" } --- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split --- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) local function pixels(b, chunks, total, w, ht, depth, ct, interlace, pal, tr, out) -- the inflated size: every (pass) row has a filter byte local channels = Decode.CHANNELS[ct] @@ -135284,7 +133440,6 @@ local checkCrc = opts and opts.checkCrc or false return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) end local b, n = r.buf, r.limit - -- chunks local pal = buffer.create(1024) for i = 0, 255 do buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black @@ -135484,7 +133639,6 @@ local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } local DISPOSE_CODES= { none = 0, background = 1, previous = 2 } local BLEND_CODES= { source = 0, over = 1 } --- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds local function delayFraction(delay) for den = 1, 1000 do local num = math.floor(delay * den + 0.5) @@ -135516,7 +133670,6 @@ return type(im) == "table" and buffer.len(im.pixels) >= im.width * im.height * 4 end --- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list local function animationFrames(img, opts) local frames = img.frames local mode = (opts and{opts.apng }or{nil @@ -135574,7 +133727,6 @@ if not validImage(img) then local want = opts and opts.colorType or "auto" local ctName= want if want == "auto" then - -- the smallest colour type that holds the image and every frame local alpha, color = false, false local function scan(im) local c = Encode.pickColorType(im.pixels, im.width, im.height) @@ -135678,8 +133830,6 @@ end end -- ------------------------------------------------------------------------------------------------ extras --- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a --- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. function Png.composite(img) if not validImage(img) then return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") @@ -135708,9 +133858,7 @@ __FILES["image/png/Apng"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / --- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the --- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +-- image/png/Apng: APNG 1.0 dispose / blend compositing; "over" uses ffmpeg pngdec.c's integer arithmetic (byte-exact). local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill @@ -135720,7 +133868,6 @@ local function div255(x) return math.floor((x + 128) * 257 / 65536 )end --- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas local function blend(canvas, cw, src, fw, fh, fx, fy, over) for y = 0, fh - 1 do local so = y * fw * 4 @@ -135753,7 +133900,6 @@ local function blend(canvas, cw, src, fw, fh, fx, fy, over) end end --- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) function Apng.composite(w, h, frames) local canvas = bcreate(w * h * 4) local saved = bcreate(w * h * 4) @@ -135792,12 +133938,7 @@ __FILES["image/png/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the --- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. --- Absorbed from png-luau src/Png/Decode.luau (same author). --- --- The caller (init) has validated the header and checked that the data holds at least the expected number of --- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +-- image/png/Decode: PNG unfiltering and expansion to RGBA8 (absorbed from png-luau src/Png/Decode.luau, same author). local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcopy = buffer.copy @@ -135819,20 +133960,16 @@ Decode.PASSES = PASSES local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } Decode.CHANNELS = CHANNELS --- bytes per row (without the filter byte) for a pass width function Decode.rowBytes(pw, channels, depth) return math.floor((pw * channels * depth + 7) / 8 )end --- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per --- complete pixel (at least 1). Returns true, or false + the bad filter type. local function unfilter(raw, p, ph, rb, bpp) local stride = rb + 1 for r = 0, ph - 1 do local f = readu8(raw, p) local cur = p + 1 if f == 0 then - -- none elseif f == 1 then for i = cur + bpp, cur + rb - 1 do writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) @@ -135842,7 +133979,6 @@ local stride = rb + 1 local i = cur local e4 = cur + rb - 4 while i <= e4 do - -- four bytes at once: add without carries between the byte lanes local x, y = readu32(raw, i), readu32(raw, i - stride) local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) @@ -135903,9 +134039,6 @@ local stride = rb + 1 return true, 0 end --- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. --- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), --- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. local function convert(raw, ro, pw, out, oo, ostep, ct, depth, pal, tr) if ct == 6 then if depth == 8 then @@ -136004,8 +134137,6 @@ local function convert(raw, ro, pw, out, oo, ostep, ct, depth, pal, tr) end end --- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). --- Returns true, or false + message. function Decode.run(raw, w, h, depth, ct, interlace, pal, tr, out) local channels = CHANNELS[ct] local bpp = math.max(1, math.floor((channels * depth) / 8)) @@ -136047,9 +134178,7 @@ __FILES["image/png/Encode"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and --- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute --- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +-- image/png/Encode: PNG colour type choice and filtering (per-row minimum sum of |signed residuals|, as libpng). local readu8, writeu8 = buffer.readu8, buffer.writeu8 local bcreate, bcopy = buffer.create, buffer.copy @@ -136057,7 +134186,6 @@ local Encode = {} local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } --- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" function Encode.pickColorType(px, w, h) local opaque, gray = true, true for i = 0, w * h - 1 do @@ -136079,7 +134207,6 @@ local opaque, gray = true, true return "rgb" end --- convert rgba8 to the colour type's packed rows (no filter bytes) local function pack(px, w, h, ct) local ch = CHANNELS[ct] if ch == 4 then @@ -136116,8 +134243,6 @@ local pa = math.abs(b - c) return c end --- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); --- the arithmetic is inlined: this runs for every byte local function costs(src, s, rb, bpp, first) local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 local p = s - rb @@ -136147,7 +134272,6 @@ local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 return c0, c1, c2, c3, c4 end --- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) local function apply(src, s, rb, bpp, first, f, out, o) writeu8(out, o, f) o =o+ 1 @@ -136176,8 +134300,6 @@ local function apply(src, s, rb, bpp, first, f, out, o) end end --- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of --- |signed residuals| (the libpng heuristic) function Encode.filter(px, w, h, ct) local ch = CHANNELS[ct] local src = pack(px, w, h, ct) @@ -136209,14 +134331,9 @@ return Encode end __FILES["image/pnm"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), --- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any --- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). --- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout --- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is --- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel --- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. --- Not supported: multi-image streams (the first image is read), PAM depths above 4. +-- image/pnm: Netpbm, from the Netpbm format pages: PBM (P1 / P4), PGM (P2 / P5), PPM (P3 / P6), PAM (P7, depth 1..4) +-- and PFM (PF / Pf, either byte order, bottom-up rows). Supports: maxval 1..65535, PFM to rgba8 as clamp(v, 0, 1) * +-- 255; writes all seven types. Not supported: multi-image streams, PAM depths above 4. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -136247,7 +134364,6 @@ local Pnm = { - local FMT_CODE= { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } local BPP= { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } local readu8 = buffer.readu8 @@ -136276,7 +134392,6 @@ local function isSpace(c) return c == 32 or (c >= 9 and c <= 13) end --- the next header token from p: token, position after it (nil at the end) local function token(b, p, limit) while p < limit do local c = readu8(b, p) @@ -136371,7 +134486,6 @@ while true do maxval = int(v) elseif key == "TUPLTYPE" then tupl = v - -- the rest of the line belongs to the value while p < limit and readu8(b, p) ~= 10 do p =p+ 1 end @@ -136597,17 +134711,13 @@ __FILES["image/pnm/Codec"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, --- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM --- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. --- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +-- image/pnm/Codec: Netpbm sample loops: P1 digits may run together; PFM either byte order. local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 local byteswap = bit32.byteswap local Codec = {} --- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). -- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) function Codec.readSamples(b, p, limit, count, mode, out) if mode == 1 then @@ -136629,7 +134739,6 @@ if mode == 1 then end local i = 0 while i < count do - -- skip whitespace and comments while p < limit do local c = readu8(b, p) if c == 35 then -- '#' @@ -136669,7 +134778,6 @@ if mode == 1 then return true, nil end --- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values function Codec.readBits(b, p, limit, w, h, out) local rowBytes = math.floor((w + 7) / 8 ) if p + rowBytes * h > limit then @@ -136685,11 +134793,9 @@ local rowBytes = math.floor((w + 7) / 8 return true, nil end --- format codes for pack / extract Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 --- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for --- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +-- 8-bit: round(v * 255 / maxval) function Codec.pack(s, n, ch, maxval, invert, fmt, dst) local wide = fmt == 4 or fmt == 5 local top = wide and 65535 or 255 @@ -136740,7 +134846,6 @@ local v = math.min(readu16(s, i * 2), maxval) end end --- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst function Codec.readFloats(b, p, limit, w, h, ch, le, dst) if p + w * h * ch * 4 > limit then return false, "truncated" @@ -136778,8 +134883,7 @@ if v ~= v then return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) end --- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for --- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +-- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000 function Codec.extract(px, fmt, n, ch, wide) local out = buffer.create(n * ch * 2) local srcWide = fmt == 4 or fmt == 5 @@ -136828,7 +134932,6 @@ end return out end --- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) function Codec.writeSamples(s, count, wide, out, o) if wide then for i = 0, count - 1 do @@ -136846,7 +134949,6 @@ if wide then return o end --- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) function Codec.writeBits(s, w, h, threshold, out, o) for y = 0, h - 1 do local acc, nb = 0, 0 @@ -136867,8 +134969,6 @@ for y = 0, h - 1 do return o end --- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM --- rows, bottom-to-top function Codec.writeFloats(px, w, h, ch, out, o) for y = h - 1, 0, -1 do for x = 0, w - 1 do @@ -136886,10 +134986,8 @@ return Codec end __FILES["image/qoi"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. --- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); --- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. --- Not supported: nothing in the spec is left out. +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). Supports: the whole spec (RGB / RGBA, +-- both colour space tags in meta.source.colorSpace). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137012,16 +135110,13 @@ __FILES["image/qoi/Codec"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). --- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read --- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +-- image/qoi/Codec: QOI op loops, from the QOI specification 1.0 (qoiformat.org). local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 local Codec = {} local index = buffer.create(256) --- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) function Codec.decode(b, p, limit, out, n) buffer.fill(index, 0, 0, 256) local r, g, bl, a = 0, 0, 0, 255 @@ -137093,7 +135188,6 @@ buffer.fill(index, 0, 0, 256) return true, nil end --- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes function Codec.encode(px, n, bpp, out, o) buffer.fill(index, 0, 0, 256) local pr, pg, pb, pa = 0, 0, 0, 255 @@ -137164,12 +135258,9 @@ return Codec end __FILES["image/sgi"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" --- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) --- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 --- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is --- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / --- colour-map files (colormap field 1..3: UNSUPPORTED). +-- image/sgi: Silicon Graphics images (Paul Haeberli's "The SGI Image File Format" 1.00). Supports: verbatim and RLE, 1 +-- / 2 bytes per channel, 1..4 channels, dimension 1..3, bottom-up rows, the image name; writes RGB(A) 8 / 16-bit. Not +-- supported: dithered / screen / colour-map files (colormap 1..3). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137244,7 +135335,7 @@ local b, o, limit = r.buf, r.base, r.limit if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel planes as 16-bit samples (8-bit values scaled * 257) + -- 8-bit values scaled * 257 local plane = buffer.create(w * h * z * 2) local truncated = false local function put(c, row, x, v) @@ -137452,12 +135543,9 @@ return Sgi end __FILES["image/sunras"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour --- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, --- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in --- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the --- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), --- raw colour maps (RMT_RAW is ignored). +-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>). Supports: 1-bit (0 = white without a colour map), +-- 8-bit, 24 / 32-bit BGR / XBGR (RT_STANDARD, RT_OLD, RT_BYTE_ENCODED) or RGB / XRGB (RT_FORMAT_RGB), 0x80 RLE, 16-bit +-- row padding; 32-bit X is alpha unless all zero. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF, RMT_RAW. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137701,15 +135789,9 @@ return Sunras end __FILES["image/tga"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) --- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / --- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, --- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: --- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data --- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. --- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left --- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage --- stamp, ...), which are ignored. +-- image/tga: Truevision TGA (TGA 2.0 specification). Supports: types 1 / 2 / 3 and RLE 9 / 10 / 11, 8..32-bit pixels +-- and colour maps, every origin, descriptor alpha bits (16-bit: only when 1 alpha bit is declared), the image ID, the +-- 2.0 footer. Not supported: the extension area's fields (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -137781,7 +135863,6 @@ return readu8(b, o + q) + readu8(b, o + q + 1) * 256 return h end --- plausible(h) -> nil | why not local function implausible(h) local t = h.imageType if not TYPES[t] then @@ -137843,7 +135924,6 @@ local maxPixels = opts and opts.maxPixels or 2 ^ 26 local p = r.base + 18 local id = (h.idLen > 0 and p + h.idLen <= r.limit and{(buffer.readstring(b, p, h.idLen) )}or{nil })[1] p =p+ h.idLen - -- colour map local pal = buffer.create(4) local palN = 0 if h.cmapType == 1 and h.cmapLen > 0 then @@ -137981,15 +136061,12 @@ __FILES["image/tga/Codec"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 --- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented --- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +-- image/tga/Codec: Truevision TGA 2.0 pixel loops: raw / RLE (packets may cross scanlines on read, never on write). local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local Codec = {} --- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, --- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +-- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 local function pixel(b, p, kind, alpha1, pal, palN) if kind == 0 then return readu8(b, p) * 0x10101 + 0xFF000000 @@ -138013,7 +136090,6 @@ if kind == 0 then end Codec.pixel = pixel --- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? function Codec.decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) local n = w * h local i = 0 @@ -138065,9 +136141,6 @@ local n = w * h return i, false end --- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); --- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. --- out needs room for w * h * (outBpp + 1) bytes. function Codec.encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) local function get(q) if srcBpp == 1 then @@ -138138,17 +136211,9 @@ return Codec end __FILES["image/tiff"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. --- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / --- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's --- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), --- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, --- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as --- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard --- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). --- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / --- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. --- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. +-- image/tiff: TIFF 6.0 (+ Adobe technote 3, BigTIFF). Supports: strips, tiles, planar 1 / 2, none / LZW (old-style too) +-- / Deflate (8, 32946) / PackBits / JPEG (7), predictors 2 / 3, int / float samples, CMYK (naive), fill order 2. Not +-- supported: old-style JPEG (6), CCITT (2, 3, 4), YCbCr, CIELab, JBIG. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -138229,7 +136294,6 @@ local function off(c, at) return (c.big and{(u64(c, at) )}or{(u32(c, at) )})[1]end --- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many local function values(c, e, max) if not e then return nil @@ -138294,7 +136358,6 @@ local v = values(c, e, 64) return (v and v[1] and{v[1] }or{default })[1]end --- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err local function readIfd(c, p) local esize = c.big and 20 or 12 local hsize = c.big and 8 or 2 @@ -138342,7 +136405,6 @@ if not e or e.at < c.base then return x end --- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err local function inflateChunk(c, comp, p, len, out, o, size, rev) if p < c.base or len < 0 or p + len > c.limit then -- a chunk past the end: keep what exists (truncated files) @@ -138447,10 +136509,10 @@ local w, h = one(c, t[256], 0), one(c, t[257], 0) if ch > h and not tiled then ch = h end - local pspp = (chunky and{spp }or{1 -- samples per pixel in one plane + local pspp = (chunky and{spp }or{1 })[1] local nplanes = chunky and 1 or spp - local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane - local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + local rb = math.ceil(w * pspp * bps / 8) + local crb = math.ceil(cw * pspp * bps / 8) if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") end @@ -138521,7 +136583,6 @@ __DARKLUA_CONTINUE_7=true break elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) end - -- into the plane local plane = planes[pl + 1] local x0b = math.floor(tx * cw * pspp * bps / 8) local cols = math.min(cw, w - tx * cw) @@ -138541,7 +136602,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end le = true -- fpAcc leaves the samples little endian end local colorType = PHOTOMETRIC[photo] - -- the output layout local kind = "rgba8" if opts and opts.native and comp ~= 7 then if photo == 3 or photo == 5 then @@ -138645,7 +136705,6 @@ local v = bytesOf(c, t[tag], 65536) return img, nil end --- pages(r) -> the IFD tables of every page (and the context) | nil, Err local function pages(r, maxPages) local b, base, limit = r.buf, r.base, r.limit if limit - base < 8 then @@ -138690,7 +136749,6 @@ local b, base, limit = r.buf, r.base, r.limit return list, c, nil end --- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err function Tiff.info(r) local list, c, err = pages(r, 1024) if not list or not c then @@ -138756,7 +136814,6 @@ end end -- ------------------------------------------------------------------------------------------------ encode --- layout per pixel format: samples, bits, sample format, photometric, extra samples local LAYOUT = { gray8 = { 1, 8, 1, 1 }, graya8 = { 2, 8, 1, 1 }, @@ -138903,7 +136960,6 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then if not tags or not strips then return nil, err end - -- strip data first local soffs = {} for i, s in __iter(strips) do if w:tell() % 2 == 1 then @@ -138984,10 +137040,7 @@ __FILES["image/tiff/Pixels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and --- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's --- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. --- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +-- image/tiff/Pixels: TIFF predictors 2 / 3 (TIFF 6.0 section 14, technote 3; 3 as libtiff fpAcc / fpDiff). local Bytes = __include("core/Bytes") local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 @@ -138998,8 +137051,7 @@ local Pixels = {} local scratch = buffer.create(8) --- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an --- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +-- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads local function f32(bits) if band(bits, 0x7F800000) == 0x7F800000 then if band(bits, 0x7FFFFF) ~= 0 then @@ -139042,7 +137094,6 @@ function Pixels.reverseBits(b, off, len) end -- ------------------------------------------------------------------------------------------------ predictors --- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) function Pixels.unpredict2(b, off, rows, rb, stride, bps, le) for r = 0, rows - 1 do local base = off + r * rb @@ -139078,7 +137129,6 @@ function Pixels.unpredict2(b, off, rows, rb, stride, bps, le) end end --- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) function Pixels.predict2(b, off, rows, rb, stride, bps) for r = 0, rows - 1 do local base = off + r * rb @@ -139095,8 +137145,7 @@ function Pixels.predict2(b, off, rows, rb, stride, bps) end end --- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little --- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +-- the samples come out little endian whatever the file's byte order (libtiff fpAcc) function Pixels.unpredict3(b, off, rows, rb, bytes, stride, tmp) local wc = math.floor(rb / bytes ) for r = 0, rows - 1 do @@ -139113,7 +137162,6 @@ function Pixels.unpredict3(b, off, rows, rb, bytes, stride, tmp) end end --- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) function Pixels.predict3(b, off, rows, rb, bytes, stride, tmp) local wc = math.floor(rb / bytes ) for r = 0, rows - 1 do @@ -139133,7 +137181,6 @@ end -- ------------------------------------------------------------------------------------------------ samples local half = Bytes.half --- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them @@ -139201,7 +137248,6 @@ if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then return false end --- convert(P): every pixel into P.out in P.kind's layout function Pixels.convert(P) if fast(P) then return @@ -139212,7 +137258,6 @@ function Pixels.convert(P) local float = sfmt == 3 local signed = sfmt == 2 local cmapN = 2 ^ math.min(bps, 16) - -- raw sample s of pixel x in the row starting at byte ro of its plane local function raw(s, x, row) local b, i if chunky then @@ -139383,15 +137428,9 @@ return Pixels end __FILES["image/tim"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation --- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. --- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit --- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 --- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when --- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. --- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image --- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque --- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. +-- image/tim: PlayStation TIM (magic 0x10), from Sony's PSX "File Formats" documentation. Supports: 4 / 8-bit CLUT, 15 / +-- 24-bit direct; colours are 1-5-5-5 STP-B-G-R, expanded (v << 3) | (v >> 2), 0x0000 transparent as on the hardware, +-- opaque black written as 0x8000. Not supported: mixed mode (pmode 4). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -139544,7 +137583,6 @@ local magic, flags = r:u32le(), r:u32le() end -- ------------------------------------------------------------------------------------------------ encode --- rgba8 pixel -> PSX colour local function psx(v) local r, g, b, a = v % 256, (math.floor(v / 256)) % 256, (math.floor(v / 65536)) % 256, math.floor(v / 16777216 ) if a < 128 then @@ -139632,18 +137670,9 @@ return Tim end __FILES["image/vtf"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer --- Community "VTF (Valve Texture Format)" page; no code taken. --- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail --- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image --- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to --- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure --- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, --- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through --- codecs/image/Texel), DXT1 (+ one-bit alpha), --- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, --- texel, reflectivity, bumpScale }. --- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. +-- image/vtf: Valve Texture Format 7.0 - 7.5 (Source engine), from the Valve Developer Community VTF page. Supports: the +-- high-resolution image, mips / faces / slices / frames, uncompressed texels, DXT1 / DXT3 / DXT5, ATI1N / ATI2N (35 / +-- 34 Alien Swarm, 38 / 37 Source 2013). Not supported: P8, Strata / Source 2 formats, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -139674,7 +137703,6 @@ local Vtf = { local M = Texel.masked --- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind local FORMATS= { [0] = "rgba8", -- RGBA8888 [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 @@ -139723,7 +137751,6 @@ return r:peek(4) == "VTF\0" and r:peekU8(4) == 7 and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- bytes of one w x h image in format f local function imageSize(f, w, h) if type(f) == "string" and BCN[f] then return Bcn.size(f == "bc1a" and"bc1" or f, w, h) or 0 @@ -139795,7 +137822,6 @@ local size = r.limit - r.base local lowSize = (lowFmt >= 0 and lowW > 0 and lowH > 0 and lf and{(imageSize(lf, lowW, lowH) )}or{0 })[1] dataAt = headerSize + lowSize end - -- the chain: mips smallest first; per mip: frames, faces, slices local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) @@ -139879,20 +137905,9 @@ return Vtf end __FILES["image/webp"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 --- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the --- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. --- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw --- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the --- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or --- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif --- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and --- metadata). --- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does), --- alpha dithering / premultiplied output. --- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s --- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). --- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. +-- image/webp: WebP (RFC 9649); bitstreams ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +-- Supports: VP8 key frames (bit-exact with dwebp), VP8L, ALPH, VP8X, ANIM / ANMF, ICC / EXIF / XMP; writes VP8L. Not +-- supported: lossy encoding, VP8 scale fields (ignored, as dwebp), alpha dithering. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -139932,8 +137947,6 @@ local Webp = { - - local DEFAULT_MAX_PIXELS = 2 ^ 26 local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20 @@ -139947,7 +137960,6 @@ local function corrupt(msg, offset) return nil, Err.new(Err.CORRUPT, msg, offset) end --- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT) local function fromMessage(msg, offset) if Err.is(msg) then return msg @@ -139983,8 +137995,7 @@ local out= {} return out, nil end --- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size --- must fit the data (TRUNCATED) and bytes after it are ignored. +-- as libwebp: the RIFF size must fit the data and bytes after it are ignored local function readChunks(r) local buf, base, limit = r.buf, r.base, r.limit if limit - base < 12 then @@ -140011,7 +138022,6 @@ local buf, base, limit = r.buf, r.base, r.limit return list, f end --- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f, c) local n = c.size - 12 return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) @@ -140254,7 +138264,6 @@ if o.coalesce then return img, nil end --- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err function Webp.info(r) local chunks, cerr = readChunks(r) if not chunks then @@ -140479,8 +138488,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ extras --- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way --- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) function Webp.coalesce(img) if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil @@ -140509,9 +138516,8 @@ end __FILES["image/webp/Alpha"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), --- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / --- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). local Vp8L = __include("codecs/image/Vp8L") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -140551,7 +138557,6 @@ local function unfilter(a, w, h, filter) end end --- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message function Alpha.decode(buf, off, len, w, h) if len <= 1 then return nil, "truncated: ALPH chunk" @@ -140587,18 +138592,15 @@ end __FILES["image/webp/Anim"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c, --- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour --- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha --- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the --- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws. +-- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt): the background colour is ignored, as the spec recommends. local band, rshift = bit32.band, bit32.rshift local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill local Anim = {} --- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult) +-- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult @@ -140627,7 +138629,6 @@ local sa = rshift(src, 24) end Anim.blendPixel = blendPixel --- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets) local function blendRow(cur, prev, o, n) for i = o, o + n - 1 do local s = readu32(cur, i * 4) @@ -140637,7 +138638,6 @@ local function blendRow(cur, prev, o, n) end end --- draw(canvas, cw, f): copy the frame rectangle into the canvas local function draw(canvas, cw, f) for j = 0, f.h - 1 do bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) @@ -140650,7 +138650,6 @@ local function clearRect(canvas, cw, x, y, w, h) end end --- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them function Anim.coalesce(cw, ch, frames) local size = cw * ch * 4 local out= {} @@ -140709,9 +138708,6 @@ if not p.disposeBg then return out end --- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or --- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle; --- previous: restore) function Anim.composite(cw, ch, frames) local size = cw * ch * 4 local canvas = bcreate(size) @@ -140750,10 +138746,8 @@ return Anim end __FILES["image/xbm"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height --- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, --- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below --- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant). Supports: _width / _height / _x_hot / _y_hot +-- defines, char / short arrays in hex, decimal or octal, LSB first, set bits black; writes X11 format. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -140871,7 +138865,6 @@ if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name @@ -140914,12 +138907,9 @@ return Xbm end __FILES["image/xpm"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: --- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / --- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour --- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in --- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, --- the fewest chars per pixel; opts.name (default "image"). +-- image/xpm: X PixMap (XPM 3 C source and XPM 2 plain; Arnaud Le Hors's "XPM Manual"). Supports: the values line and +-- hotspot, c / g / g4 / m / s keys (c preferred, then g, g4, m), #RGB .. #RRRRGGGGBBBB, None, colour names (unknown: +-- black); writes XPM 3 with hex colours. Not supported: the extensions section (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -140959,7 +138949,6 @@ local s = Sniff.text(r, 64, true) end -- ------------------------------------------------------------------------------------------------ decode --- colour value -> rgba8 u32, or nil for an unknown name local function colour(v) local l = string.lower(v) if l == "none" or l == "transparent" then @@ -140984,7 +138973,6 @@ c =c+ math.floor(x * 255 / mx + 0.5) * 256 ^ i return (rgb and((rgb + 0xFF000000 ))or(nil ))end --- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) local function strings(s) local out = {} if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then @@ -141129,7 +139117,6 @@ if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name @@ -141188,9 +139175,7 @@ return Xpm end __FILES["image/xpm/Names"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's --- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. --- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +-- image/xpm/Names: CSS Color 4 named colours with X11's values where they differ, and grey0 .. grey100. local Names = {} local HEX= { @@ -141226,7 +139211,6 @@ local HEX= { violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, } --- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) function Names.lookup(name) local v = HEX[name] if v then @@ -141247,19 +139231,9 @@ return Names end __FILES["layered/aseprite"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, --- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every --- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, --- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to --- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old --- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and --- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, --- delay }. --- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk --- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, --- palette, tags. --- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour --- profiles (sRGB assumed). +-- layered/aseprite: Aseprite .ase / .aseprite (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA / grayscale / +-- indexed, frames, layer tree (groups, blend, opacity), raw / zlib / linked cels, palettes (0x2019, 0x0004 / 0x0011), +-- tags, user data. Not supported: tilemaps / tilesets (meta.skipped), slices, external files, colour profiles (sRGB). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -141287,7 +139261,6 @@ local Aseprite = { - local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" } local BLEND_IDS= {} for k, v in __iter(BLENDS) do @@ -141315,7 +139288,6 @@ local function str(r) return r:string(r:u16le()) end --- cel pixels (depth bytes per pixel) -> rgba8 local function toRGBA(src, so, n, depth, palette, transparent, background) local out = buffer.create(n * 4) if depth == 32 then @@ -141379,8 +139351,8 @@ local maxPixels = opts and opts.maxPixels or 2 ^ 26 local tags= {} local frames= {} local skipped = 0 - local lastUser= nil -- the object the next user data chunk belongs to - local tagUser = 0 -- tags waiting for their user data chunks + local lastUser= nil + local tagUser = 0 for fi = 1, nframes do local fstart = r.pos local fbytes = r:u32le() @@ -141572,10 +139544,9 @@ if ctyp == 0 then r.pos = fstart + fbytes end local _ = ncolors - -- the layer tree of one frame local function build(fi) local root= {} - local stack= { root } -- stack[level + 1] = the children list at that level + local stack= { root } for li, info in __iter(infos) do local level = math.min(info.level, #stack - 1) local list = stack[level + 1] @@ -141601,7 +139572,6 @@ local root= {} l.opacity = 1 end table.insert(list, l) - -- deeper layers go into this group for k = #stack, level + 2, -1 do stack[k] = nil end @@ -141640,9 +139610,8 @@ local root= {} end return root end - -- cel images (shared by linked cels) for _, f in __iter(frames) do - for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + for li, cel in pairs(f.cels) do if cel.raw then local info = infos[li] local img = Types.Image.new(cel.w, cel.h) @@ -141718,7 +139687,6 @@ if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.w end local meta= (type(layered.meta) == "table" and{layered.meta }or{{} })[1] local level = opts and opts.level or 6 - -- frames: the layered frames, or one frame of the layers local frameList= (type(layered.frames) == "table" and #layered.frames > 0 and{layered.frames }or{{ { layers = layered.layers, delay = 0.1 } } })[1] local struct= {} if not nodes(frameList[1].layers, 0, struct) then @@ -141746,7 +139714,6 @@ if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.w end perFrame[fi] = ns end - -- the colour depth: requested, or the source's when every pixel fits local depth = opts and opts.depth or meta.colorDepth or 32 local explicit = opts ~= nil and opts.depth ~= nil if depth ~= 32 and depth ~= 16 and depth ~= 8 then @@ -141862,7 +139829,6 @@ if type(ud) ~= "table" then chunk(fw, 0x2020, c) return 1 end - -- where each (layer, frame) cel's image was first written: linked cels local firstAt= {} for fi, f in __iter(frameList) do local fw = Bytes.writer(4096) @@ -142003,15 +139969,9 @@ return Aseprite end __FILES["layered/ora"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with --- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. --- Decode: the stack tree (nested <stack> = groups: isolation="auto" is passThrough; <layer> name / src / x / y / --- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), --- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: --- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) --- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to --- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the <text> / <filter> / --- <selection> elements (ignored). +-- layered/ora: OpenRaster 0.0.6 (freedesktop.org; new code): a zip with a stored "mimetype" first, stack.xml, PNG +-- layers, mergedimage.png, Thumbnails/thumbnail.png. Supports: nested stacks (isolation="auto" = passThrough), layer +-- attributes, svg:* ops; PNGs via opts.decodeImage / encodeImage. Not supported: non-PNG sources, <text> / <filter>. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -142114,7 +140074,7 @@ local data, derr = zip:read(path) end return img, nil end - -- a <stack>'s children, top first in the file -> bottom to top + -- stack.xml lists a <stack>'s children top first local function stack(node, ox, oy) local out= {} for _, ch in __iter(node.children) do @@ -142183,7 +140143,6 @@ if not (opts and opts.composite == false) and zip:find("mergedimage.png") then end -- ------------------------------------------------------------------------------------------------ encode --- nearest-neighbour downscale to fit max x max local function thumbnail(img, max) local w, h = img.width, img.height local s = math.min(1, max / math.max(w, h)) @@ -142222,7 +140181,6 @@ if type(img) ~= "table" or img.format ~= "rgba8" then end return data, nil end - -- layers bottom to top -> xml children top first local function stack(layers) local kids = {} for i = #layers, 1, -1 do @@ -142298,17 +140256,9 @@ return Ora end __FILES["layered/psd"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of --- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers --- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, --- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / --- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image --- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. --- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend --- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, --- clipping, opacity / fill, hidden flags and Unicode names. --- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer --- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. +-- layered/psd: Adobe Photoshop PSD / PSB (Photoshop File Formats Specification, 2016). Supports: every colour mode at +-- 1 / 8 / 16 / 32 bits, layers (RLE / ZIP channels, Lr16 / Lr32, iOpa, luni, masks, lsct groups), the merged image, +-- resources; encode: 8-bit RGB. Not supported: adjustment / type / smart-object contents, effects, vector masks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -142400,7 +140350,6 @@ local function utf16be(s) return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) end --- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err local function layerRecords(r, c) local count = r:i16be() local absAlpha = count < 0 @@ -142524,7 +140473,7 @@ __DARKLUA_CONTINUE_6=true break end end if ch.size < 2 then -__DARKLUA_CONTINUE_6=true break -- an empty channel +__DARKLUA_CONTINUE_6=true break end local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) if not plane then @@ -142550,7 +140499,6 @@ __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end return recs, absAlpha, nil end --- records (bottom to top) -> a layer tree local function tree(recs) local root= {} local stack= {} @@ -142766,7 +140714,7 @@ local o= opts or {} planes[k] = plane end elseif comp == 2 or comp == 3 then - -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + -- Photoshop writes all channels in one zlib stream local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) if not all then return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) @@ -143044,10 +140992,8 @@ end __FILES["layered/psd/Channels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a --- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the --- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". --- Never throws: every read is range-checked first; failures return nil, "message". +-- layered/psd/Channels: PSD / PSB channel data (Photoshop File Formats Specification 2016, "Channel image data" / +-- "Image data section"): raw, PackBits RLE, ZIP, ZIP with prediction; colour modes to rgba8; PackBits rows. local Deflate = __include("codecs/compress/Deflate") local PackBits = __include("codecs/compress/PackBits") @@ -143058,7 +141004,6 @@ local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.wr local floor, min, max = math.floor, math.min, math.max local byteswap = bit32.byteswap --- rowBytes(w, depth) -> bytes per row of one channel function Channels.rowBytes(w, depth) if depth == 1 then return math.floor((w + 7) / 8 @@ -143066,7 +141011,6 @@ if depth == 1 then return w * (math.floor(depth / 8)) end --- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil function Channels.rleCounts(src, p, limit, rows, psb) local size = psb and 4 or 2 if rows < 0 or p + rows * size > limit then @@ -143084,7 +141028,6 @@ for i = 1, rows do return counts, p end --- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message function Channels.rle(src, p, limit, counts, first, rows, rowBytes, dst, d) for i = 0, rows - 1 do local c = counts[first + i] or 0 @@ -143101,7 +141044,6 @@ for i = 0, rows - 1 do return p, nil end --- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place local function unpredict(plane, w, h, depth) if depth == 8 then for y = 0, h - 1 do @@ -143145,8 +141087,6 @@ local function unpredict(plane, w, h, depth) end end --- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the --- 2-byte compression code and the data of one layer channel. function Channels.channel(src, p, limit, w, h, depth, psb) local rb = Channels.rowBytes(w, depth) local plane = bcreate(rb * h) @@ -143187,31 +141127,29 @@ local rb = Channels.rowBytes(w, depth) return plane, nil end --- sample8(plane, i, depth) -> sample i as 0..255 local function sample8(plane, i, depth) if depth == 8 then return readu8(plane, i) elseif depth == 16 then return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) elseif depth == 32 then - local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + local f = readf32(plane, i * 4) if f ~= f then return 0 end return floor(max(0, min(1, f)) * 255 + 0.5) end - -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + -- 1-bit: 1 = black (whole-byte widths only; toRGBA reads bitmaps itself) return math.floor(readu8(plane, math.floor(i / 8)) / 2 ^ (7 - i % 8) )% 2 == 1 and 0 or 255 end --- swap32(plane): big-endian f32 samples to native order, in place function Channels.swap32(plane) for i = 0, math.floor(blen(plane) / 4 )- 1 do writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) end end --- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +-- PSD Lab (0..255 each) to sRGB, the D50 white approximated by D65 local function srgb(c) c = (c <= 0.0031308 and((12.92 * c ))or((1.055 * c ^ (1 / 2.4) - 0.055 ))) return floor(max(0, min(1, c)) * 255 + 0.5) @@ -143232,8 +141170,7 @@ return (t > 6 / 29 and((t * t * t ))or((3 * (6 / 29) ^ 2 * (t - 4 / 29) return srgb(r), srgb(g), srgb(bl) end --- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } --- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +-- PSD colour modes: 0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab function Channels.toRGBA(planes, w, h, depth, mode, palette) local n = w * h local out = bcreate(n * 4) @@ -143241,7 +141178,6 @@ local n = w * h local alpha = planes.alpha local bitmapW = math.floor((w + 7) / 8 ) if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then - -- the common case, without a call per sample local g8 = (mode == 3 and c2 and blen(c2) >= n and{c2 }or{c1 })[1] local b8 = (mode == 3 and c3 and blen(c3) >= n and{c3 }or{c1 })[1] local a8 = (alpha and blen(alpha) >= n and{alpha }or{nil @@ -143294,7 +141230,6 @@ local n = w * h return out end --- gray8(plane, w, h, depth) -> 1 byte per pixel function Channels.gray8(plane, w, h, depth) local n = w * h local out = bcreate(n) @@ -143321,7 +141256,6 @@ function Channels.unmatte(rgba, n) end end --- matte(rgba, n) -> a copy matted with white (the writer's merged image) function Channels.matte(rgba, n) local out = bcreate(n * 4) bcopy(out, 0, rgba, 0, n * 4) @@ -143339,12 +141273,10 @@ local out = bcreate(n * 4) end -- ------------------------------------------------------------------------------------------------ writer helpers --- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) function Channels.packRow(src, o, n, out, d) local start = d local i = 0 while i < n do - -- a run of at least 3 equal bytes? local v = readu8(src, o + i) local run = 1 while i + run < n and run < 128 and readu8(src, o + i + run) == v do @@ -143356,7 +141288,6 @@ local start = d d =d+ 2 i =i+ run else - -- literals up to the next run of 3 local j = i while j < n and j - i < 128 do if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then @@ -143374,7 +141305,6 @@ local start = d return d - start end --- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) function Channels.planes8(rgba, w, h) local n = w * h local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) @@ -143391,7 +141321,6 @@ local n = w * h return r, g, b, a end --- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code function Channels.rleChannel(plane, w, h, psb) local cs = psb and 4 or 2 local out = bcreate(h * cs + h * (w + math.floor(w / 128 )+ 2)) @@ -143414,27 +141343,9 @@ return Channels end __FILES["model/3ds"] = function() local __compat = __compat local type = __compat.type --!strict --- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the --- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference --- for transforms and conventions; no code ported) and lib3ds (layouts only). --- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, --- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and --- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials --- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, --- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as --- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / --- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the --- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), --- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, --- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / --- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from --- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects --- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not --- applied), the keyframer frame range. --- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first --- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural --- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on --- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). +-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3, +-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer. +-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -143489,7 +141400,6 @@ local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) if not raw then return nil, Err.from(msg, at) end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene = pcall(Build.scene, raw, opts ) if not ok then return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) @@ -143516,13 +141426,11 @@ return ThreeDs end __FILES["model/3ds/Build"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world --- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * --- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix --- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key --- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's --- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position --- are averaged; group 0 is flat). Times are frame / fps. +-- model/3ds/Build: Read's chunk tables -> Types.Scene. +-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a +-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix) +-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle +-- deltas from the previous key. Smoothing group 0 is flat. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Read = __include("model/3ds/Read") @@ -143535,7 +141443,6 @@ local band = bit32.band local sqrt, abs = math.sqrt, math.abs -- ------------------------------------------------------------------------------------------------ math --- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 local function meshMatrix(m) @@ -143551,7 +141458,6 @@ return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10 end Build.det3 = det3 --- q(a) * q(b) local function qmul(a, b) local ax, ay, az, aw = a[1], a[2], a[3], a[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] @@ -143564,7 +141470,7 @@ local ax, ay, az, aw = a[1], a[2], a[3], a[4] end Build.qmul = qmul --- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +-- 3DS angles turn clockwise local function keyQuat(angle, x, y, z) if x == 0 and y == 0 and z == 0 then return { 0, 0, 0, 1 } @@ -143580,7 +141486,7 @@ local l = sqrt(x * x + y * y + z * z) return x / l, y / l, z / l, l end --- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +-- -Z looks from pos to target, world up +Z function Build.lookAt(p, t, roll) local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) if l == 0 then @@ -143590,7 +141496,6 @@ local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) if abs(fz) > 0.999999 then ux, uy, uz = 0, 1, 0 end - -- right = forward x up, up = right x forward local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx local a = math.rad(roll) @@ -143680,18 +141585,14 @@ local file = m.file end -- ------------------------------------------------------------------------------------------------ meshes --- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved --- by xf (world -> the node's local space) local function mesh(name, m, xf, matByName, opts) local nv, nf = m.nv, m.nf local pos, faces = m.positions, m.faces - -- local positions local lp = table.create(nv * 3, 0) for v = 0, nv - 1 do local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z end - -- faces with valid corners, their materials local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) local valid = table.create(nf, false) for f = 0, nf - 1 do @@ -143710,7 +141611,6 @@ local nv, nf = m.nv, m.nf end local smooth = m.smoothing local doNormals = opts.normals ~= false - -- face normals (area weighted) and the faces around each distinct position local fn = table.create(nf * 3, 0) local around= {} local group = table.create(nv, 0) @@ -143765,7 +141665,6 @@ local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] local nx, ny, nz = normalize(x, y, z) return nx, ny, nz end - -- primitives in the order their material first appears local order= {} local byMat= {} for f = 1, nf do @@ -143838,7 +141737,6 @@ local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] end -- ------------------------------------------------------------------------------------------------ tracks --- the value of a track at a frame (linear between keys, clamped at the ends) local function evalTrack(t, frame, default) if not t or #t.frames == 0 then return default @@ -143876,7 +141774,6 @@ local function scaleKey(v) return { v[1] == 0 and 1 or v[1], v[2] == 0 and 1 or v[2], v[3] == 0 and 1 or v[3] } end --- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys local function rotations(t) local frames, quats = {}, {} local acc= nil @@ -143913,7 +141810,6 @@ local o= opts or {} local fps = o.fps or 30 local scene = S.new() local matByName = materials(raw, scene) - -- objects by name local objByName= {} for _, obj in __iter(raw.objects) do if objByName[obj.name] == nil then @@ -143995,15 +141891,14 @@ local L= { name = obj.name, type = "point", color = { l.color[1], l.color[2], l. local kf = raw.keyframer local kfNodes = (kf and{kf.nodes }or{{} -})[1] -- targets of cameras / spotlights by name - local targets= {} +})[1] local targets= {} for _, n in __iter(kfNodes) do if n.kind == "target" or n.kind == "lightTarget" then targets[n.name] = targets[n.name] or n end end local placedObj= {} - local sceneOf= {} -- kf id -> scene node + local sceneOf= {} local channels= {} local function channel(node, path, times, values, comps) for i = 1, #times do @@ -144068,7 +141963,6 @@ __DARKLUA_CONTINUE_25=true break channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) end else - -- cameras and lights: position, target, roll local isCam = kind == "camera" local cam = (obj and isCam and{obj.camera }or{nil })[1] local lit = (obj and not isCam and{obj.light }or{nil @@ -144098,7 +141992,6 @@ local p = evalTrack(tr.pos, frame, basePos) end local ni = addNode(node, parent) sceneOf[id] = ni - -- every key time of the position, roll and target tracks local set= {} local times= {} for _, t in __iter({ tr.pos, tr.roll, (aims and tgt and{tgt.tracks.pos }or{nil })[1]}) do @@ -144129,7 +142022,6 @@ local p = evalTrack(tr.pos, frame, basePos) end end __DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break end end - -- objects the keyframer does not place (or files without one): at their own matrix / position for _, obj in __iter(raw.objects) do local __DARKLUA_CONTINUE_31=false repeat if placedObj[obj] then __DARKLUA_CONTINUE_31=true break @@ -144181,12 +142073,8 @@ return Build end __FILES["model/3ds/Read"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read --- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their --- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes --- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). --- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is --- clipped to the parent. Never throws on bad data: returns nil, message, offset. +-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables. +-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it. local Read = {} local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 @@ -144210,17 +142098,14 @@ local C = { } Read.C = C --- material map chunks -> their name in Raw materials Read.MAPS = { [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", } --- keyframer node chunks -> kind local NODE_KINDS = { [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", [0xB006] = "lightTarget", [0xB007] = "spot", } --- track chunks -> (field, values per key) local TRACKS= { [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, @@ -144261,7 +142146,6 @@ local TRACKS= { --- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error -- ------------------------------------------------------------------------------------------------ helpers @@ -144270,7 +142154,7 @@ local b = ctx.b while p + 6 <= stop do local id, size = readu16(b, p), readu32(b, p + 2) if size < 6 then - return nil, nil -- padding or garbage after the last chunk + return nil, nil end local e = p + size if e > ctx.limit then @@ -144285,7 +142169,6 @@ local b = ctx.b return nil, nil end --- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil local function cstring(b, p, stop) for q = p, stop - 1 do if readu8(b, q) == 0 then @@ -144299,7 +142182,7 @@ local function vec3(b, p) return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } end --- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +-- colour chunks: the first float or byte colour (the gamma-corrected variants only when nothing else) local function color(ctx, p, stop) local b = ctx.b local main, lin= nil, nil @@ -144324,7 +142207,6 @@ if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then return main or lin end --- a percentage chunk list -> a fraction 0..1 local function percent(ctx, p, stop) local b = ctx.b local v= nil @@ -144654,7 +142536,6 @@ if id == C.MATERIAL then end) end --- parse(b, base, limit, opts) -> Raw | nil, message, offset function Read.parse(b, base, limit, opts) if limit - base < 6 or readu16(b, base) ~= C.MAIN then return nil, "not a 3DS file (no 0x4D4D main chunk)", base @@ -144665,7 +142546,6 @@ if limit - base < 6 or readu16(b, base) ~= C.MAIN then if size < 6 then return nil, "bad main chunk size", base end - -- a main chunk declared longer than the data: truncated if base + size > limit then return nil, "truncated: the main chunk runs past the end of the data", base end @@ -144689,15 +142569,8 @@ return Read end __FILES["model/3ds/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world --- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's --- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 --- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with --- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and --- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in --- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key --- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. --- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does +-- (positive keyframer transform, mirror in the mesh matrix). local Bytes = __include("core/Bytes") local Types = __include("Types") local Sampler = __include("codecs/model/Sampler") @@ -144798,7 +142671,6 @@ local l = sqrt(x * x + y * y + z * z) return x / l, y / l, z / l end --- a quaternion -> the 3DS (clockwise angle, axis) local function axisAngle(q) local x, y, z, w = q[1], q[2], q[3], q[4] local n = sqrt(x * x + y * y + z * z + w * w) @@ -144818,7 +142690,6 @@ local function conj(q) return { -q[1], -q[2], -q[3], q[4] } end --- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) local function sample(ch, t) local f = Sampler.channel(ch) if not f then @@ -144881,7 +142752,6 @@ local bc = m.baseColor or { 1, 1, 1, 1 } if x.wire then leaf(w, C.MAT_WIRE, function() end) end - -- maps: the PBR texture refs first, then the other kinds model/3ds read local maps= {} local function fromRef(ref, saved) if not ref or not files[ref.texture] then @@ -144933,7 +142803,6 @@ maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) close(w, at) end -- ------------------------------------------------------------------------------------------------ meshes --- the mesh as 3DS parts (local space), or nil, message @@ -144950,7 +142819,6 @@ return n == "TEXCOORD_0" or n == "NORMAL" local tv, tc = (T and{T.values }or{nil})[1], (T and{T.components }or{0 })[1] local flipV = opts.flipV ~= false local corners = merged.corners - -- per face: material, smoothing group local nf = math.floor(#corners / 3 ) local fmat, fsg = table.create(nf, 0), table.create(nf, 1) for _, part in __iter(merged.parts) do @@ -144962,7 +142830,6 @@ return n == "TEXCOORD_0" or n == "NORMAL" })[1] if savedOk then fsg[f] = saved[f - part.firstFace] elseif N then - -- flat when every corner normal is the face normal local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } @@ -145088,7 +142955,6 @@ local function writeMesh(w, part, M, matNames) end -- ------------------------------------------------------------------------------------------------ cameras / lights --- the eye, target and roll of a node's world matrix (looking down -Z, Y up) local function aim(m, dist) local p = { m[13], m[14], m[15] } local fx, fy, fz = unit(-m[9], -m[10], -m[11]) @@ -145096,7 +142962,6 @@ local p = { m[13], m[14], m[15] } fx, fy, fz = 0, 0, -1 end local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } - -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis local q0 = Build.lookAt(p, t, 0) local m0 = Mat4.fromQuat(q0) local ux, uy, uz = unit(m[5], m[6], m[7]) @@ -145179,7 +143044,6 @@ local function writeTrack(w, id, frames, values, size) end) end --- frames (rounded, strictly increasing) and the indices of the channel keys they keep @@ -145248,7 +143112,6 @@ local o= opts or {} leaf(w, C.MESH_VERSION, function() w:u32le(3) end) - -- materials (unique names) local files = textureFiles(scene, o) local matNames= {} local used= {} @@ -145268,7 +143131,6 @@ local n, k = base, 1 leaf(w, C.MASTER_SCALE, function() w:f32le(1) end) - -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) used = {} local firstNode= {} for _, i in __iter(order) do @@ -145298,7 +143160,6 @@ __DARKLUA_CONTINUE_37=true break writeMesh(w, part, M, matNames) end __DARKLUA_CONTINUE_37=true until true if not __DARKLUA_CONTINUE_37 then break end end - -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors local KW= {} for _, i in __iter(order) do local n = scene.nodes[i] @@ -145335,7 +143196,6 @@ local __DARKLUA_CONTINUE_41=false repeat local n = scene.nodes[i] local kn= { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } table.insert(kfs, kn) local idx = #kfs - -- animated root cameras / lights: position, target and roll at the key times local chs= (p == 0 and{byNode[i] }or{nil })[1] local targetFrames, targetVals = { 0 }, tgt if chs and (chs.translation or chs.rotation) then @@ -145397,7 +143257,6 @@ if not camOrLight then end if onlyThis and idx then kfOf[i] = idx - -- the node's frame in the keyframer: the camera / light pose local kn = kfs[idx] local pos = kn.values.pos local m= W[i] @@ -145414,7 +143273,6 @@ if not camOrLight then camLight(true) __DARKLUA_CONTINUE_41=true break end - -- an object node (or a dummy) with the node's transform relative to its keyframer parent local pkw = (p ~= 0 and kfOf[p] and{KW[p] }or{S.IDENTITY })[1] local inv = Mat4.inverse(pkw) or Mat4.identity() local L = S.mul(inv, KW[i]) @@ -145423,7 +143281,6 @@ __DARKLUA_CONTINUE_41=true break })[1] local objName = (plist and{plist[1].name }or{"$$$DUMMY" })[1] local instance = (plist and n.name and n.name ~= objName and{(name(n.name, objName) )}or{(not plist and{(name(n.name, "Dummy" .. i) )}or{nil })[1]})[1] local kn= { chunk = 0xB002, name = objName, instance = instance, parent = (pk and((pk - 1 ))or((-1))), frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } - -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) local chs = byNode[i] if chs then local own = S.nodeMatrix(n) @@ -145464,7 +143321,6 @@ __DARKLUA_CONTINUE_41=true break camLight(false) __DARKLUA_CONTINUE_41=true until true if not __DARKLUA_CONTINUE_41 then break end end close(w, ed) - -- the keyframer local kf = open(w, C.KEYFRAMER) leaf(w, C.KF_HDR, function() w:u16le(5) @@ -145518,23 +143374,9 @@ return Write end __FILES["model/3mf"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, --- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts --- (codecs/text/Xml). --- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from --- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices --- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata --- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours --- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to --- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it --- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first --- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices --- are split where a vertex's corners carry different colours / texture coordinates. --- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a --- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, --- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). --- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are --- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). +-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path). +-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups. +-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -145570,7 +143412,6 @@ function ThreeMf.sniff(r) if r:peek(4) ~= "PK\3\4" then return 0 end - -- the central directory sits at the end: look for the model part's name there, then at the start local n = r:size() local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then @@ -145615,13 +143456,8 @@ return ThreeMf end __FILES["model/3mf/Read"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first --- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), --- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension --- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, --- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. --- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and --- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under +-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -145637,7 +143473,6 @@ local MAX_DEPTH = 64 local localName = Xml.localName --- an attribute by local name (namespaced attributes such as p:path) local function attr(node, name) local a = node.attrs local v = a[name] @@ -145660,7 +143495,7 @@ local n = (s and{(tonumber(s) )}or{nil return nil end --- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +-- "#RRGGBB" / "#RRGGBBAA", sRGB local function hexColor(s) if type(s) ~= "string" then return nil @@ -145684,7 +143519,7 @@ if c <= 0.04045 then end local toLinear = Read.toLinear --- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention local function transform(s) if not s then return nil, true @@ -145714,7 +143549,6 @@ p = string.gsub(p, "\\", "/") p = string.gsub(p, "^/+", "") return p end --- one model part parsed into its resources and build @@ -145869,7 +143703,6 @@ __DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end return model, nil end --- the root model part's path local function rootPath(zip) local rels = zip:readString("_rels/.rels") if rels then @@ -145929,7 +143762,6 @@ local p = normPath(path) scene.meta.metadata = root.metadata scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } - -- textures and materials (shared across model parts by part path + resource id) local texCache= {} local function texture(model, id) local key = model.path .. "#" .. id @@ -145975,7 +143807,6 @@ local m = Types.Scene.material(name) return m end - -- property of one corner -> (group key, material index?, kind, resource, index) local function resolve(model, pid, p, depth) local r = model.res[pid] if not r or p < 0 then @@ -146045,7 +143876,6 @@ local r = model.res[pid] return "none", nil, "none", nil, 0 end - -- one Scene mesh per (part, object) with a mesh local meshCache= {} local function buildMesh(model, o) local key = model.path .. "#" .. o.id @@ -146148,7 +143978,6 @@ local key = model.path .. "#" .. o.id return #scene.meshes end - -- nodes: one per object instance (build items and components) local nodeCount = 0 local maxNodes = opts.maxNodes or 2 ^ 20 local instantiate @@ -146215,12 +144044,7 @@ return Read end __FILES["model/3mf/Write"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, --- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the --- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), --- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has --- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). --- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -146264,7 +144088,6 @@ return math.clamp(math.floor(x * 255 + 0.5), 0, 255) return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) end --- the triangle corner list of a primitive (0-based vertex indices) or nil local function triangles(prim) local pos = prim.attributes and prim.attributes.POSITION if type(pos) ~= "table" then @@ -146344,10 +144167,9 @@ local o = opts or {} nextId =nextId+ 1 return nextId end - local res= {} -- resource XML chunks, in definition order + local res= {} local files= {} - -- unit local unitName, scale= "millimeter", 1 local mu= scene.meta and scene.meta.unit if type(o.unit) == "string" and UNITS[o.unit] then @@ -146368,16 +144190,14 @@ nextId =nextId+ 1 end end - -- base materials: one group with every Scene material local baseId= nil local nmat = #scene.materials - local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local defaultBase = nmat local needDefault = false if nmat > 0 then baseId = id() end - -- textures used as base colour textures local texRes= {} local function textureId(ti) if texRes[ti] ~= nil then @@ -146402,7 +144222,6 @@ return w == "clamp" and"clamp" or(w == "mirror" and"mirror" or"wrap" return rid end - -- objects local objectOf= {} local objChunks= {} for mi, mesh in __iter(scene.meshes) do @@ -146411,7 +144230,7 @@ local __DARKLUA_CONTINUE_10=false repeat local verts= {} local base = 0 local objPid, objP= nil, nil local anyNone = false - local triList= {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + local triList= {} for _, prim in __iter(mesh.primitives) do local __DARKLUA_CONTINUE_11=false repeat local corners = triangles(prim) if not corners or #corners == 0 then @@ -146426,7 +144245,6 @@ __DARKLUA_CONTINUE_11=true break for v = 0, n - 1 do table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num((pos.components >= 2 and{(getP(v, 1) )}or{0})[1]), num((pos.components >= 3 and{(getP(v, 2) )}or{0})[1]))) end - -- properties: texture group, colour group, base material, none local pid, kind = -1, "none" local mat = prim.material and scene.materials[prim.material] local uv = prim.attributes.TEXCOORD_0 @@ -146512,7 +144330,6 @@ __DARKLUA_CONTINUE_10=true break table.insert(res, objChunks[#objChunks]) __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end - -- the base material group goes first (its id was taken first) if baseId then local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) } for _, m in __iter(scene.materials) do @@ -146526,7 +144343,6 @@ __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break en table.insert(res, 1, table.concat(parts)) end - -- build items: every node with a mesh, at its world matrix local items= {} local seen= {} for _, pl in __iter(Types.Scene.flatten(scene)) do @@ -146558,7 +144374,6 @@ __DARKLUA_CONTINUE_18=true break end __DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end - -- metadata local meta= {} local md = scene.meta and scene.meta.metadata if type(md) == "table" then @@ -146634,23 +144449,9 @@ return Write end __FILES["model/b3d"] = function() --!strict --- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description --- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. --- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, --- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> --- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is --- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree --- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / --- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the --- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights --- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the --- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, --- default 60) -> one animation of LINEAR channels at frame / fps seconds. --- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding --- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their --- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. --- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the --- extras; texture coordinate sets of 3 / 4 components keep their first two. +-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp). +-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored. +-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -146689,7 +144490,6 @@ function B3d.decode(r, opts) if r:peek(4) ~= "BB3D" then return nil, Err.new(Err.CORRUPT, "no BB3D chunk") end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, r, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) @@ -146704,10 +144504,7 @@ return B3d end __FILES["model/b3d/Read"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are --- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes --- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene. local Bytes = __include("core/Bytes") local Types = __include("Types") local Chunks = __include("containers/Chunks") @@ -146725,8 +144522,8 @@ local Read = {} local LAYOUT= { maxChunks = 1000000 } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } --- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated --- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse +-- rotation, as assimp reads them) then mirrored @@ -146759,7 +144556,6 @@ local v= (type(files) == "table" and{files[uri] }or{nil })[1]})[1] end end --- scene(r, opts) -> Scene | nil, message, kind function Read.scene(src, opts) local buf = src.buf local maxVertices = opts and opts.maxVertices or 2 ^ 24 @@ -146782,7 +144578,7 @@ local buf = src.buf local scene = Types.Scene.new() local texs= {} local brushes= {} - local materialOf= {} -- brush index (0-based) -> material + local materialOf= {} local meshes= {} local bones= {} local nodeKeys= {} @@ -146846,7 +144642,6 @@ if c.truncated then end end - -- the material of brush id (0-based) | nil for -1 / out of range local function material(id) if id < 0 or id >= #brushes then return nil @@ -146995,7 +144790,6 @@ local master = r:i32le() fail(string.format("triangle %d: vertex index out of range", i)) return nil end - -- mirrored z: reverse the winding to keep the faces front-facing writeu32(idx, i * 12, a) writeu32(idx, i * 12 + 4, cc) writeu32(idx, i * 12 + 8, b) @@ -147007,7 +144801,7 @@ local master = r:i32le() end end if not attrs then - return nil -- a mesh without vertices: the node stays a pivot + return nil end if #mesh.primitives == 0 then table.insert(mesh.primitives, { attributes = attrs, mode = "points" }) @@ -147177,7 +144971,7 @@ local w = worldCache[i] end end end - local self= nil -- the mesh node as a joint, for vertices no bone moves + local self= nil local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) for v = 0, nv - 1 do local e = inf[v + 1] @@ -147189,7 +144983,6 @@ local w = worldCache[i] buffer.writeu16(jb, v * 8, self ) buffer.writef32(wb, v * 16, 1) else - -- the 4 strongest, normalised local order = {} for k = 1, #e, 2 do table.insert(order, k) @@ -147273,7 +145066,7 @@ return e[a + 1] > e[b + 1] brushes = #brushes, frames = (anim and{anim.frames }or{nil})[1], fps = (anim and{anim.fps }or{nil})[1], - handedness = "left", -- converted: z mirrored, winding reversed + handedness = "left", } return scene, nil, nil end @@ -147282,13 +145075,8 @@ return Read end __FILES["model/bsp"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) --- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a --- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III --- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as --- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not --- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. --- Quake II .wal sizes come from opts.resolve("textures/<name>.wal") / opts.files. Units are map units, z up. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW +-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. -- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -147338,7 +145126,6 @@ if r:remaining() < 64 then return (v == 38 or v == 46 or v == 47 )and 1 or 0.3 end if v == 29 or v == 30 then - -- no magic: check that the lump directory fits the file local size = r:remaining() for i = 0, 14 do local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) @@ -147352,7 +145139,6 @@ if r:remaining() < 64 then end -- ------------------------------------------------------------------------------------------------ decode --- the entities text -> { { key = value } } local function entities(text) local out= {} for block in __iter(string.gmatch(text, "%b{}")) do @@ -147434,15 +145220,9 @@ return Bsp end __FILES["model/bsp/Brush"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex --- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture --- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the --- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / --- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the --- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from --- opts.resolve("textures/<name>.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). --- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. --- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the +-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture +-- size. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") @@ -147467,7 +145247,6 @@ local function cstr(b, at, n) return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) end --- miptex lump (Quake / Half-Life) -> textures local function miptex(b, base, l, hl, pal, maxPixels) local out= {} if l.size < 4 then @@ -147515,9 +145294,6 @@ local out= {} return out, nil end --- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message --- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, --- models, miptex (q1 / hl) function Brush.decode(b, base, lumps, variant, opts) local q2 = variant == "q2" local maxPixels = opts and opts.maxPixels or 2 ^ 24 @@ -147530,9 +145306,8 @@ local q2 = variant == "q2" ) if nF > (opts and opts.maxVertices or 2 ^ 24) then return nil, "limit: too many faces" end - -- textures local texs= {} - local texOf= {} -- texinfo -> texture index (1-based) + local texOf= {} if q2 then local byName= {} for i = 0, nTI - 1 do @@ -147561,7 +145336,6 @@ local q2 = variant == "q2" texOf[i + 1] = (mt >= 0 and mt < #texs and((mt + 1 ))or(0 )) end end - -- faces of each model local scene = Scene.new() scene.meta.up = "z" local faceModel= {} @@ -147595,7 +145369,6 @@ local __DARKLUA_CONTINUE_8=false repeat local fo = base + Fc.at + f * 20 skipped =skipped+ 1 __DARKLUA_CONTINUE_8=true break end - -- the polygon local poly= {} local ok = true for k = 0, numEdges - 1 do @@ -147624,7 +145397,7 @@ __DARKLUA_CONTINUE_8=true break if side ~= 0 then nx, ny, nz = -nx, -ny, -nz end - -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + -- Newell's normal of the polygon as stored local n = math.floor(#poly / 3 ) local ax, ay, az = 0, 0, 0 for k = 0, n - 1 do @@ -147674,7 +145447,6 @@ __DARKLUA_CONTINUE_8=true break end end __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end - -- textures, materials for i, t in __iter(texs) do local tex= { name = t.name, image = t.image, uri = (t.image and{nil }or{((q2 and(("textures/" .. t.name .. ".wal" ))or(t.name))) })[1]} table.insert(scene.textures, tex) @@ -147685,7 +145457,6 @@ __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } } table.insert(scene.materials, mat) end - -- meshes and nodes local root= { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 @@ -147727,13 +145498,8 @@ return Brush end __FILES["model/bsp/Quake3"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a --- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches --- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap --- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 --- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as --- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. --- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. local Types = __include("Types") local Quake3 = {} @@ -147751,13 +145517,12 @@ local function cstr(b, at, n) return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) end --- decode(b, base, lumps, opts) -> Scene | nil, message function Quake3.decode(b, base, lumps, opts) local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps local nT, nM, nV, nMV, nF, nLM = math.floor(T.size / 72), math.floor(M.size / 40), math.floor(VX.size / 44), math.floor(MV.size / 4), math.floor(F.size / 104), math.floor(LM.size / 49152 ) local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) local maxV = opts and opts.maxVertices or 2 ^ 24 - -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + -- patch vertices: 12 floats + 4 colour bytes each local extra= {} local function vertex(i) local o = base + VX.at + i * 44 @@ -147820,7 +145585,6 @@ end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local L = level for py = 0, math.floor((h - 1) / 2 )- 1 do for px = 0, math.floor((w - 1) / 2 )- 1 do - -- the 3x3 control points of this sub-patch local ctrl= {} for j = 0, 2 do for i = 0, 2 do @@ -147855,7 +145619,7 @@ end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then for gx = 0, L - 1 do local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- counter-clockwise for Quake's clockwise-front control grids + -- Quake's control grids are clockwise-front for _, v in __iter({ a, d, c2, c2, d, e }) do table.insert(tris, v) end @@ -147894,7 +145658,6 @@ end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then end local scene = Scene.new() scene.meta.up = "z" - -- shaders, lightmaps for i = 0, nT - 1 do local name = cstr(b, base + T.at + i * 72, 64) table.insert(scene.textures, { name = name, uri = name }) @@ -147990,28 +145753,10 @@ return Quake3 end __FILES["model/dae"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its --- manifest.xml and the images). New code. --- Reads: geometry (<mesh> triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input --- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), --- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / --- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> --- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), --- kept encoded (opts.resolve / opts.files, embedded hex <data>, data: URIs), the instanced visual scene (matrix / --- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances --- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under --- <skeleton> or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph --- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; --- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as --- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE --- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, --- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" --- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left --- origin (opts.flipV = false keeps Collada's). --- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. --- Not supported: <spline> / <brep> geometry, polygon holes (<ph>: the outer loop only), Bezier / Hermite curves --- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than --- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, +-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations. +-- Not supported: <spline> / <brep>, polygon holes (<ph>), Bezier / Hermite curves (sampled linearly), non-transform +-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -148098,7 +145843,7 @@ local v= nil })[1] end end --- the main .dae of a .zae: manifest.xml's <dae_root>, else the first .dae entry +-- a .zae's main .dae: manifest.xml's <dae_root>, else the first .dae entry local function zae(r) local zip, err = Zip.open(r) if not zip then @@ -148165,7 +145910,6 @@ if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "tab return nil, Err.new(Err.ARG, "needs a Scene") end if opts and opts.format == "zae" then - -- a zip: manifest.xml, the .dae and its images local files = {} local o = table.clone(opts) o.files = files @@ -148198,8 +145942,7 @@ return Dae end __FILES["model/dae/Math"] = function() --!strict --- model/dae/Math: the Collada-specific transform elements (<lookat>, <skew>); everything else (matrices, --- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +-- model/dae/Math: the Collada transform elements <lookat> and <skew>; matrices are flat column-major arrays of 16. local Mat4 = __include("codecs/model/Mat4") local DaeMath = {} @@ -148217,7 +145960,7 @@ local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) return { a[1] / l, a[2] / l, a[3] / l } end --- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +-- <lookat>: an object at eye whose -Z looks at interest function DaeMath.lookat(v) local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) @@ -148226,14 +145969,14 @@ local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } end --- skew(angle, rotation axis, translation axis) (RenderMan's skew) +-- <skew> (RenderMan's skew) function DaeMath.skew(v) local a = rad(v[1] or 0) local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) local s = math.tan(a) local m = Mat4.identity() - -- M = I + s * t * r^T (column-major: m[col*4 + row]) + -- M = I + s * t * r^T for row = 0, 2 do for col = 0, 2 do do local __DARKLUA_VAR=col * 4 + row + 1 m[__DARKLUA_VAR]=m[__DARKLUA_VAR]+ s * t[row + 1] * r[col + 1] @@ -148246,15 +145989,7 @@ return DaeMath end __FILES["model/dae/Read"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / --- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile --- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, --- images (kept encoded through the fetch callback, or embedded hex <data>), the visual scene's node tree (matrix / --- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin --- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as --- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform --- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS --- channels; one animation per animation clip, else one for the file). +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. local Err = __include("core/Err") local Types = __include("Types") local Xml = __include("codecs/text/Xml") @@ -148360,7 +146095,6 @@ local function skip(C, what) end -- ------------------------------------------------------------------------------------------------ sources --- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) local function readSource(C, el) local cached = C.sources[el] if cached ~= nil then @@ -148526,7 +146260,6 @@ local cached = C.images[id] return img end --- the effect's newparams by sid (this level and the profile's) local function newparams(effect, profile, technique) local out = {} for _, scope in __iter({ effect, profile, technique }) do @@ -148542,7 +146275,6 @@ local out = {} return out end --- texture(effect params, sampler sid) -> scene texture index local function texture(C, params, samplerSid) local np = params[samplerSid] local imageId= nil @@ -148611,7 +146343,6 @@ end return idx end --- one colour-or-texture parameter of a common technique local function param(C, params, el, uvsets) if not el then return nil, nil @@ -148721,7 +146452,7 @@ local cached = C.materials[id] if type(shininess) == "number" then mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) end - -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then local mode = attr(transparentEl, "opaque") or "A_ONE" local tv = (type(transparency) == "number" and{transparency }or{1 @@ -148775,7 +146506,6 @@ if mode == "RGB_ZERO" then return idx end -- ------------------------------------------------------------------------------------------------ geometry --- the inputs of a primitive element (VERTEX expanded into the <vertices> inputs) @@ -148810,7 +146540,6 @@ local out= {} return out, math.max(stride, 1) end --- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode local function corners(C, prim, kind, stride) local p= {} local faces= {} @@ -148915,7 +146644,6 @@ end local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true } --- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) local function buildPrim(C, prim, verticesEl, kind) @@ -148935,7 +146663,6 @@ local ins, stride = inputs(C, prim, verticesEl) skip(C, "primitives without positions") return nil end - -- attribute names local named= {} local texSets= {} local texInputs= {} @@ -148972,10 +146699,9 @@ if a.set ~= b.set then table.insert(named, { input = i, name = "_" .. s .. ((i.set ~= 0 and{(tostring(i.set) )}or{""})[1]), comps = math.max(comps, 1) }) end end - -- de-index local np = #p local keyOf= {} - local tuples= {} -- the first p index of each output vertex's tuple + local tuples= {} local corner = (table.create(#starts) ) local count = 0 for ci, s in __iter(starts) do @@ -149050,7 +146776,6 @@ if stride == 1 then if allTri then mode = "triangles" elseif C.triangulate then - -- fan triangulation local tri= {} local at = 0 for _, f in __iter(faces) do @@ -149079,7 +146804,6 @@ local ib = buffer.create(nc * 4) return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } end --- geometry(el) -> the built primitives (cached per geometry element) local function geometry(C, el) local cached = C.posIndex[el] if cached then @@ -149110,7 +146834,6 @@ end return out end --- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set local function bindings(node) local syms= {} local sets= {} @@ -149141,7 +146864,6 @@ local b = buffer.create(buffer.len(a.data)) return Scene.accessor(b, a.type, a.components, a.count) end --- mesh(geometry element, instance element, skin?) -> scene mesh index local function meshFor(C, geomEl, inst, key, bindShape) local syms, sets = bindings(inst) local parts = { key } @@ -149162,7 +146884,6 @@ local syms, sets = bindings(inst) for _, b in __iter(built) do local prim = b.prim if bindShape then - -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) local attrs = table.clone(prim.attributes) local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do @@ -149208,7 +146929,6 @@ local syms, sets = bindings(inst) end end if target then - -- texcoord semantic -> TEXCOORD_n index among this primitive's sets local uv= {} for sem, set in __iter((sym and sets[sym]) or {}) do uv[sem] = (table.find(b.texSets, set) or 1) - 1 @@ -149223,7 +146943,6 @@ local syms, sets = bindings(inst) return idx, built end --- morph controller -> mesh with targets (deltas) local function morphMesh(C, ctrl, morph, inst) local base = C.ids[urlId(attr(morph, "source")) or ""] if not base or lname(base) ~= "geometry" then @@ -149329,7 +147048,6 @@ else return #C.scene.cameras end --- light(el) -> light index, or nil and the ambient colour local function light(C, el) local tc = child(el, "technique_common") if not tc then @@ -149371,7 +147089,6 @@ end -- ------------------------------------------------------------------------------------------------ nodes local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } --- the matrix of one transform element's values local function xfMatrix(kind, v) if kind == "matrix" then return Mat4.fromRows(v) @@ -149429,7 +147146,7 @@ table.insert(C.scene.nodes, node) return idx end --- the instances of a node: the first of each kind on the node itself, the rest on child nodes +-- extra instances of a node go on child nodes local function instances(C, el, node, idx) local function slot(kind, name) local n= node @@ -149569,7 +147286,7 @@ end end -- ------------------------------------------------------------------------------------------------ skins --- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +-- joints: by sid below the skeleton roots, else by sid / id / name anywhere local function findJoint(C, name, roots, byId) local nodes = C.scene.nodes local function search(i, depth) @@ -149657,7 +147374,7 @@ __DARKLUA_CONTINUE_71=true break local skin= { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } if ps.bind then local sk= skin - sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + sk.extras = { dae = { bindShapeMatrix = ps.bind } } end if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) @@ -149679,7 +147396,6 @@ __DARKLUA_CONTINUE_71=true break cache[key] = si end C.scene.nodes[ps.node].skin = si - -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) local mesh = C.scene.meshes[ps.mesh] if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then __DARKLUA_CONTINUE_71=true break @@ -149704,7 +147420,7 @@ __DARKLUA_CONTINUE_71=true break local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} local wdata = wSrc and wSrc.data or {} - local per= {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local per= {} local at = 0 for pi, c in __iter(vcount) do local list = {} @@ -149802,8 +147518,8 @@ for k = 1, st do return a end --- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element -local function target(C, s) -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" +-- "id/sid/sid.member" or "id/sid(i)(j)" +local function target(C, s) -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" local id, sids = match(s, "^([^/]*)/(.*)$") if not id then @@ -149854,7 +147570,6 @@ local id, sids = match(s, "^([^/]*)/(.*)$") return nodes, xf, member end --- the channels of one <animation> (recursively) -> curves grouped by node local function collect(C, anim, byNode, order, depth) if depth > 64 then return @@ -149944,7 +147659,6 @@ local channels= {} local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) local prev= nil for i, t in __iter(times) do - -- this time's values of each animated element local xf = {} for k, x in __iter(info.xf) do xf[k] = { kind = x.kind, values = table.clone(x.values) } @@ -149985,7 +147699,6 @@ local channels= {} table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } ) table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } ) table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } ) - -- the node is now TRS-driven local node = C.scene.nodes[ni] if node.matrix then setTransform(node, node.matrix) @@ -150068,12 +147781,11 @@ local root = doc and doc.root } for _, el in __iter(Xml.descendants(root)) do local id = el.attrs.id - -- duplicate ids: the first one, unless it is empty (some exporters write <light id="x"/> before the real one) + -- duplicate ids: the first, unless empty (some exporters write <light id="x"/> before the real one) if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then C.ids[id] = el end end - -- asset: up axis, unit local asset = child(root, "asset") local up = asset and child(asset, "up_axis") local upAxis = (up and{(upper(match(text(up), "[%w_]+") or "Y_UP") )}or{"Y_UP" @@ -150081,8 +147793,7 @@ local root = doc and doc.root local unit = asset and child(asset, "unit") local meter = unit and attr(unit, "meter") scene.meta.unit = (meter and{tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 }or{1 -})[1] -- the instanced visual scene (else the first one) - local vsId= nil +})[1] local vsId= nil local sceneEl = child(root, "scene") local ivs = sceneEl and child(sceneEl, "instance_visual_scene") if ivs then @@ -150128,11 +147839,8 @@ return Read end __FILES["model/dae/Write"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- model/dae/Write: Scene -> Collada 1.4.1 text. One <geometry> per mesh primitive (triangles, lines or polylist; strips --- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n --- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its --- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major <matrix>; cameras; --- lights. Not written: skins, morph targets, animations. +-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major <matrix>. +-- Not written: skins, morph targets, animations. local Types = __include("Types") local Xml = __include("codecs/text/Xml") local Base64 = __include("core/Base64") @@ -150167,7 +147875,6 @@ local function nameAttr(s) return (s and((' name="' .. esc(s) .. '"' ))or("" ))end --- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind local function corners(prim) local n = prim.attributes.POSITION.count local idx= {} @@ -150289,7 +147996,6 @@ local files = opts and type(opts.files) == "table" and opts.files or nil local meta= scene.meta or {} local up = meta.up == "z" and"Z_UP" or(meta.up == "x" and"X_UP" or"Y_UP" ) w(format('<asset><contributor><authoring_tool>rosetta</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up)) - -- images local imageId= {} if #scene.textures > 0 then w("<library_images>\n") @@ -150313,12 +148019,11 @@ local files = opts and type(opts.files) == "table" and opts.files or nil end w("</library_images>\n") end - -- effects + materials if #scene.materials > 0 then w("<library_effects>\n") for i, mat in __iter(scene.materials) do local ph= mat.extras and mat.extras.phong or {} - local params= {} -- the newparam strings, and their sids as seen-keys + local params= {} local function texParam(ref) if not ref or not imageId[ref.texture] then return nil, nil @@ -150365,7 +148070,6 @@ if not ref or not imageId[ref.texture] then end w("</library_materials>\n") end - -- geometries: one per primitive local geoms= {} w("<library_geometries>\n") for mi, mesh in __iter(scene.meshes) do @@ -150418,7 +148122,6 @@ __DARKLUA_CONTINUE_15=true break __DARKLUA_CONTINUE_15=true until true if not __DARKLUA_CONTINUE_15 then break end end end w("</library_geometries>\n") - -- cameras / lights if #scene.cameras > 0 then w("<library_cameras>\n") for i, cam in __iter(scene.cameras) do @@ -150445,7 +148148,6 @@ if cam.type == "orthographic" then end w("</library_lights>\n") end - -- the node tree w('<library_visual_scenes><visual_scene id="scene" name="scene">\n') local seen= {} local function node(i, depth) @@ -150506,26 +148208,9 @@ return Write end __FILES["model/fbx"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays --- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and --- assimp's FBX importer, and the FBX SDK's documentation of the transform model. --- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl --- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms --- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, --- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference --- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR --- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins --- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets --- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and --- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for --- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). --- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives --- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), --- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + --- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler --- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). --- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered --- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). +-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs. +-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras. +-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -150607,8 +148292,6 @@ end local toErr = Err.from --- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. --- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. function Fbx.tree(r, opts) if r:peek(21) == MAGIC then local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) @@ -150636,7 +148319,6 @@ local root, version, binary = Fbx.tree(r, opts) if not root then return nil, version end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) @@ -150674,9 +148356,8 @@ return Fbx end __FILES["model/fbx/Ascii"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' --- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary --- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays, +-- " in strings); integers longer than 15 digits stay strings so ids are exact. local Base64 = __include("core/Base64") local Ascii = {} @@ -150690,7 +148371,6 @@ local function isNameStart(c) return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end --- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset function Ascii.parse(text, opts) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local n = #text @@ -150711,7 +148391,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 30 end end - -- at i: a name followed by ':'? -> name, the index after ':' local function nameAt() local c = sbyte(text, i) if not c or not isNameStart(c) then @@ -150736,7 +148415,6 @@ local c = sbyte(text, i) return nil, i end - -- the values of one node (after the ':'), up to a new name, '{' or '}' local function values() local props= {} while true do @@ -150838,7 +148516,6 @@ while true do return e end end - -- "*N { a: v, v, ... }" -> an Array local p1 = props[1] if #props == 1 and type(p1) == "table" and p1.star then local a = node.children[1] @@ -150888,7 +148565,6 @@ if v == math.floor(v) and math.abs(v) < 1e15 then return string.format("%.17g", v) end --- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) function Ascii.write(root, version) local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", math.floor((version or 7400) / 1000), math.floor((version or 7400) % 1000 / 100)) } local function node(nd, indent) @@ -150911,7 +148587,7 @@ local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\ elseif tv == "table" and v.array then arr = v elseif tv == "buffer" then - -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + -- raw bytes (Video Content): base64 split into lines as the FBX SDK writes them local b64 = Base64.encode(v) local chunks = {} for k = 1, #b64, 2048 do @@ -150951,11 +148627,8 @@ end __FILES["model/fbx/Binary"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit --- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's --- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array --- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become --- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset). +-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by +-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L<hex>" so ids stay exact. local Deflate = __include("codecs/compress/Deflate") local Binary = {} @@ -150972,7 +148645,7 @@ local MAX_DEPTH = 128 local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 local writef64 = buffer.writef64 --- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +-- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>" local function i64(b, p, asString) local lo, hi = readu32(b, p), readu32(b, p + 4) if hi >= 0x80000000 then @@ -150991,7 +148664,6 @@ Binary.i64 = i64 local ELEM= { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } --- the elements of a raw array (n elements of type t at p) as f64s local function toF64(t, src, p, n) local out = buffer.create(n * 8) if t == "d" then @@ -151017,7 +148689,6 @@ local out = buffer.create(n * 8) return out end --- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset function Binary.parse(b, base, limit, opts) local maxBytes = opts and opts.maxBytes or 2 ^ 30 if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then @@ -151109,7 +148780,6 @@ if enc == 0 then return out, p end - -- one node record at p: node | false (the null record), next offset | nil, message, offset local function node(p, stop, depth) if p + head > stop then return nil, "truncated node record", p @@ -151180,10 +148850,8 @@ if p + head > stop then return root, version, nil end -- ------------------------------------------------------------------------------------------------ writer --- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit --- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint --- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their --- type (compressed with zlib when longer than 32 elements, unless compress = false). +-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per +-- property; arrays over 32 elements are zlib-compressed @@ -151413,17 +149081,8 @@ return Binary end __FILES["model/fbx/Read"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> --- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric --- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in --- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one --- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the --- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file --- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind --- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's --- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or --- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node --- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, +-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. local Err = __include("core/Err") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -151464,7 +149123,7 @@ local function isArray(v) return type(v) == "table" and v.array == true end --- the array under n.<name> (or inline numbers: old ASCII files) +-- old ASCII files have inline numbers local function array(n, name) local c = child(n, name) if not c then @@ -151501,7 +149160,7 @@ if i < 0 or i >= a.count then return buffer.readf64(a.data, i * 8) end --- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) local function objectName(s) if type(s) ~= "string" then return "" @@ -151518,7 +149177,7 @@ if type(s) ~= "string" then end Read.objectName = objectName --- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +-- Properties70: P: name, type, label, flags, values... local function properties(n, into) local out = into or {} local p70 = child(n, "Properties70") @@ -151569,7 +149228,7 @@ local triangulate = not (opts and opts.triangulate == false) local maxVertices = opts and opts.maxVertices or 2 ^ 25 local scene = Types.Scene.new() - -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + -- Definitions/ObjectType/PropertyTemplate local templates= {} local defs = child(root, "Definitions") if defs then @@ -151583,7 +149242,6 @@ local triangulate = not (opts and opts.triangulate == false) end end - -- objects local objects= {} local order= {} local objs = child(root, "Objects") @@ -151601,7 +149259,6 @@ local triangulate = not (opts and opts.triangulate == false) end end - -- connections: children (sources) of each parent, parents of each child, in file order local kids= {} local parents= {} local conns = child(root, "Connections") @@ -151650,7 +149307,6 @@ local out = {} return out end - -- global settings local gs = properties(child(root, "GlobalSettings")) local upAxis = pnum(gs, "UpAxis", 1) local unitScale = pnum(gs, "UnitScaleFactor", 1) @@ -151694,7 +149350,7 @@ if not v then return p end end - -- ASCII: base64 strings (possibly split into several) + -- ASCII: base64, possibly split into several strings local parts = {} for _, p in __iter(c.props) do if type(p) == "string" then @@ -151798,7 +149454,6 @@ if p.Opacity then if opacity < 1 then m.alphaMode = "blend" end - -- 3ds Max Physical / PBR materials local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] if pbr then local prefix = p["3dsMax|main|basecolor"] and"3dsMax|main|" or"3dsMax|Parameters|" @@ -151918,7 +149573,6 @@ if over and over[key] then nd.scale = s end nd.extras = { fbx = { type = o.sub, id = o.id } } - -- parent local parentModel= nil for _, t2 in __iter(targets(o.id, "Model")) do parentModel = t2.obj @@ -151931,7 +149585,7 @@ if over and over[key] then table.insert(scene.roots, ni) end end - -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + -- break parent cycles: cut children already placed do local placed= {} local function visit(i) @@ -151951,13 +149605,11 @@ if over and over[key] then end for i in __iter(scene.nodes) do if not placed[i] then - -- part of a parent cycle: make it a root table.insert(scene.roots, i) visit(i) end end end - -- world matrices (rest pose) local worldM= {} local function world(i, parent) worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) @@ -151973,7 +149625,6 @@ if over and over[key] then -- ------------------------------------------------------------------------------------------ meshes local corners = 0 - -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels local function skinOf(geo) local skin = sources(geo.id, "Deformer", "Skin")[1] if not skin then @@ -152059,7 +149710,7 @@ local out = {} end local meshCache= {} - local shapeChannels= {} -- mesh index -> blend shape channel objects (for weights curves) + local shapeChannels= {} local nodeSkin= {} local skinCache= {} @@ -152076,7 +149727,6 @@ local g = geo.node if corners > maxVertices or ncp > maxVertices then return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") end - -- polygons: corner -> control point, polygon of each corner, polygon starts local cp = table.create(nc, 0) local polyOf = table.create(nc, 0) local starts= { 0 } @@ -152102,8 +149752,7 @@ local g = geo.node np =np+ 1 starts[np + 1] = nc end --- layer elements - + local function elems(kind, dataName, indexName, comps) local out= {} for _, c in __iter(g.children) do @@ -152125,7 +149774,6 @@ return a.order < b.order end) return out end - -- the data element of a corner (c 0-based), or -1 local function lookup(e, c) local m = e.mapping local i @@ -152156,7 +149804,7 @@ local m = e.mapping local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] - -- the normals index name varies ("NormalsIndex" / "NormalIndex") + -- "NormalsIndex" / "NormalIndex" for _, e in __iter(normals) do if not e.index then local c = nil @@ -152172,7 +149820,6 @@ local m = e.mapping end end end - -- polygons by material slot local groups= {} local slots= {} for p = 0, np - 1 do @@ -152199,7 +149846,7 @@ local m = e.mapping table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3= nil -- normal matrix (inverse transpose of G) + local N3= nil -- inverse transpose of G if G then local inv = Mat4.inverse(G) if inv then @@ -152418,12 +150065,11 @@ table.insert(scene.skins, skin) for _, o in __iter(models) do local ni = nodeOf[o.id] local nd = scene.nodes[ni] - -- materials of the model, in connection order local mats= {} for _, m in __iter(sources(o.id, "Material")) do table.insert(mats, material(m)) end - -- geometric transform (not inherited: baked into the mesh) + -- geometric transform: not inherited, baked into the mesh local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) @@ -152461,7 +150107,7 @@ table.insert(scene.skins, skin) end end end - -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis for _, a in __iter(sources(o.id, "NodeAttribute")) do local p = a.props if a.sub == "Camera" then @@ -152534,7 +150180,7 @@ local have = curveCache[o.id] times[k + 1] = at(kt, k) / TICKS values[k + 1] = at(kv, k) end - -- per-key attribute flags (expanded through KeyAttrRefCount) + -- expanded through KeyAttrRefCount local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") local flags = table.create(n, 4) local slopes= {} @@ -152637,11 +150283,10 @@ local n = math.floor(#vals / comps for _, stack in __iter(order) do if stack.class == "AnimationStack" then local anim= { name = stack.name, channels = {} } --- model id -> { T/R/S -> { axis -> curve } , defaults } - + local tracks= {} local trackOrder= {} - local morph= {} -- blend shape channel id -> DeformPercent curve + local morph= {} local layers = sources(stack.id, "AnimationLayer") for _, layer in __iter(layers) do for _, cn in __iter(sources(layer.id, "AnimationCurveNode")) do @@ -152742,7 +150387,6 @@ for k = 0, math.floor(#vals / comps )- 1 do end end end - -- morph target weights: every node whose mesh has an animated blend shape channel if next(morph) then for ni, nd in __iter(scene.nodes) do local chans = nd.mesh and shapeChannels[nd.mesh] @@ -152799,13 +150443,8 @@ return Read end __FILES["model/fbx/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types --- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). --- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one --- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals --- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; --- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> --- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +-- model/fbx/Write: Scene -> an FBX 7.4 node tree. Property types follow what Blender's and the FBX SDK's readers check +-- (ids L, ints I, doubles D, KTime L, arrays d / i / l / f); rotations as Euler XYZ degrees. local Err = __include("core/Err") local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -152828,7 +150467,7 @@ local n = #list end return { array = true, type = t, count = n, data = d } end --- P: name, type, label, flags, values (vt: one type character per value) +-- P: name, type, label, flags, values local function P(name, ptype, label, flags, vt, ...) return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } end @@ -152864,7 +150503,6 @@ if not acc then return Types.Scene.reader(acc) end --- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) local function faces(prim) local pos = prim.attributes.POSITION if not pos then @@ -153035,7 +150673,6 @@ nextId =nextId+ 1 link(m.baseColorTexture, "DiffuseColor") link(m.normalTexture, "NormalMap") link(m.emissiveTexture, "EmissiveColor") - -- the other textures the FBX material had (specular, metalness, ... maps), under their property names local linked = { [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, [m.normalTexture and m.normalTexture.texture or -1] = true, @@ -153060,7 +150697,7 @@ nextId =nextId+ 1 -- ------------------------------------------------------------------------------------------ models local modelIds= {} local skip= {} - local attrHost= {} -- orientation node -> its parent node (the attribute moves there) + local attrHost= {} local parentOf= {} for i, nd in __iter(nodes) do for _, c in __iter(nd.children or {}) do @@ -153083,7 +150720,6 @@ nextId =nextId+ 1 attrHost[i] = p end end - -- world matrices (rest pose) for clusters and the bind pose local worldM= {} local visiting= {} local function world(i) @@ -153190,8 +150826,7 @@ local mid = id() local euler = Mat4.eulerXYZ(r) local ftype = nd.extras and (nd.extras ).fbx and (nd.extras ).fbx.type local sub = nd.mesh and"Mesh" or((jointSet[i] or ftype == "LimbNode" )and"LimbNode" or"Null" -) -- an orientation child folded into this node gives it its attribute - local folded= nil +) local folded= nil for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) if host == i then folded = c @@ -153230,9 +150865,9 @@ local mid = id() -- ------------------------------------------------------------------------------------------ geometry local geoIds= {} - local geoSlots= {} -- mesh -> material indices by slot + local geoSlots= {} local geoVerts= {} - local geoChannels= {} -- mesh index -> blend shape channel ids (for weights animation) + local geoChannels= {} local geoCount= {} local function geometry(mi) if geoIds[mi] then @@ -153425,7 +151060,6 @@ if geoIds[mi] then geoSlots[mi] = (anyMat and{slots }or{{} })[1] geoVerts[mi] = layout geoCount[mi] = offset - -- morph targets local prims = mesh.primitives local ntargets = 0 for _, l in __iter(layout) do @@ -153517,7 +151151,6 @@ if geoIds[mi] then OO(pm, mid) end end - -- skin: one Skin per (geometry, skin) local skin = nd.skin and scene.skins[nd.skin] local key = tostring(gid) .. ":" .. tostring(nd.skin) if skin and not skinned[key] then @@ -153528,7 +151161,6 @@ if geoIds[mi] then local meshWorld = world(i) pose(mid, meshWorld) local ibm = accessorReader(skin.inverseBindMatrices) - -- per joint: control points and weights local perJoint= {} for j in __iter(skin.joints) do perJoint[j] = { idx = {}, w = {} } @@ -153678,7 +151310,6 @@ local e = (cubic and((k * 3 + 1 ))or(k end table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) else - -- weights: one DeformPercent curve per blend shape channel of the node's mesh local nd = nodes[ch.node] local gc= geoChannels local chans = nd.mesh and gc[nd.mesh] @@ -153797,9 +151428,8 @@ return Write end __FILES["model/fbx/Xform"] = function() --!strict --- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model --- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The --- matrix / quaternion arithmetic is codecs/model/Mat4. +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): +-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1 local Mat4 = __include("codecs/model/Mat4") local Xform = {} @@ -153809,7 +151439,6 @@ local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } function Xform.euler(x, y, z, order) return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") end --- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers @@ -153826,7 +151455,6 @@ local m = Mat4.translation(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p. end m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - -- the inverse of a rotation is its transpose m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) @@ -153841,24 +151469,9 @@ return Xform end __FILES["model/gltf"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and --- binary (.glb). New code. --- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every --- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR --- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, --- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, --- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, --- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, --- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a --- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. --- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). --- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes <name>.bin and the --- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). --- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the --- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back --- uncompressed (the extension is dropped). --- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels --- (skipped and counted in the animation's extras). +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*, +-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed). +-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -153940,7 +151553,6 @@ return string.char((tonumber(h, 16) )) })[1] end end --- the JSON text and BIN chunk of a GLB local function glb(r) local magic, version, length = r:u32le(), r:u32le(), r:u32le() if r.err then @@ -154020,7 +151632,6 @@ if type(scene) ~= "table" or scene.kind ~= "scene" then local doc = out.doc local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local files = opts and opts.files - -- images: data: URIs, or files if doc.images then local n = 0 for _, im in __iter(doc.images) do @@ -154096,16 +151707,12 @@ end __FILES["model/gltf/Pack"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene --- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range --- first (offsets, strides and counts against the buffer lengths); nothing here throws. +-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers +-- check every range first. glTF pads matrix columns to 4 bytes. local Pack = {} local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 --- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is --- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = --- cols * colBytes bytes each) function Pack.gather(dst, src, off, count, elem, stride, cols, colBytes, colStride) if cols == 1 or colBytes == colStride then if stride == elem then @@ -154126,7 +151733,6 @@ function Pack.gather(dst, src, off, count, elem, stride, cols, colBytes, colStri end end --- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) function Pack.scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride) if cols == 1 or colBytes == colStride then if stride == elem then @@ -154147,8 +151753,6 @@ function Pack.scatter(dst, at, src, count, elem, stride, cols, colBytes, colStri end end --- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element --- idx[k] of dst becomes value k (values packed, elem bytes each) function Pack.sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) for k = 0, n - 1 do local i @@ -154171,12 +151775,8 @@ return Pack end __FILES["model/gltf/Read"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type --- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, --- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the --- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the --- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, --- scenes. glTF extras and unhandled extensions are kept in <object>.extras.gltf = { extras, extensions }. +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are +-- kept in <object>.extras.gltf = { extras, extensions }. local Err = __include("core/Err") local Types = __include("Types") local Base64 = __include("core/Base64") @@ -154199,7 +151799,7 @@ local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } local WRAP= { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } --- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +-- the extensions this reader understands (any other required one -> UNSUPPORTED) local KNOWN = { KHR_lights_punctual = true, KHR_mesh_quantization = true, @@ -154255,7 +151855,6 @@ if type(v) ~= "table" or #v ~= n then return table.move(v, 1, n, 1, {} ) end --- extras.gltf: the JSON extras and the extensions not turned into Scene fields local function keep(obj, handled) local extras = obj.extras local ext= nil @@ -154274,8 +151873,7 @@ local extras = obj.extras return { gltf = { extras = extras, extensions = ext } } end --- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value --- by value: normalized integers <-> floats, ints widened or narrowed) +-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value local DRACO_HANDLED = { KHR_draco_mesh_compression = true } local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } local DRACO_SAME= { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } @@ -154343,7 +151941,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 30 end end local scene = Types.Scene.new() - -- buffers local buffers= {} local total = 0 for i, b in __iter(arr(doc.buffers)) do @@ -154400,7 +151997,6 @@ end end views[i] = { buf = b, offset = off, length = len, stride = stride } end - -- accessors local accessors= {} for i, a in __iter(arr(doc.accessors)) do local label = "accessor " .. (i - 1) @@ -154467,7 +152063,7 @@ end if io + n * isz > iv.length or vo + n * elem > vv.length then return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") end - -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + -- sparse values are tightly packed (matrices: padded columns) local vals, valOff = vv.buf, vv.offset + vo if cols > 1 and colBytes ~= colStride then vals = buffer.create(n * elem) @@ -154489,7 +152085,6 @@ end local k = int(v) return (k and{accessors[k + 1] }or{nil })[1] end - -- images (kept encoded), samplers, textures local images= {} for i, im in __iter(arr(doc.images)) do if type(im) ~= "table" then @@ -154575,7 +152170,6 @@ local k = int(v) end table.insert(scene.textures, tex) end - -- materials local function texRef(info) if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then return nil @@ -154587,7 +152181,7 @@ if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures end return r end - -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + -- a textureInfo: a table with an index, under a key ending in Texture local function convertExt(v) if type(v) ~= "table" then return v @@ -154637,7 +152231,6 @@ if type(v) ~= "table" then mat.extras = kept table.insert(scene.materials, mat) end - -- meshes for i, m in __iter(arr(doc.meshes)) do if type(m) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) @@ -154706,7 +152299,6 @@ return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then return nil, Err.new(Err.CORRUPT, "bad indices accessor") end - -- indices must reference existing vertices local get = (Types.Scene.reader(ind ) ) for q = 0, ind.count - 1 do if get(q, 0) >= count then @@ -154735,7 +152327,6 @@ end end table.insert(scene.meshes, mesh) end - -- cameras, lights for _, c in __iter(arr(doc.cameras)) do if type(c) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad camera") @@ -154763,7 +152354,6 @@ end }) end end - -- nodes local nodes = arr(doc.nodes) for i, n in __iter(nodes) do if type(n) ~= "table" then @@ -154819,7 +152409,6 @@ end p = parent[p] end end - -- skins for _, s in __iter(arr(doc.skins)) do if type(s) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad skin") @@ -154833,7 +152422,6 @@ end end table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = (int(s.skeleton) and s.skeleton < #scene.nodes and((s.skeleton + 1 ))or(nil ))}) end - -- animations for _, a in __iter(arr(doc.animations)) do if type(a) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad animation") @@ -154870,7 +152458,6 @@ end end table.insert(scene.animations, anim) end - -- scenes local scenes = arr(doc.scenes) local list = {} for _, s in __iter(scenes) do @@ -154892,7 +152479,6 @@ end end end end - -- root extensions other than the lights, asset info local rootExt = nil if type(doc.extensions) == "table" then for k, v in __iter(doc.extensions) do @@ -154920,13 +152506,8 @@ return Read end __FILES["model/gltf/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex --- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), --- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), --- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, --- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their --- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first --- for concave faces). +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. Vertex attributes 4-byte aligned per +-- element, matrix columns padded, f64 / i32 data converted (glTF has neither), POSITION and animation input min / max. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -155010,7 +152591,6 @@ local pad = (4 - bin:tell() % 4) % 4 return #views - 1 end - -- accessor(acc, usage, attribute?) -> the glTF index (0-based) local function accessor(acc, usage, attribute) local known = accIndex[acc] if known then @@ -155069,7 +152649,6 @@ local known = accIndex[acc] return 0 end if attribute == "POSITION" or usage == "input" then - -- min / max of the raw component values local raw = Types.Scene.accessor(a.data, a.type == "unorm8" and"u8" or(a.type == "unorm16" and"u16" or(a.type == "snorm8" and"i8" or(a.type == "snorm16" and"i16" or a.type))), comps, a.count) local get = (Types.Scene.reader(raw) ) local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) @@ -155094,7 +152673,6 @@ local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) return index end - -- extras.gltf -> extras / extensions fields of a glTF object local function restore(g, extras) local saved = type(extras) == "table" and extras.gltf if type(saved) ~= "table" then @@ -155114,7 +152692,6 @@ local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) end end - -- images, samplers, textures local images= {} local imageOut= {} local imageIndex= {} @@ -155133,7 +152710,7 @@ local key= data or uri im.bufferView = view(data, buffer.len(data), nil, nil) im.mimeType = mime or "image/png" elseif embedImages then - im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI / a file name by the caller im.mimeType = mime table.insert(imageOut, { data = data, mime = mime, name = im.uri }) else @@ -155237,7 +152814,6 @@ if type(v) ~= "table" then end return out end - -- materials local materials= {} for i, m in __iter(scene.materials or {}) do if type(m) ~= "table" then @@ -155291,7 +152867,6 @@ if type(v) ~= "table" then restore(g, m.extras) table.insert(materials, g) end - -- meshes local meshes= {} for i, mesh in __iter(scene.meshes or {}) do if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then @@ -155317,7 +152892,6 @@ if type(v) ~= "table" then local mode = p.mode or "triangles" local indices = p.indices if mode == "polygons" then - -- fan-triangulate local faces = p.faces local getf = faces and Types.Scene.reader(faces) local n = (indices and{indices.count }or{p.attributes.POSITION.count @@ -155380,7 +152954,6 @@ if type(v) ~= "table" then restore(g, mesh.extras) table.insert(meshes, g) end - -- cameras, lights local cameras= {} for _, c in __iter(scene.cameras or {}) do local g = object() @@ -155419,7 +152992,6 @@ if type(v) ~= "table" then end table.insert(lights, g) end - -- nodes local nodes= {} local nodeCount = #(scene.nodes or {}) for i, n in __iter(scene.nodes or {}) do @@ -155470,7 +153042,6 @@ if type(v) ~= "table" then restore(g, n.extras) table.insert(nodes, g) end - -- skins local skins= {} for _, s in __iter(scene.skins or {}) do local g = object() @@ -155491,7 +153062,6 @@ if type(v) ~= "table" then end table.insert(skins, g) end - -- animations local animations= {} for _, a in __iter(scene.animations or {}) do local g = object() @@ -155523,7 +153093,7 @@ if type(v) ~= "table" then if failure then return nil, failure end - -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + -- scenes: the original list (meta.gltf.scenes), else the roots local meta= (type(scene.meta) == "table" and{scene.meta }or{{} })[1] local mg = type(meta.gltf) == "table" and meta.gltf or {} local scenes = {} @@ -155540,7 +153110,6 @@ if type(v) ~= "table" then restore(g, s.extras) table.insert(scenes, g) end - -- the current roots replace the default scene's list local which = mg.scene or 1 if scenes[which] then scenes[which].nodes = {} @@ -155567,7 +153136,6 @@ if type(v) ~= "table" then asset.extras = mg.asset.extras end doc.asset = asset - -- root extensions kept from the source (variants, ...), the lights if type(mg.extensions) == "table" then doc.extensions = object() for k, v in __iter(mg.extensions) do @@ -155618,17 +153186,9 @@ return Write end __FILES["model/iqm"] = function() local __compat = __compat local type = __compat.type --!strict --- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / --- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). --- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as --- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as --- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _<name>), joints --- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels --- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in --- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's --- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). --- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and --- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). +-- model/iqm: Inter-Quake Model (IQM version 2; iqm.txt / iqm.h of Lee Salzman's IQM SDK, public domain; checked against +-- assimp). Supports: meshes, every vertex array format, joints / skin, poses + anims, bounds. IQM is z-up, clockwise. +-- Not supported: IQM version 1, adjacency and extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -155702,9 +153262,7 @@ return Iqm end __FILES["model/iqm/Read"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and --- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). --- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. Every header range is checked before it is read. local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -155735,7 +153293,7 @@ local s = bit32.band(h, 0x8000) ~= 0 and-1 or 1 return s * (1 + m / 1024) * 2 ^ (e - 15) end --- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +-- normalized: integer formats scaled to 0..1 / -1..1 local function values(b, at, format, n, normalized) local out = (table.create(n) ) local size = Read.SIZES[format] @@ -155780,7 +153338,6 @@ end local MIME= { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } --- scene(b, base, limit, opts) -> Scene | nil, message function Read.scene(b, base, limit, opts) local size = limit - base local H= {} @@ -155831,7 +153388,6 @@ if ofs >= #text then if H.num_comment > 0 then source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") end - -- vertex arrays (the whole model's vertices; meshes are ranges of them) local nv = H.num_vertexes local arrays= {} @@ -155850,7 +153406,6 @@ local arrays= {} local name = (kind and{kind }or{("_" .. ((typ >= 0x10 and{(str(typ - 0x10) )}or{(tostring(typ))})[1]) )})[1] table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) end - -- joints -> nodes + a skin local jointNodes= {} local skin= nil if H.num_joints > 0 then @@ -155869,7 +153424,7 @@ for k = 0, 9 do end jointNodes, skin = Rig.skeleton(scene, joints, "local") end - -- materials: one per distinct material string (IQM names its texture there) + -- materials: one per distinct material string (IQM tools name the texture there) local matOf= {} local function material(name) if name == "" then @@ -155888,7 +153443,6 @@ if name == "" then matOf[name] = #scene.materials return #scene.materials end - -- meshes for m = 0, H.num_meshes - 1 do local p = base + H.ofs_meshes + m * 24 local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) @@ -155945,7 +153499,7 @@ for v = 0, cv - 1 do if not attributes.POSITION then return nil, "no position array" end - -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + -- IQM's front faces are clockwise: corners 2 and 3 swap local ib = buffer.create(ct * 12) for k = 0, ct - 1 do local q = base + H.ofs_triangles + (ft + k) * 12 @@ -155966,7 +153520,7 @@ for v = 0, cv - 1 do table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + -- frames hold the masked pose channels (offset + value * scale), in pose order if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then local np = H.num_poses local poses= {} @@ -156063,16 +153617,8 @@ return Read end __FILES["model/iqm/Write"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines --- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights --- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins --- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse --- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world --- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are --- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), --- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. --- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). --- Plain code (the caller wraps it in pcall). +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). Blend weights are u8 summing to 255; the skeleton +-- is the union of the scene's skins, parents first; animations quantized per pose channel to 16 bits. local Types = __include("Types") local Bytes = __include("core/Bytes") local Mat4 = __include("codecs/model/Mat4") @@ -156084,7 +153630,6 @@ local Write = {} local Scene = Types.Scene -- ------------------------------------------------------------------------------------------------ scene walk --- world matrices (rest pose, or with a pose's overrides) and the parent of every node local function parents(scene) local parent= {} @@ -156134,7 +153679,6 @@ local w = world[i] end -- ------------------------------------------------------------------------------------------------ geometry --- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points local function triangles(prim) local mode = prim.mode or "triangles" local nv = prim.attributes.POSITION.count @@ -156207,7 +153751,7 @@ for v = 0, nv - 1 do return out end --- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +-- the 4 strongest, u8 weights summing to 255 local function influences(skin, jointIndex, joints, weights, v) local pairs_= {} for c = 1, 4 do @@ -156243,7 +153787,6 @@ return a[2] > b[2] return list end --- appends a flat influence list to the blend index / weight arrays (4 slots) local function push4(bi, bw, list) local n = #bi for c = 1, 4 do @@ -156258,7 +153801,6 @@ end function Write.iqm(scene, opts) local parent = parents(scene) local rest = worlds(scene, parent, nil) - -- the skeleton: every skin joint, parents first local isJoint= {} local ibmOf= {} for _, skin in __iter(scene.skins) do @@ -156276,9 +153818,9 @@ for k = 1, 16 do end end end - -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + -- IQM wants parents first local jointList= {} - local jointIndex= {} -- node -> 0-based joint + local jointIndex= {} local function add(n, depth) if jointIndex[n] or depth > #scene.nodes then return @@ -156335,7 +153877,6 @@ local p = jointParent(n) end return Mat4.decompose(m) end - -- the meshes local nodeOfMesh= {} local placed= {} local seen= {} @@ -156375,7 +153916,6 @@ local p = jointParent(n) local hasTC, hasN, hasTG, hasC = false, false, false, false local tris= {} local meshes= {} - -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds local skinOf= {} local nvTotal = 0 for _, pl in __iter(placed) do @@ -156456,7 +153996,7 @@ local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) else table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) end - -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + -- the 4 strongest, u8 weights summing to 255 local list if joints and weights and skinned then list = influences(skinned, jointIndex, joints, weights, v) @@ -156468,7 +154008,7 @@ if joints and weights and skinned then push4(BI, BW, list) skinOf[#skinOf + 1] = list end - -- triangles back to IQM's clockwise order + -- IQM's clockwise order local tfirst = math.floor(#tris / 3 ) for k = 1, #tri, 3 do table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) @@ -156492,7 +154032,6 @@ if joints and weights and skinned then if #meshes == 0 then return nil, "nothing to write: no triangle primitives" end - -- animation frames local frames= {} -- frames[f][joint] = 10 values local anims= {} local frameWorld= {} @@ -156502,7 +154041,6 @@ if joints and weights and skinned then if #keys > 0 then local rate = opts and opts.framerate if not rate then - -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second local dt = (#keys > 1 and((keys[2] - keys[1] ))or(0 )) local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 for k = 2, #keys do @@ -156539,7 +154077,6 @@ for j, n in __iter(jointList) do end end end - -- quantization per pose channel local masks, offsets, scales = {}, {}, {} local numChannels = 0 for j = 1, #jointList do @@ -156564,7 +154101,6 @@ for j, n in __iter(jointList) do end masks[j], offsets[j], scales[j] = mask, off, sc end - -- text local text = { "\0" } local textLen = 1 local textAt= { [""] = 0 } @@ -156591,7 +154127,6 @@ local hit = textAt[s] str(a.name) end local comment = opts and opts.comment - -- layout local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) local H= {} local function at() @@ -156613,8 +154148,7 @@ return w:tell() w:u32le(v) end end --- vertex arrays: headers, then data - + local arrs= { { typ = 0, format = 7, comps = 3, data = P } } if hasTC then table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) @@ -156712,7 +154246,6 @@ local arrs= { { typ = 0, format = 7, comps = 3, data = P } } while at() % 4 ~= 0 do w:u8(0) end - -- bounds of the skinned vertices per frame H.ofs_bounds = at() local skinM = (table.create(#jointList) ) for f, world in __iter(frameWorld) do @@ -156771,35 +154304,9 @@ return Write end __FILES["model/ldraw"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and --- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked --- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. --- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + --- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines --- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at --- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried --- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing --- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). --- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without --- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main --- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = --- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one --- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines --- = false drops them); no normals, no indices (each triangle has its own three vertices). --- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise --- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or --- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. --- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge --- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig --- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered --- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> --- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). --- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node --- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = --- false leaves it out (meta.up = nil, meta.source.up = "-y"). --- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. --- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta --- commands (ignored); BFC in model files' references (models place parts as certified). +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read; File Format spec 1.0.2 with the MPD, BFC and !COLOUR extensions +-- (ldraw.org). Supports: line types 0-5, sub-files, BFC, LDConfig colours. -Y up, 1 LDU = 0.4 mm (a root node turns +-- it). Not supported: writing; !TEXMAP and !DATA; LDCad / MLCad / LPub meta commands; BFC in model files' references. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -156852,7 +154359,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ldraw.decode(r, opts) local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, text, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) @@ -156864,8 +154370,6 @@ local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) end -- ------------------------------------------------------------------------------------------------ extras --- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, --- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added function Ldraw.colors(ldconfig) local t = Colors.builtin() if ldconfig then @@ -156878,9 +154382,8 @@ return Ldraw end __FILES["model/ldraw/Colors"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from --- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see --- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- model/ldraw/Colors: the LDraw colour table, parsed from !COLOUR lines. The built-in table is LDraw.org's LDConfig.ldr +-- (UPDATE 2025-05-20; CC BY 2.0, see licenses/LDRAW_COLOURS.txt), without the "0 !COLOUR " prefix and with MATERIAL cut -- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. local Colors = {} @@ -156889,7 +154392,7 @@ local Colors = {} local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } --- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +-- "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." function Colors.entry(rest) local words= {} for w in __iter(string.gmatch(rest, "%S+")) do @@ -156930,7 +154433,6 @@ local words= {} return code, { name = name, rgb = rgb , edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } end --- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added function Colors.parse(text, into) local t= into or {} for line in __iter(string.gmatch(text, "[^\n]+")) do @@ -157176,7 +154678,6 @@ Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 ]] local cache= nil --- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) function Colors.builtin() if not cache then local t= {} @@ -157199,15 +154700,14 @@ return Colors end __FILES["model/ldraw/Read"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command --- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into --- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/ldraw/Read: LDraw text -> Types.Scene. Sub-files are tried as written (backslashes as slashes), then lower +-- case, under "", "parts/", "p/", "parts/s/" and "models/"; faces are written counter-clockwise after the matrices' +-- mirroring. local Types = __include("Types") local Colors = __include("model/ldraw/Colors") local Read = {} --- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +-- k = 0 (a BFC state change), 1 (a reference: v = x y z a b c d e f g h i), 2..5 @@ -157252,7 +154752,6 @@ local function srgbToLinear(v) return (v <= 0.04045 and((v / 12.92 ))or((((v + 0.055) / 1.055) ^ 2.4 )))end --- parse(text, name) -> File (colour definitions go into colours as they are met) local function parse(text, name, colours, stats) local f= { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } local cmds = f.cmds @@ -157296,7 +154795,6 @@ local f= { name = name, key = norm(name), cmds = {}, certified = false, refs = 0 elseif w1 == "Author:" then f.author = rest elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then - -- (headers) elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) end @@ -157352,7 +154850,6 @@ local inv = invert return f end --- scene(text, opts) -> Scene | nil, message, kind function Read.scene(text, opts) local o= opts or {} local colours = Colors.builtin() @@ -157529,7 +155026,7 @@ return ((math.floor(v / s)) % 16) * 17 end end - -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + -- m is a 3x4 row-major matrix local function bake(f, m, colour, inv, certified, depth, stack, groups, order, direct) if failure then return @@ -157639,7 +155136,6 @@ local b = buffer.create(count * 12) return Types.Scene.accessor(b, "f32", 3, count) end - -- the mesh of a file baked at the identity (nil when it has no geometry) local meshOf= {} local function meshFor(f, colour, inv, direct) local key = f.key .. "|" .. colour .. "|" .. (inv and"i" or"") .. (direct and"d" or"") @@ -157781,21 +155277,9 @@ return Read end __FILES["model/lwo"] = function() --!strict --- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from --- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. --- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / --- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and --- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: --- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the --- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has --- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces --- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> --- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, --- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: --- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding --- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. --- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / --- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). +-- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against +-- assimp. Supports: layers, polygons, VMAP / VMAD, surfaces, clips. Left-handed: z negated, winding reversed. Not +-- supported: LWO3, envelopes, procedural / gradient textures, planar / cylindrical / spherical projections, smoothing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -157869,13 +155353,8 @@ return Lwo end __FILES["model/lwo/Build"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z --- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's --- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its --- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), --- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, --- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. --- Plain code (the caller wraps it in pcall). +-- model/lwo/Build: a parsed LightWave object -> Types.Scene. LightWave is left-handed (y up, clockwise front faces): z +-- is negated and the winding reversed, as assimp does. Vertices are split where a VMAD gives a corner its own value. local Types = __include("Types") local Parse = __include("model/lwo/Parse") @@ -157988,7 +155467,6 @@ if a.material ~= b.material then return groups end --- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners) local n = #corners local out = (table.create(n) ) @@ -158004,8 +155482,8 @@ end local function primitive(layer, g, attrs, morphs, triangulate) local pts, pivot = layer.pts, layer.pivot local vertOf= {} - local srcPoint= {} -- vertex (1-based) -> point - local srcPoly= {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local srcPoint= {} + local srcPoly= {} -- -1: none local indices= {} local faces= {} local madMaps= {} @@ -158074,7 +155552,6 @@ for k = 1, n do writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) end local attributes= { POSITION = Scene.accessor(pos, "f32", 3, nv) } - -- the value of map m for vertex v (1-based), or nil local function value(m, v) local f = srcPoly[v] if f >= 0 then @@ -158176,7 +155653,7 @@ local triangulate = not (opts and opts.triangulate == false) local scene = Scene.new() scene.meta.up = "y" scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } - -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + -- every TXUV map name, in order of first appearance, gets one TEXCOORD_n index local uvSets= {} local nuv = 0 for _, layer in __iter(m.layers) do @@ -158187,7 +155664,6 @@ local triangulate = not (opts and opts.triangulate == false) end end end - -- materials: one per surface, then one per tag without a surface, then a default one local texCache= {} local bySurfName= {} for i, surf in __iter(m.surfaces) do @@ -158229,7 +155705,6 @@ if tag ~= nil then end return default end - -- nodes and meshes local nodeOf= {} local layerOfNode= {} for _, layer in __iter(m.layers) do @@ -158304,7 +155779,7 @@ end end end end - -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + -- a parent link that would close a cycle is dropped local parentOf= {} for ni, layer in __iter(layerOfNode) do local pi = (layer.parent ~= nil and{nodeOf[layer.parent] }or{nil @@ -158340,17 +155815,9 @@ return Build end __FILES["model/lwo/Parse"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build --- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave --- 5.x), checked against what assimp's LWO importer reads (no code taken). --- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are --- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS --- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo --- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural --- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). --- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, --- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. --- Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/lwo/Parse: LightWave object chunks -> plain tables. From the LWO2 specification (LightWave 6 "Object Files", +-- Ernie Wright) and the LWOB one (LightWave 5.x), checked against assimp (no code taken). Several PNTS per layer: later +-- POLS / VMAP indices are relative to the latest. Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. local Bytes = __include("core/Bytes") local Chunks = __include("containers/Chunks") @@ -158420,7 +155887,7 @@ local MAP_KINDS= { } -- ------------------------------------------------------------------------------------------------ primitives --- S0: a NUL-terminated string padded to an even length +-- S0: NUL-terminated, padded to an even length local function s0(r) local start = r.pos local s = r:cstring() @@ -158430,7 +155897,7 @@ local start = r.pos return s end --- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +-- VX: 2 bytes, or 4 bytes after an 0xFF byte local function vx(r) if r:peekU8() == 0xFF then return r:u32be() - 0xFF000000 @@ -158443,7 +155910,7 @@ local s = r:string(4) return (string.gsub(s, " +$", "")) end --- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +-- LWO2 sub-chunks: 4-byte id, 2-byte size, padded to even local function subchunks(buf, p, e, f) while p + 6 <= e do local id = buffer.readstring(buf, p, 4) @@ -158474,7 +155941,6 @@ local n = math.floor(r:remaining() / 12 return nil end --- POLS (LWO2): returns nil or an error local function readPolys(r, layer, kind, ptBase, budget) local polys = layer.polys local npts = math.floor(#layer.pts / 3 @@ -158622,7 +156088,7 @@ end local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } local function readBlock(r, surf) - -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + -- IMAP / PROC / GRAD / SHDR header: ordinal string, header sub-chunks if r:remaining() < 6 then return end @@ -158805,7 +156271,6 @@ local function readClip(r, clips, refs) end -- ------------------------------------------------------------------------------------------------ the file --- parse(buf, from, limit, opts) -> Model | nil, message function Parse.model(buf, from, limit, maxCorners) local version = buffer.readstring(buf, from + 8, 4) local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) @@ -158857,7 +156322,7 @@ local version = buffer.readstring(buf, from + 8, 4) if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then err = readPolys(r, layer, kind, ptBase, budget) else - -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + -- PTAG / VMAD refer to the polygon numbering: keep it, skip the geometry local before = #layer.polys err = readPolys(r, layer, kind, ptBase, budget) model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before @@ -158893,19 +156358,9 @@ return Parse end __FILES["model/mca"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/mca: Minecraft Anvil region files (r.<x>.<z>.mca: 32 x 32 chunks), read-only. New code, from the Minecraft --- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads --- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over --- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, --- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). --- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks --- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with --- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its --- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, --- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header --- and one chunk's NBT without building voxels. --- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the --- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). +-- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, +-- LZ4 (lz4-java blocks, 24w04a+) and stored chunks, external .mcc chunks, every chunk layout back to pre-1.13. +-- Not supported: writing; custom (127) compression; LZ4 checksums; the separate 1.17+ entities/ region files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -158981,7 +156436,6 @@ local n = r.limit - r.base end -- ------------------------------------------------------------------------------------------------ decode --- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) function Mca.list(r) local n = r.limit - r.base if n < 8192 then @@ -159016,7 +156470,6 @@ if o.region then return nil, nil end --- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err local function payload(r, e, o) local p = r.base + e.sector * 4096 if p + 5 > r.limit then @@ -159069,7 +156522,6 @@ local p = r.base + e.sector * 4096 return out, comp end --- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) function Mca.chunk(r, x, z, opts) local o= opts or {} if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then @@ -159137,7 +156589,6 @@ local o= opts or {} end end end - -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, c in __iter(chunks) do lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) @@ -159167,7 +156618,7 @@ local o= opts or {} end end if lo[2] == math.huge then - lo[2], hi[2] = 0, -1 -- no blocks at all + lo[2], hi[2] = 0, -1 end if #chunks == 0 then lo, hi = { 0, 0, 0 }, { -1, -1, -1 } @@ -159177,7 +156628,6 @@ local o= opts or {} if n > (o.maxCells or 2 ^ 25) then return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) end - -- one palette for the grid (air first), each section copied in through a remap table local states = { "minecraft:air" } local index= { ["minecraft:air"] = 0 } local grid = buffer.create(n * 2) @@ -159250,11 +156700,9 @@ return Mca end __FILES["model/mca/Chunk"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three --- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least --- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = --- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through --- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +-- model/mca/Chunk: an Anvil chunk's blocks (Minecraft wiki "Chunk format"): 1.18+ sections[] block_states +-- (non-spanning, >= 4 bits); 1.13 - 1.17 Level.Sections[] Palette + BlockStates (spanning before DataVersion 2529 = +-- 20w17a); pre-1.13 Blocks / Add / Data nibble arrays. A section is 16 x 16 x 16 cells, x then z then y. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -159282,7 +156730,6 @@ local function list(v) return (type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) and{v }or{{} })[1]end --- a palette section (1.13+): states from the palette compounds, cells from the packed array local function paletted(y, palette, data, minBits, spanning) local states = (table.create(#palette) ) for i, c in __iter(palette) do @@ -159309,7 +156756,6 @@ for i, c in __iter(palette) do return { y = y, states = states, cells = cells }, nil end --- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk function Chunk.blocks(root) if type(root) ~= "table" or not Types.isObject(root) then return nil, "chunk NBT is not a compound" @@ -159387,17 +156833,15 @@ return Chunk end __FILES["model/mca/Lz4Block"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 --- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | --- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the --- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +-- model/mca/Lz4Block: lz4-java LZ4BlockOutputStream framing (Minecraft 24w04a+, compression type 4): "LZ4Block", token +-- (0x10 raw / 0x20 LZ4 | level), compressed and decompressed lengths, XXH32 (LE i32s; not verified), then the block; +-- blocks are independent and an empty block ends the stream. local Lz4 = __include("codecs/compress/Lz4") local Lz4Block = {} local MAGIC = "LZ4Block" --- decode(buf, offset, length, maxBytes) -> buffer | nil, message function Lz4Block.decode(b, offset, length, maxBytes) local p, e = offset, offset + length local parts, total = {}, 0 @@ -159459,17 +156903,9 @@ return Lz4Block end __FILES["model/md2"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the --- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. --- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, --- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), --- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored --- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not --- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one --- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture --- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. --- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. --- Not supported: the GL command list (the triangles carry the same geometry), writing. +-- model/md2: Quake II MD2 ("IDP2" v8), from qfiles.h dmdl_t and David Henry's "MD2 file format"; no code taken. +-- Supports: clockwise faces reversed, frames as morph targets, animations per frame-name group (10 fps), skin URIs. +-- Not supported: the GL command list, writing; Quake's normal table (not redistributable: normals are computed). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159509,7 +156945,6 @@ if r:remaining() < 68 then end -- ------------------------------------------------------------------------------------------------ decode --- group frame names by their name without trailing digits, in file order local function groups(names, fps) local out= {} for i, n in __iter(names) do @@ -159559,13 +156994,11 @@ return o >= 0 and n >= 0 and o + n <= size return nil, Err.new(Err.CORRUPT, "frame size too small", 16) end local b, base = r.buf, r.base - -- skins local skins= {} for i = 0, nSkins - 1 do local s = buffer.readstring(b, base + oSkins + i * 64, 64) table.insert(skins, (string.match(s, "^[^%z]*")) ) end - -- weld (xyz, st) pairs local key= {} local vx, vst= {}, {} local indices= {} @@ -159600,7 +157033,6 @@ return o >= 0 and n >= 0 and o + n <= size writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) end end - -- frames local frames= {} local normals= {} local names= {} @@ -159670,16 +157102,9 @@ return Md2 end __FILES["model/md3"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format --- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" --- notes (PhaethonH); no code taken. --- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame --- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left --- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all --- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes --- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). --- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. --- Not supported: writing. +-- model/md3: Quake III MD3 ("IDP3" v15), from qfiles.h md3Header_t / md3Surface_t and PhaethonH's "MD3 file format"; +-- no code taken. Supports: surfaces as primitives, positions in 1/64 units, lat / long normals, frames as morph +-- targets, tags as child nodes with channels. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159846,7 +157271,6 @@ for t = 0, nTris - 1 do table.insert(mesh.primitives, prim) so =so+ oEnd end - -- frames and tags local frameNames= {} for f = 0, nFrames - 1 do frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) @@ -159906,12 +157330,8 @@ return Md3 end __FILES["model/md5"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim --- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from --- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by --- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless --- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom --- units, z up. Not supported: writing, .md5camera. +-- model/md5: Doom 3 / Quake 4 MD5 (MD5Version 10 text): .md5mesh and .md5anim (model/md5/Read); a mesh loads +-- opts.anims, joints matched by name. Not supported: writing, .md5camera. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -159991,13 +157411,8 @@ return Md5 end __FILES["model/md5/Read"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: --- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive --- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed --- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: --- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at --- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding --- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +-- model/md5/Read: MD5Version 10 text, from modwiki "MD5 (file format)" and David Henry's "The MD5 Mesh and Animation +-- Formats"; no code taken. The bind pose is model space, the baseframe parent-relative. local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -160085,7 +157500,7 @@ expect(L, "(") return v end --- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +-- w = -sqrt(1 - x² - y² - z²) (w <= 0, as id's tools store it) local function quat(x, y, z) local t = 1 - x * x - y * y - z * z return { x, y, z, t < 0 and 0 or-math.sqrt(t) } @@ -160098,7 +157513,6 @@ local qx, qy, qz, qw = q[1], q[2], q[3], q[4] return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx) end -- ------------------------------------------------------------------------------------------------ md5mesh --- mesh(text, opts) -> Scene, joint node indices by name | nil, message @@ -160260,7 +157674,6 @@ local L= { text = text, pos = 1, err = nil } return scene, byName end -- ------------------------------------------------------------------------------------------------ md5anim --- anim(text) -> Anim | nil, message @@ -160388,7 +157801,6 @@ local L= { text = text, pos = 1, err = nil } return a, nil end --- addAnim(scene, nodes by joint name, anim, name) -> channels added function Read.addAnim(scene, byName, a, name) local nodes= {} local tracks= {} @@ -160408,7 +157820,6 @@ local nodes= {} return #scene.animations[ai].channels end --- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation function Read.animScene(a, name) local scene = Scene.new() scene.meta.up = "z" @@ -160433,12 +157844,8 @@ return Read end __FILES["model/mdl"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: --- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the --- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), --- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = --- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx --- files) is UNSUPPORTED. +-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins +-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -160519,16 +157926,9 @@ return Mdl end __FILES["model/mdl/HalfLife"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h --- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. --- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> --- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans --- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = --- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> --- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). --- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone --- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "<name>t.mdl" (pass it --- as opts.textures = that file's bytes). +-- model/mdl/HalfLife: GoldSrc studio models ("IDST" v10), from the Half-Life SDK studio.h and HLMV / Crowbar notes; no +-- code taken. Not supported: sequence groups in other files, bone controllers, hitboxes / attachments / events, blends +-- past the first. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Pixels = __include("codecs/image/Pixels") @@ -160547,7 +157947,6 @@ local function str(b, at, n) return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) end --- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message local function textures(b, base, size, maxPixels) local n, at = readi32(b, base + 180), readi32(b, base + 184) if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then @@ -160572,7 +157971,7 @@ local n, at = readi32(b, base + 180), readi32(b, base + 184) return out, names end --- one animation value: bone default + stored value * scale (frame f, 0-based) +-- bone default + stored value * scale local function animValue(b, at, limit, f) local p = at local k = f @@ -160597,7 +157996,6 @@ local p = at return nil end --- decode(b, base, size, opts) -> Scene | nil, message function HalfLife.decode(b, base, size, opts) if size < 244 then return nil, "truncated header" @@ -160626,7 +158024,6 @@ return o >= 0 and n >= 0 and o + n <= size local maxPixels = opts and opts.maxPixels or 2 ^ 24 local scene = Scene.new() scene.meta.up = "z" - -- bones local bones= {} local joints= {} for i = 0, nBones - 1 do @@ -160644,7 +158041,6 @@ return o >= 0 and n >= 0 and o + n <= size table.insert(scene.nodes, root) scene.roots[1] = 1 local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) - -- textures and skins local texSrc, texBase, texSize = b, base, size if nTex == 0 and opts and opts.textures then texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) @@ -160671,7 +158067,6 @@ for i, img in __iter(images) do skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 end end - -- body parts local totalVerts = 0 for part = 0, nParts - 1 do local po = base + oParts + part * 76 @@ -160693,8 +158088,7 @@ for i, img in __iter(images) do local tex = skinMap[skinref + 1] or (skinref + 1) local img = images[tex] local tw, th = (img and{img.width }or{1})[1], (img and{img.height }or{1 -})[1] -- triangle commands - local weld= {} +})[1] local weld= {} local corners= {} local indices= {} local p = base + oTri @@ -160805,7 +158199,6 @@ for i, img in __iter(images) do table.insert(root.children, #scene.nodes) end end - -- sequences local seqs= {} for s = 0, nSeq - 1 do local so = base + oSeq + s * 176 @@ -160861,11 +158254,8 @@ return HalfLife end __FILES["model/mdl/Quake"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et --- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. --- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; --- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per --- side); simple and grouped frames become morph targets with one animation per frame-name group. +-- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam +-- texture coordinates of back-facing triangles move half a skin width; a skin group shows its first picture. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") local Rig = __include("codecs/model/Rig") @@ -160881,7 +158271,6 @@ local function name16(b, at) return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) end --- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) function Quake.decode(b, base, size, palette, opts) if size < 84 then return nil, "truncated header" @@ -160903,7 +158292,6 @@ if size < 84 then local function need(n) return n >= 0 and p + n <= size end - -- skins local pal = (palette and{(Pixels.palette(palette, 0, 256) )}or{nil })[1] local skins= {} local px = sw * sh @@ -160941,7 +158329,6 @@ return n >= 0 and p + n <= size table.insert(skins, img) p =p+ count * px end - -- texture coordinates and triangles if not need(nVerts * 12 + nTris * 16) then return nil, "truncated vertices / triangles" end @@ -160979,7 +158366,7 @@ return n >= 0 and p + n <= size table.insert(indices, c[1]) end p =p+ nTris * 16 - -- frames: simple (type 0) or groups of simple frames + -- frames: simple (type 0) or groups local frameAt= {} local names= {} local fsize = 24 + nVerts * 4 @@ -161085,20 +158472,9 @@ return Quake end __FILES["model/ms3d"] = function() local __compat = __compat local type = __compat.type --!strict --- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of --- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested --- against (no code ported). --- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and --- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in --- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; --- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use --- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse --- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes --- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, --- the model comment / fps / frames / joint size in meta.source. meta.up = "y". --- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), --- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 --- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). +-- model/ms3d: MilkShape 3D 1.8 (.ms3d v3 / v4), from ms3dspec.h, tested against assimp's MS3D importer (no code +-- ported). Supports: groups, materials, joints, a skin, keyframes, comments and the extra blocks, read + write. Not +-- supported: scale keys (MilkShape has none), a second skin; writes at most 65535 vertices, 255 groups, 127 joints. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -161138,8 +158514,7 @@ local h = r:peek(14) end -- ------------------------------------------------------------------------------------------------ decode -function Ms3d.decode(r, opts) -- the scene builder is plain (not native) code: a bug there must not escape as an error - +function Ms3d.decode(r, opts) local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) @@ -161169,17 +158544,9 @@ return Ms3d end __FILES["model/ms3d/Read"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h --- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a --- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess --- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and --- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds --- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), --- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), --- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). --- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices --- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + --- key positions). Never throws on bad data: returns nil, message, offset. +-- model/ms3d/Read: the ms3dspec.h layout: vertices, triangles, groups, materials (shininess 0..128), the animation +-- header, joints (local Euler XYZ radians, keys in seconds relative to the rest pose), then the sub-versioned comments, +-- vertex extras (weights in percent, subversion 1-3), joint extras (colours) and model extras. Never throws. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -161225,7 +158592,6 @@ local function euler(x, y, z) return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) end -- ------------------------------------------------------------------------------------------------ parse --- scene(b, base, limit, opts) -> Scene | nil, message, offset @@ -161247,7 +158613,6 @@ return p + n <= limit end p =p+ 14 local maxV = opts and opts.maxVertices or 2 ^ 20 - -- vertices if not need(2) then return nil, "truncated vertex count", p end @@ -161262,7 +158627,6 @@ return p + n <= limit verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } end p =p+ nv * 15 - -- triangles if not need(2) then return nil, "truncated triangle count", p end @@ -161276,7 +158640,6 @@ return p + n <= limit end local triAt = p p =p+ nt * 70 - -- groups if not need(2) then return nil, "truncated group count", p end @@ -161305,7 +158668,6 @@ return p + n <= limit p =p+ 1 table.insert(groups, g) end - -- materials if not need(2) then return nil, "truncated material count", p end @@ -161324,7 +158686,7 @@ return p + n <= limit }) end p =p+ nm * 361 - -- animation header and joints (version 3 files may end here) + -- version 3 files may end here local fps, current, frames = 24, 0, 0 local joints= {} if need(12) then @@ -161359,7 +158721,6 @@ return p + n <= limit table.insert(joints, j) end end - -- sub-versioned blocks local source= { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } local function comments(list) if not need(4) then @@ -161452,8 +158813,7 @@ end function Read.build(b, triAt, verts, groups, mats, joints, source) local scene = S.new() scene.meta.up = "y" - scene.meta.source = source -- materials, textures - + scene.meta.source = source for _, m in __iter(mats) do local mat = S.material(m.name) local d = m.diffuse @@ -161475,7 +158835,6 @@ for _, m in __iter(mats) do } table.insert(scene.materials, mat) end - -- joints: nodes, rest pose, skin local nj = #joints local jointNode= {} local byName= {} @@ -161525,7 +158884,6 @@ for _, m in __iter(mats) do end scene.skins[1] = { joints = list, inverseBindMatrices = ibm } end - -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner local nv = #verts for gi, g in __iter(groups) do local remap= {} @@ -161535,7 +158893,6 @@ for _, m in __iter(mats) do local count = 0 for _, ti in __iter(g.tris) do local __DARKLUA_CONTINUE_21=false repeat local q = triAt + ti * 70 - -- a triangle with an out-of-range vertex is dropped if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then __DARKLUA_CONTINUE_21=true break end @@ -161552,7 +158909,6 @@ __DARKLUA_CONTINUE_21=true break table.move(v.pos, 1, 3, o * 3 + 1, P) N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) - -- influences: the valid bones, weights normalized local sum = 0 for c = 1, 4 do if v.bones[c] >= 0 then @@ -161599,7 +158955,6 @@ __DARKLUA_CONTINUE_21=true until true if not __DARKLUA_CONTINUE_21 then break en table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- the animation: rest * key rotations, rest + key positions local channels= {} for i, j in __iter(joints) do if #j.rotKeys > 0 then @@ -161635,15 +158990,8 @@ return Read end __FILES["model/ms3d/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, --- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first --- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); --- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each --- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's --- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: --- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and --- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), --- joint colours and model extras are written in their sub-versioned blocks. +-- model/ms3d/Write: Scene -> MilkShape 3D v4: a group per placed primitive, the first skin's joints (rest pose from +-- the inverse bind matrices, keys relative to it), vertex extras subversion 2 (weights in percent). local Bytes = __include("core/Bytes") local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") @@ -161690,7 +159038,6 @@ local t= { world = {}, parent = {}, order = {} } return t end -- ------------------------------------------------------------------------------------------------ joints --- the rigid part (rotation and translation) of a matrix @@ -161699,8 +159046,6 @@ local t, r = Mat4.decompose(m) return Mat4.compose(t, r, nil) end --- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; --- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices local function joints(scene, tr) local skin = scene.skins[1] local anim = scene.animations[1] @@ -161721,7 +159066,6 @@ local skin = scene.skins[1] table.insert(chans[ch.node], ch) end end - -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix local B = S.IDENTITY local IBM= (skin and skin.inverseBindMatrices and{(S.reader(skin.inverseBindMatrices) )}or{nil })[1] if skin and IBM and tr.world[skin.joints[1] ] then @@ -161740,8 +159084,7 @@ __DARKLUA_CONTINUE_7=true break while p ~= 0 and byNode[p] == nil do p = tr.parent[p] end - -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the - -- joint and its joint parent (C) carry over to the keys + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world local invP = (p ~= 0 and{Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() }or{(Mat4.identity() )})[1] local gp = tr.parent[ni] local C = S.mul(invP, (gp ~= 0 and{tr.world[gp] }or{S.IDENTITY})[1]) @@ -161789,7 +159132,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end return out, bySkin, byNode, B end -- ------------------------------------------------------------------------------------------------ geometry --- every placed primitive as a group: vertices, triangles; or nil, message @@ -161811,7 +159153,6 @@ return false __DARKLUA_CONTINUE_12=true break end local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil - -- a rigid mesh follows its nearest joint local rigid = -1 if not skinned then local p = pl.node @@ -161893,7 +159234,6 @@ return a[2] > b[2] b, c = c, b end local t= { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = (saved and{saved[f + 1] }or{1})[1], group = gi } - -- the face normal for primitives without normals local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z @@ -161979,7 +159319,6 @@ local o= opts or {} end w:i8(g.material % 256) end - -- materials w:u16le(#scene.materials) local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" for i, m in __iter(scene.materials) do @@ -162011,7 +159350,6 @@ local bc = m.baseColor or { 1, 1, 1, 1 } fixedString(w, file, 128) fixedString(w, msg(x.alphamap), 128) end - -- the animation header and joints local fps = o.fps or ((fromMs3d and type(src.fps) == "number" and src.fps > 0 and{src.fps }or{24})[1]) local last = 0 for _, j in __iter(js) do @@ -162048,7 +159386,6 @@ local bc = m.baseColor or { 1, 1, 1, 1 } end end end - -- comments w:u32le(1) local function comments(list, get) local found = {} @@ -162101,7 +159438,6 @@ local x= scene.nodes[j.node].extras end w:u32le(0) end - -- joint colours, model extras w:u32le(1) for _, j in __iter(js) do local x= scene.nodes[j.node].extras @@ -162123,19 +159459,9 @@ return Write end __FILES["model/obj"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp --- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form --- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR --- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line --- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", --- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false --- keeps OBJ's). --- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. --- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. --- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups --- (s: kept per node in extras.obj.smoothing, not used to compute normals). --- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to --- opts.files[<name>.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. +-- model/obj: Wavefront OBJ + MTL (Paul Bourke's specs, as Blender / Maya / assimp write them). Supports: v (with +-- "v x y z r g b"), vt, vn, f in every index form, l, p, o / g, usemtl / mtllib, continuations; TEXCOORD_0 flipped to +-- top-left. Not supported: free-form geometry (curv, surf: skipped), smoothing groups (kept in extras.obj.smoothing). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -162270,7 +159596,6 @@ local s = section() end return p end - -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil local function corner(tok) local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") local vi = tonumber(a) @@ -162304,7 +159629,6 @@ local __DARKLUA_CONTINUE_1=false repeat local e = string.find(text, "\n", pos, local line = string.sub(text, pos, e - 1) pos = e + 1 lineNo =lineNo+ 1 - -- continuation lines while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do line = string.gsub(line, "\\\r?$", " ") local e2 = string.find(text, "\n", pos, true) or (len + 1) @@ -162390,7 +159714,6 @@ local hash = string.find(rest, "#", 1, true) end end if mode == "triangles" and k > 3 then - -- fan: rewrite the k corners as (k - 2) triangles local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 2, k - 1 do @@ -162400,7 +159723,6 @@ local hash = string.find(rest, "#", 1, true) end end elseif mode == "lines" then - -- a polyline -> segments local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 1, k - 1 do @@ -162433,7 +159755,6 @@ local hash = string.find(rest, "#", 1, true) skipped =skipped+ 1 end __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end - -- materials local scene = Types.Scene.new() local matIndex= {} local texIndex= {} @@ -162478,7 +159799,7 @@ local file = string.gsub(map.file, "\\", "/") end end end - -- materials named by usemtl but not defined anywhere: a default one with the name + -- usemtl of an undefined material: a default one with that name for _, s in __iter(sections) do for _, p in __iter(s.prims) do if p.material and not matIndex[p.material] then @@ -162488,7 +159809,6 @@ local file = string.gsub(map.file, "\\", "/") end end end - -- vertices: one per distinct (v, vt, vn) in each primitive local f32 = buffer.writef32 local KT, KN = nt + 1, nn + 1 local numericKeys = np * KT * KN < 2 ^ 52 @@ -162558,7 +159878,6 @@ local n = #p.cv end return out end - -- nodes: objects at the root, their groups as children; without objects every group is a root local objectNode= {} for _, s in __iter(sections) do if #s.prims > 0 then @@ -162587,7 +159906,6 @@ local n = #p.cv objectNode[s.object] = #scene.nodes table.insert(scene.roots, #scene.nodes) elseif hasObjects and s.object and objectNode[s.object] then - -- the object's own faces after its groups: a child too table.insert(scene.nodes, node) table.insert(scene.nodes[objectNode[s.object] ].children, #scene.nodes) else @@ -162612,7 +159930,6 @@ local n = #p.cv end -- ------------------------------------------------------------------------------------------------ encode --- the shortest decimal that reads back as the same f32 local probe = buffer.create(4) local function f32str(v) if v ~= v or v == math.huge or v == -math.huge then @@ -162651,7 +159968,6 @@ if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "tabl local placed = Types.Scene.flatten(scene) local out = { "# written by rosetta" } local mats = scene.materials or {} - -- material names (unique), texture file names local names= {} local used= {} for i, m in __iter(mats) do @@ -162719,7 +160035,6 @@ __DARKLUA_CONTINUE_22=true break return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") end end - -- the normal matrix (inverse transpose) for baked normals local nm= nil if Nr and not ident then local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] @@ -162771,7 +160086,6 @@ local s = tostring(nv + i + 1) end return s end - -- the corner list local ind = prim.indices local I= (ind and{(Types.Scene.reader(ind) )}or{nil })[1] local count = (ind and{ind.count }or{n @@ -162867,7 +160181,6 @@ __DARKLUA_CONTINUE_22=true until true if not __DARKLUA_CONTINUE_22 then break en end -- ------------------------------------------------------------------------------------------------ extras --- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) function Obj.encodeMtl(scene, opts) if type(scene) ~= "table" or type(scene.materials) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") @@ -162888,10 +160201,8 @@ return Obj end __FILES["model/obj/Mtl"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, --- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping --- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the --- reverse (from extras.obj when present, else from the PBR fields). +-- model/obj/Mtl: Wavefront .mtl (Paul Bourke's MTL spec + the PBR extension: Pr, Pm, Ps, Pc, Pcr, aniso, anisor, Ke, +-- map_Pr, map_Pm, map_Ke, norm); Phong values are kept in extras.obj. local Types = __include("Types") local Mtl = {} @@ -162924,7 +160235,6 @@ local opts= {} end end else - -- -o / -s / -t: up to three numbers while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do table.insert(vals, args[i]) i =i+ 1 @@ -162937,7 +160247,6 @@ local opts= {} return { file = file, options = opts } end --- parse(text) -> { Entry } in file order function Mtl.parse(text) local out= {} local cur= nil @@ -162985,7 +160294,6 @@ local ext = string.match(file, "%.([%w]+)$") return (ext and{MIME[string.lower(ext)] }or{nil })[1]end --- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map function Mtl.toMaterial(e, texture) local m = Types.Scene.material(e.name) local v = e.values @@ -163033,7 +160341,6 @@ local map = e.maps[key] if m.emissiveTexture and not ke then m.emissive = { 1, 1, 1 } end - -- everything else as it was, for the writer and for Phong renderers local extra= {} for k, vals in __iter(v) do extra[k] = vals @@ -163060,7 +160367,6 @@ if v == math.floor(v) and math.abs(v) < 1e15 then end Mtl.num = num --- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. function Mtl.write(materials, names, textureFile) local out = { "# written by rosetta" } for i, m in __iter(materials) do @@ -163079,7 +160385,6 @@ local out = { "# written by rosetta" } end order = table.clone(saved.order or {}) end - -- the PBR fields win over the saved Phong values they map to local bc = m.baseColor or { 1, 1, 1, 1 } values.Kd = { bc[1], bc[2], bc[3] } if (bc[4] or 1) < 1 or values.d then @@ -163124,7 +160429,6 @@ local out = { "# written by rosetta" } setMap("norm", m.normalTexture) end setMap("map_ORM", m.metallicRoughnessTexture) - -- the saved order first, then the rest sorted local keys = {} local seen = {} for _, k in __iter(order) do @@ -163184,23 +160488,9 @@ return Mtl end __FILES["model/off"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description --- (geomview.org/docs/html/OFF.html). --- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the --- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; --- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 --- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). --- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; --- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are --- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or --- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single --- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". --- meta.source = { format, keyword, vertices, faces, edges }. --- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes --- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons --- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are --- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF --- (UNSUPPORTED). +-- model/off: Geomview OFF text (geomview.org/docs/html/OFF.html), read + write. Supports: [ST][C][N]OFF, face colours +-- (prim.extras.faceColors), n-gons (fan-triangulated or "polygons"), point clouds; floats as %.9g (f32-exact). +-- Not supported: 4OFF / nOFF, binary OFF; colormap-index face colours are ignored. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -163237,7 +160527,7 @@ local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writ -- ------------------------------------------------------------------------------------------------ sniff function Off.sniff(r) local head = r:peek(512) - for _ = 1, 16 do -- leading comment lines + for _ = 1, 16 do local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") if not rest then break @@ -163251,7 +160541,7 @@ local head = r:peek(512) return 0 end -- ------------------------------------------------------------------------------------------------ decode --- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +-- unorm8 when every value is an integer and some value is above 1, else f32 @@ -163259,7 +160549,6 @@ local function colorType(c) return not c.float and c.max > 1 and"unorm8" or"f32" end --- the colour accessor for count entries of 4 values (nan = absent: opaque white) local function colorAccessor(c, count) local t = colorType(c) local buf = buffer.create(count * (t == "unorm8" and 4 or 16)) @@ -163294,7 +160583,7 @@ table.insert(vals, v) c.max = v end else - table.insert(vals, 0 / 0) -- absent: full (opaque white) + table.insert(vals, 0 / 0) end end end @@ -163307,7 +160596,6 @@ local triangulate = true local maxVertices = opts and opts.maxVertices or 2 ^ 24 local maxFaces = opts and opts.maxFaces or 2 ^ 25 local text = buffer.readstring(r.buf, r.base, r.limit - r.base) - -- the next non-empty line's tokens (comments stripped) local at = 1 local lineNo = 0 local function line() @@ -163373,7 +160661,6 @@ if head[2] == "BINARY" then if nf > maxFaces then return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) end - -- every vertex / face line takes at least 6 / 2 bytes if nv * 6 + nf * 2 > #text - at + 2 then return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") end @@ -163458,7 +160745,6 @@ if head[2] == "BINARY" then addColor(fcol, t, 1, 0) end end - -- the primitive local attrs= { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } if nrm then attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) @@ -163552,7 +160838,6 @@ writef32(scratch, 0, v) return string.format("%.9g", v) end --- a colour attribute's 4 components of entry i (0-based) as text local function colorText(a, vals, comps, i) local out = table.create(4) for c = 1, 4 do @@ -163614,7 +160899,6 @@ return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == end table.insert(out, s) end - -- face colours of a single primitive (per file face, or through faceOfTriangle) local fc= nil local fcMap= nil if wantC and #m.parts == 1 and nf > 0 then @@ -163666,26 +160950,9 @@ return Off end __FILES["model/ply"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, --- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). --- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> --- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u --- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> --- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's --- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are --- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are --- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", --- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face --- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after --- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, --- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments --- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and --- types. meta.source = { format, encoding, vertices, faces }. --- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, --- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces --- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when --- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. --- Not supported: list properties in the vertex element (UNSUPPORTED). +-- model/ply: Stanford PLY (Greg Turk 1994; paulbourke.net/dataformats/ply, rply / plyfile behaviour), ascii and +-- binary either endian, read + write. Supports: every property type, faces (fan-triangulated or "polygons"), point +-- clouds; other elements, comments, obj_info and property order round-trip. Not supported: vertex list properties. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -163782,7 +161049,6 @@ local b, base, size = r.buf, r.base, r.limit - r.base if first then first = false -- "ply" elseif kw == nil then - -- blank line elseif kw == "end_header" then h.dataStart = base + at - 1 break @@ -163841,7 +161107,6 @@ else end return h, nil end --- the reading plan of one element: per property, where its values go @@ -163880,7 +161145,6 @@ local np = #e.props return pl end --- unset scalar destinations get their own native buffer local function ownBuffers(e, pl) for k, p in __iter(e.props) do if not p.list and pl.dst[k] == nil then @@ -163889,7 +161153,6 @@ local function ownBuffers(e, pl) end end --- read one element's rows (binary) into the plan; returns the next offset or nil, Err local function readBinary(r, p, e, pl, be) local b, limit, n, np = r.buf, r.limit, e.count, #e.props local hasList, rowSize = false, 0 @@ -163934,7 +161197,6 @@ local b, limit, n, np = r.buf, r.limit, e.count, #e.props return q, nil end --- a token as a value of type code, or nil local function value(tok, code) if tok == nil then return nil @@ -163950,7 +161212,6 @@ if tok == nil then return v end --- read one element's rows (ascii) from the token stream local function readAscii(nextTok, e, pl) ownBuffers(e, pl) local n = e.count @@ -164019,7 +161280,6 @@ for k, p in __iter(e.props) do return nil end --- vertex element -> attributes: sets the plan's destinations, returns the attribute table local function planVertex(e, pl) local nv = e.count local attrs= {} @@ -164029,7 +161289,6 @@ local nv = e.count return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") end end - -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional local function group(attr, names, required, ok, comps, fillValue) local ks= {} local codes = {} @@ -164075,7 +161334,6 @@ return 7 end group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) - -- colours: one type class for all channels do local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") if rk and gk and bk then @@ -164114,7 +161372,6 @@ return 7 return attrs, nil end --- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle local function fan(sizes, corners, nf) local nt = 0 for f = 0, nf - 1 do @@ -164180,7 +161437,6 @@ for i, e in __iter(h.elems) do end if ascii then local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) - -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating local need = 0 for _, e in __iter(h.elems) do need =need+ e.count * #e.props @@ -164194,7 +161450,6 @@ end local attrs= {} local p = h.dataStart if not ascii then - -- every row takes at least its scalar sizes and list counts: bound the counts before allocating local need = 0 for _, e in __iter(h.elems) do local row = 0 @@ -164233,7 +161488,6 @@ end p = q end end - -- the primitive local prim= { attributes = attrs, mode = "points" } local nf = 0 local extras= {} @@ -164297,7 +161551,6 @@ end if next(extras) then prim.extras = extras end - -- raw elements, element order, property order local elements= {} local order= {} for i, e in __iter(h.elems) do @@ -164328,7 +161581,6 @@ end return scene, nil end -- ------------------------------------------------------------------------------------------------ encode --- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) @@ -164337,7 +161589,6 @@ local function keep(name) return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" end --- the spelling `want` from the source file when it means the same type as code, else the classic name local function spell(want, code) if want and CODES[want] == code then return want @@ -164355,7 +161606,6 @@ local rg = RANGE[code] end return v end --- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer @@ -164429,7 +161679,6 @@ local s = col.sizes[i + 1] w.pos = o end --- numbers of a raw element column (buffer of a ply type) local function bufNumbers(b, code, count) if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then return nil @@ -164441,7 +161690,6 @@ for i = 0, count - 1 do return out end --- the list count type for a maximum count local function countCodeFor(maxCount) return maxCount <= 255 and 2 or(maxCount <= 65535 and 4 or 6 )end @@ -164458,7 +161706,6 @@ local o= opts or {} end local meta= (type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" and{scene.meta.ply }or{{} })[1] local nv = m.count - -- source property spellings / order local srcType= {} local srcOrder= {} if type(meta.vertexProperties) == "table" then @@ -164489,7 +161736,6 @@ return CODES[srcType[name] or ""] == 8 and 8 or 7 if C then local code = C.raw and C.type == "unorm8" and 2 or(C.raw and C.type == "unorm16" and 4 or 7 ) if C.raw and code == 7 then - -- another normalized type: as floats local vals = table.create(#C.values) local scale = C.type == "snorm8" and 127 or 32767 for i, v in __iter(C.values) do @@ -164555,7 +161801,6 @@ for i, nm in __iter({ "red", "green", "blue" }) do end end end - -- the source order first (stable for the rest) local rank= {} for i, c in __iter(cols) do rank[c] = (srcOrder[c.name] or (1000000 + i)) @@ -164563,7 +161808,6 @@ for i, nm in __iter({ "red", "green", "blue" }) do table.sort(cols, function(a, b) return rank[a] < rank[b] end) - -- faces local faceRows= nil local nf = 0 if m.sizes then @@ -164596,7 +161840,6 @@ nf = #sizes local rows= { { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, } - -- per-face data of a single primitive if #m.parts == 1 then local ex = m.parts[1].prim.extras local fot= nil @@ -164651,7 +161894,6 @@ for i = 1, nf do end end end - -- the source order, then the rest by name local placed= { [idxName] = true } local ordered= {} for _, fp in __iter(fprops) do @@ -164681,8 +161923,7 @@ for i = 1, nf do end faceRows = rows end --- raw elements - + local raws= {} local rawOrder= {} if type(meta.elements) == "table" then @@ -164724,7 +161965,6 @@ __DARKLUA_CONTINUE_67=true break end __DARKLUA_CONTINUE_67=true until true if not __DARKLUA_CONTINUE_67 then break end end end - -- element order: the source's, then vertex, face, the rest local order= {} local seen= {} local function want(name) @@ -164748,7 +161988,6 @@ __DARKLUA_CONTINUE_67=true until true if not __DARKLUA_CONTINUE_67 then break en for _, name in __iter(rawOrder) do want(name) end - -- header local vrows= {} for _, c in __iter(cols) do table.insert(vrows, { kind = "s" , col = c }) @@ -164818,11 +162057,8 @@ __FILES["model/ply/Binary"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, --- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of --- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the --- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list --- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +-- model/ply/Binary: PLY element data loops; type codes 1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, 7 f32, 8 f64, either +-- byte order. Never throws: the caller bounds every row first. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64 = buffer.readf32, buffer.readf64 local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 @@ -164839,7 +162075,6 @@ local function swap16(v) return rshift(v, 8) + band(v, 255) * 256 end --- rd(b, q, code, be) -> the value at q local function rd(b, q, code, be) if not be then if code == 7 then @@ -164880,7 +162115,6 @@ if not be then end Binary.rd = rd --- wr(d, o, code, v): v as code, little endian local function wr(d, o, code, v) if code == 7 then writef32(d, o, v) @@ -164902,7 +162136,6 @@ local function wr(d, o, code, v) end Binary.wr = wr --- put(d, o, code, v, be): v as code in either byte order (the writer) function Binary.put(d, o, code, v, be) if not be or code <= 2 then wr(d, o, code, v) @@ -164919,7 +162152,6 @@ function Binary.put(d, o, code, v, be) end end --- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p function Binary.fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode) for k = 1, np do local sc, dc, d = code[k], dCode[k], dst[k] @@ -164952,8 +162184,6 @@ function Binary.fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride end end --- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, --- or -1, message (truncated rows, a negative / fractional count) function Binary.scan(b, p, limit, n, np, code, isList, countCode, be) local totals = table.create(np, 0) local q = p @@ -164985,10 +162215,6 @@ local totals = table.create(np, 0) return q, totals end --- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. --- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their --- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows --- must have passed scan() with the same arguments. function Binary.rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) local at = table.create(np, 0) local q = p @@ -165030,19 +162256,9 @@ return Binary end __FILES["model/pmx"] = function() --!strict --- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD --- format, as documented by the MMD community). New code, no third-party code. --- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / --- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / --- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one --- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, --- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon --- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; --- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), --- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras --- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the --- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). --- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. +-- model/pmx: MikuMikuDance PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (MMD community notes); no +-- third-party code. Supports: every deform type, materials, bones and IK, vertex morphs as morph targets, the other +-- morphs, frames, rigid bodies and joints as extras. Not supported: writing, 2.1 soft bodies, VMD / VPD. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -165109,13 +162325,8 @@ return Pmx end __FILES["model/pmx/Build"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, --- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed --- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with --- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as --- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex --- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative --- translation each) and one skin with translation-only inverse bind matrices. +-- model/pmx/Build: the PMX / PMD model table to a Scene. MMD is left-handed (y up, x right, z forward): z is negated +-- and every winding reversed; UVs are already top-left. local Types = __include("Types") local Build = {} @@ -165127,7 +162338,6 @@ local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } --- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve local function fetcher(opts) return function(uri) if not opts then @@ -165150,7 +162360,6 @@ local function lh(v) return v and{ v[1], v[2], -v[3] } or nil end --- the scene index of a file texture index (0-based, -1 = none) local function texIndex(m, i) return (type(i) == "number" and i >= 0 and i < #m.textures and((i + 1 ))or(nil ))end @@ -165183,7 +162392,6 @@ local out = S.material(mat.name) return out end --- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root local function parents(bones) local nb = #bones local par = table.create(nb, 0) @@ -165208,7 +162416,6 @@ local nb = #bones return par end --- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered local function primitive(m, first, n, morphs, sdef) local map= {} local verts= {} @@ -165260,7 +162467,6 @@ local map= {} for a, acc in __iter(uvas) do buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) end - -- weights: invalid bones get weight 0, the rest is normalized local sum = 0 local js, ws = table.create(4, 0), table.create(4, 0) for c = 0, 3 do @@ -165327,7 +162533,6 @@ local scene = S.new() scene.materials[i] = material(m, mat) end - -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) local vmorphs, names, others = {}, {}, {} local wantMorphs = not (opts and opts.morphs == false) for _, mo in __iter(m.morphs) do @@ -165363,7 +162568,6 @@ local scene = S.new() first =first+ n end if first < m.indexCount then - -- faces no material covers table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) end mesh.extras = { targetNames = (#names > 0 and{names }or{nil})[1], pmx = #others > 0 and{ morphs = others } or nil } @@ -165372,7 +162576,6 @@ local scene = S.new() end scene.meshes[1] = mesh - -- nodes: 1 = the model, 2 = the mesh, then one per bone scene.nodes[1] = { name = m.name, children = { 2 } } scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } scene.roots[1] = 1 @@ -165418,13 +162621,8 @@ return Build end __FILES["model/pmx/Pmd"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as --- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community --- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, --- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to --- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in --- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in --- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +-- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are +-- Shift-JIS: kept when ASCII, else the English name, else the raw bytes (`nameSjis`). Never throws. local Bytes = __include("core/Bytes") local Pmd = {} @@ -165515,7 +162713,7 @@ if not r:match("Pmd") then r.pos =r.pos+ ni * 2 m.indexCount, m.indices = ni, ind - -- materials: 70 bytes each; texture names collected into the texture list + -- materials: 70 bytes each local nm = r:u32le() ok, e = counted(r, nm, 70, "materials") if r.err or not ok then @@ -165578,7 +162776,6 @@ if name == "" then m.bones[i] = b end - -- IK chains local nik = r:u16le() for _ = 1, nik do local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() @@ -165759,13 +162956,8 @@ return Pmd end __FILES["model/pmx/Read"] = function() local __compat = __compat local buffer, bit32, utf8, type = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type --!strict --- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that --- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. --- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices --- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, --- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, --- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). --- Never throws: returns nil, message[, kind]. +-- model/pmx/Read: PMX 2.0 / 2.1, from the specification notes that ship with PmxEditor; values as in the file +-- (left-handed, 0-based indices); 2.1 soft bodies are counted, not parsed. Never throws. local Bytes = __include("core/Bytes") local Text = __include("codecs/text/Text") @@ -165793,7 +162985,7 @@ local v= {} return v end --- a count field: i32 >= 0 and at most remaining / minSize records +-- a count field: i32 >= 0 local function count(r, minSize, what) local n = r:i32le() if r.err then @@ -165966,7 +163158,6 @@ local n = r:i32le() r.pos = p + ni * vsize m.indexCount, m.indices = ni, ind - -- textures local nt nt, e, k = count(r, 4, "textures") if not nt then @@ -165977,7 +163168,6 @@ local n = r:i32le() m.textures[i] = text() end - -- materials local nm nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") if not nm then @@ -166002,7 +163192,6 @@ local n = r:i32le() m.materials[i] = mat end - -- bones local nb nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") if not nb then @@ -166050,7 +163239,6 @@ local n = r:i32le() m.bones[i] = b end - -- morphs local nmo nmo, e, k = count(r, 8 + 2 + 4, "morphs") if not nmo then @@ -166071,7 +163259,7 @@ local n = r:i32le() return nil, e, k end if t == 1 then - -- vertex morphs: packed (index list + deltas), they become morph targets + -- vertex morphs: packed (index list + deltas) local vi, d = table.create(no), buffer.create(no * 12) for o = 1, no do local x = vidx() @@ -166172,17 +163360,9 @@ return Read end __FILES["model/qb"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the --- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA --- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 --- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. --- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as --- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view --- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and --- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). --- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; --- options default to the source file's settings. --- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. +-- model/qb: Qubicle Binary (.qb 1.1.0.0, minddesk.com "Qubicle Binary"), read + write. Supports: RGBA / BGRA, left- or +-- right-handed z, plain or RLE matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 per z slice), the alpha visibility mask, named +-- matrices with a position. Not supported: Qubicle Exchange (.qbt / .qbcl). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -166229,7 +163409,6 @@ if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then end -- ------------------------------------------------------------------------------------------------ decode --- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them local function indexed(v, colors, n) local count= {} for i = 0, n - 1 do @@ -166510,7 +163689,6 @@ if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then end return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 end - -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked local function value(x, y, z) local zz = (right and{z }or{(sz - 1 - z )})[1] local c = cellColor(v, x + sx * (y + sy * zz)) @@ -166575,17 +163753,9 @@ return Qb end __FILES["model/rbxm"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, "<roblox!"), read + write, to and from the instance --- tree of codecs/model/Rbx (an RbxTree, kind "rbxtree"; not a Scene: Roblox files hold instances, not meshes). --- Written from the rbx-dom format notes (docs/binary.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. --- Decode: the header, META (tree.metadata), SSTR (shared strings), INST (classes, referents, service flags), PROP (every --- property type of codecs/model/Rbx/Binary), PRNT (the hierarchy), END; chunk bodies raw, LZ4 or Zstandard. Unknown --- chunks are kept raw in tree.extra and written back; properties of unknown types become "Raw" values that are --- written back verbatim while the class keeps its instances. tree.place is true when the file marks services (rbxl). --- Encode: every instance depth first (referents 0..n-1), classes sorted by name, properties sorted by name, chunks --- LZ4-compressed (opts.compression = "none" writes them raw), SharedStrings deduplicated (MD5 keys). An instance --- without a property its class's other instances have gets the type's default (the format stores one value per --- instance). "XmlRaw" values (unknown XML types) are skipped. Not supported: writing Zstandard chunks. +-- model/rbxm: Roblox binary model / place (.rbxm / .rbxl, "<roblox!") to and from a codecs/model/Rbx RbxTree, from the +-- rbx-dom notes (docs/binary.md), checked against rojo 7.7 and lune 0.11. Supports: META, SSTR, INST, PROP, PRNT, END; +-- raw / LZ4 / Zstandard chunks; unknown chunks and types round-trip raw. Not supported: writing Zstandard chunks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -166626,7 +163796,7 @@ function Rbxm.sniff(r) return r:peek(14) == MAGIC and 1 or 0 end --- variant(r) -> "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +-- an INST chunk that marks services makes a place function Rbxm.variant(r) local b, p, e = r.buf, r.base + 32, r.limit if r:peek(14) ~= MAGIC then @@ -166656,7 +163826,6 @@ local b, p, e = r.buf, r.base + 32, r.limit return "rbxm" end -- ------------------------------------------------------------------------------------------------ decode --- a length-prefixed string at p of b (limit e): string, next | nil @@ -166868,7 +164037,6 @@ if clen == 0 then return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) end parented[child] = true - -- refuse cycles: the parent may not be a descendant of the child local up= parent while up do if up == child then @@ -166887,7 +164055,6 @@ if clen == 0 then if not ended then return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) end - -- instances PRNT does not mention are roots for _, inst in __iter(order) do if not parented[inst] then table.insert(tree.roots, inst) @@ -166905,7 +164072,6 @@ if clen == 0 then end -- ------------------------------------------------------------------------------------------------ encode --- the binary type of a property over a class's instances: type id, type name | nil, message local function columnType(insts, pname) local id, tname = nil, nil for _, inst in __iter(insts) do @@ -166957,8 +164123,7 @@ if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table local o= opts or {} local compress = o.compression ~= "none" local place = (o.place ~= nil and{(o.place == true )}or{o.format == "rbxl" and true or tree.place == true -})[1] -- every instance depth first; referents in that order - local insts= {} +})[1] local insts= {} local refOf= {} local parentOf= {} local function visit(inst, parent) @@ -166985,7 +164150,6 @@ if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.proper return nil, e end end - -- classes by name local byClass= {} local names = {} for _, inst in __iter(insts) do @@ -166998,7 +164162,6 @@ if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.proper table.insert(list, inst) end table.sort(names) - -- shared strings, in order of first use local sharedIdx= {} local sharedList= {} local ctx= { @@ -167073,7 +164236,7 @@ if pn == "Name" then putStr(pw, pn) local tid = t if tid == -1 then - -- Raw: the column read from a file, written back only when this class still has exactly its instances + -- Raw: written back only when this class still has exactly its instances local first = list[1].properties[pn] local raw = first and first.value local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" @@ -167182,20 +164345,10 @@ return Rbxm end __FILES["model/rbxmx"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict --- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, `<roblox version="4">`), read + write, to and from --- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). --- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. --- Decode: <Meta>, <Item class referent> with <Properties> of every type codecs/model/Rbx lists (string, BinaryString --- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), --- token, BrickColor (as rbx-dom: an <int>; read back as BrickColor for the BrickColor properties of a short --- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, --- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, --- PhysicalProperties, Ref, SharedString (+ <SharedStrings>), UniqueId, Font, SecurityCapabilities); unknown property --- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. --- tree.place is true when a root is a Workspace (rbxlx). --- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, --- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control --- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. +-- model/rbxmx: Roblox XML model / place (.rbxmx / .rbxlx, `<roblox version="4">`) to and from a codecs/model/Rbx +-- RbxTree, from the rbx-dom notes (docs/xml.md), checked against rojo 7.7 and lune 0.11. Supports: every type +-- codecs/model/Rbx lists; unknown tags round-trip as "XmlRaw". Encode follows rbx-dom's layout. +-- Not supported: writing "Raw" values. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -167227,7 +164380,6 @@ local Rbxmx = { local XmlNode = Xml.element local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch --- tag name -> type name for the simple (text) types local SCALAR_TAGS= { string = "String", ProtectedString = "ProtectedString", @@ -167264,7 +164416,7 @@ local head = r:peek(256) return 0 end --- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +-- a Workspace item makes a place function Rbxmx.variant(r) local text = buffer.readstring(r.buf, r.base, r.limit - r.base) return find(text, '<Item class="Workspace"', 1, true) and"rbxlx" or"rbxmx" @@ -167311,8 +164463,6 @@ end local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" } local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" } --- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs --- come back as { pending = referent }) local function readRaw(node, shared, key) local tag = node.name local scalar = SCALAR_TAGS[tag] @@ -167481,7 +164631,6 @@ local text = buffer.readstring(r.buf, r.base, r.limit - r.base) end local tree = Rbx.tree() tree.meta.source = { format = "rbxmx", version = root.attrs.version } - -- shared strings first (properties name them by key) local shared= {} for _, ss in __iter(Xml.children(root, "SharedStrings")) do for _, s in __iter(Xml.children(ss, "SharedString")) do @@ -167493,7 +164642,7 @@ local text = buffer.readstring(r.buf, r.base, r.limit - r.base) end end local byRef= {} - local pending= {} -- { value table, field, referent } + local pending= {} local function item(node, parent) local cls = node.attrs.class if type(cls) ~= "string" then @@ -167564,7 +164713,6 @@ local cls = node.attrs.class end -- ------------------------------------------------------------------------------------------------ encode --- the shortest text that reads back as the same float (single: f32 values; else f64) local function fmt(v, single) if type(v) ~= "number" then v = 0 @@ -167618,7 +164766,6 @@ if find(s, "[%z\1-\8\11\12\14-\31\127]") then return utf8.len(s) ~= nil end --- a property -> its element, or nil to skip local function writeValue(name, v, refOf, sharedKey) local t, x = v.type, v.value local a = { name = name } @@ -167851,24 +164998,9 @@ return Rbxmx end __FILES["model/robloxmesh"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh --- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. --- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, --- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown --- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes --- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC --- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed --- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in --- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' --- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes --- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw --- (meta.source.facs). meta.up = "y"; units are studs. --- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every --- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes --- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to --- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). --- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing --- 3.00 / 5.00+ / FACS. +-- model/robloxmesh: Roblox FileMesh (.mesh), from MaximumADHD's "Roblox Mesh Format" (devforum.roblox.com/t/326114); no +-- port. Supports: reading 1.00 - 7.00 (Draco COREMESH v2 through codecs/model/Draco), writing 2.00 and 4.00. Not +-- supported: writing 3.00 / 5.00+ / FACS; FACS and HSRAVIS are kept raw. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -167921,7 +165053,6 @@ local n = math.max(0, to - from) return accessor(d, "u32", 1, n * 3) end --- a Draco-compressed COREMESH body -> the record's vertex / face fields local function dracoCore(b, off, len) -- the stream follows a u32 byte count (accepted without it too) if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then @@ -167947,7 +165078,6 @@ if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= if not pos or pos.components < 3 then return nil, "corrupt: Draco COREMESH without positions" end - -- an attribute's values as numbers (normalized integers as -1..1 / 0..1) local function getter(a) local t = (a.normalized and{(({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) )[a.type] or a.type }or{a.type })[1] local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) @@ -168015,7 +165145,7 @@ local out = buffer.create(n * comps * 4) }, nil end --- Parse is native: nothing may throw through it, so the callback never does +-- Parse is native: nothing may throw through it local function safeCore(b, off, len) local ok, c, err = pcall(dracoCore, b, off, len) if not ok then @@ -168051,7 +165181,6 @@ local lim= { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts if r.col then attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) end - -- LOD ranges (offsets clamped to the faces) local offs = {} for _, o in __iter(r.lods) do table.insert(offs, math.clamp(o, 0, nf)) @@ -168072,7 +165201,6 @@ local lim= { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts scene.meshes[1] = mesh scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } scene.roots[1] = 1 - -- bones and skinning local nb = #r.bones if nb > 0 then local world= (table.create(nb) ) @@ -168158,7 +165286,6 @@ if not attr or c >= attr.components then return attr.values[i * attr.components + c + 1] end --- area-weighted vertex normals local function normals(pos, nv, corners) local acc = table.create(nv * 3, 0) for f = 0, math.floor(#corners / 3 )- 1 do @@ -168188,7 +165315,6 @@ end end return out end --- world matrices of every node (parents through children lists) local function worlds(scene) local out= {} local parent= {} @@ -168215,7 +165341,6 @@ if out[i] then return out end --- the bones of a skin: Parse.Bone list, or nil, message local function skinBones(scene, skin) local joints = skin.joints if type(joints) ~= "table" or #joints == 0 then @@ -168262,7 +165387,6 @@ local joints = skin.joints return out, nil end --- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) local function fill(r, m, order, nrm) local nv = #order local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) @@ -168354,7 +165478,6 @@ return keep[name] == true })[1] if src and type(src.lodType) == "number" then r.lodType, r.highQualityLods = src.lodType, (type(src.highQualityLods) == "number" and{src.highQualityLods }or{0 })[1] end - -- normals when the scene has none local nrm= nil if not m.attrs.NORMAL then local pb = buffer.create(nv0 * 12) @@ -168365,7 +165488,6 @@ return keep[name] == true end nrm = normals(pb, nv0, corners) end - -- the skin (4.00): the first node with a mesh and a skin local skin = nil if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then for _, n in __iter(scene.nodes or {}) do @@ -168385,7 +165507,6 @@ return keep[name] == true local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 local wscale = W.raw and 1 / 255 or 1 local nb = #bones - -- per vertex: up to 4 (joint, weight) pairs with weight > 0 local influences= (table.create(nv0) ) for v = 0, nv0 - 1 do local list = {} @@ -168398,7 +165519,7 @@ for v = 0, nv0 - 1 do end influences[v + 1] = list end - -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + -- subsets: a new subset when a face's joints do not fit in 26 local faceIdx = buffer.create(nf * 12) local order= {} local s= nil @@ -168498,7 +165619,6 @@ for v = 0, nv0 - 1 do end r.faces = faces r.lods = { 0, nf } - -- extra LODs of a single untransformed primitive local part = m.parts[1] local mesh = part and part.mesh local lods = (#m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" and{mesh.extras.lods }or{nil @@ -168539,16 +165659,12 @@ __FILES["model/robloxmesh/Parse"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version: --- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the --- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core --- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data. +-- model/robloxmesh/Parse: FileMesh bytes to a flat record, little endian, 1.00 - 7.00 (MaximumADHD's "Roblox Mesh +-- Format", devforum 326114); a Draco COREMESH v2 goes through the lim.core callback. Never throws. local Parse = {} local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring local writef32, writeu32 = buffer.writef32, buffer.writeu32 --- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record --- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco) @@ -168654,7 +165770,7 @@ local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)")) end -- ------------------------------------------------------------------------------------------------ binary parts --- vertices of size vs (36 / 40) at p +-- vertices of 36 / 40 bytes local function vertices(b, p, n, vs, r) local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) local col = (vs >= 40 and{(buffer.create(n * 4) )}or{nil @@ -168961,7 +166077,6 @@ local r = record(version) return r, nil end --- parse(b, p, e, lim) -> Record | nil, message function Parse.parse(b, p, e, lim) if e - p < 13 then return nil, "truncated: no version line" @@ -168986,7 +166101,7 @@ if e - p < 13 then return nil, "unsupported: version " .. version end --- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +-- packed tangent: signed bytes / 127 local function snorm(v) local x = (v >= 128 and((v - 256 ))or(v )) return math.clamp(x / 127, -1, 1) @@ -169001,9 +166116,8 @@ __FILES["model/robloxmesh/Write"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: --- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning --- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +-- model/robloxmesh/Write: a flat record to FileMesh 2.00 (header, 36- or 40-byte vertices, faces) or 4.00 (24-byte +-- header, 40-byte vertices, skinning, faces, LOD offsets, bones, bone names, subsets). Never throws. local Parse = __include("model/robloxmesh/Parse") local Bytes = __include("core/Bytes") @@ -169030,7 +166144,6 @@ local function vertex(w, r, i, colors) w.pos = p + (colors and 40 or 36) end --- write(r, version) -> buffer ("2.00" | "4.00") function Write.write(r, version) local nv, nf = r.numVerts, r.numFaces local w = Bytes.writer(64 + nv * 48 + nf * 12) @@ -169110,21 +166223,9 @@ return Write end __FILES["model/schematic"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: --- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and --- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, --- Sponge, Litematic. --- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic --- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as --- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = --- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the --- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). --- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) --- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, --- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the --- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. --- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with --- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). +-- model/schematic: Minecraft schematics, read + write: MCEdit / WorldEdit .schematic (pre-1.13), Sponge .schem v1-3 +-- (WorldEdit 7+) and Litematica .litematic. Not supported: block properties to pre-1.13 data values, Sponge biome +-- conversion between versions, rotated nodes. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -169190,7 +166291,6 @@ local p = Nbt.peek(r.buf, r.base, r.limit - r.base) return (hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) )and 1 or 0 end --- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) function Schematic.variant(r) local p = Nbt.peek(r.buf, r.base, r.limit - r.base) if not p then @@ -169209,7 +166309,6 @@ local p = Nbt.peek(r.buf, r.base, r.limit - r.base) end -- ------------------------------------------------------------------------------------------------ decode --- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil local function variantOf(root) if type(root) ~= "table" or not Types.isObject(root) then return nil, nil @@ -169344,7 +166443,6 @@ local node = value.nodes[i] return out, nil end --- merge(regions) -> one region covering them all (air where none is) local function merge(regions) if #regions == 1 then return regions[1] @@ -169446,16 +166544,14 @@ return Schematic end __FILES["model/schematic/Common"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, --- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, --- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +-- model/schematic/Common: shared region record, NBT access and block entities as Sponge v3's { pos = { x, y, z }, id, +-- data } (MCEdit / Litematica use flat { x, y, z, id, ... }, Sponge v2 { Pos, Id, ... }). local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") local Common = {} --- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states --- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil +-- a block region: u16 indices per cell in Types.Voxels order (x fastest, then y, then z) into states @@ -169469,7 +166565,6 @@ local Common = {} Common.int = Mc.int --- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells function Common.dims(a, b, c, max) local x, y, z = Common.int(a), Common.int(b), Common.int(c) if not x or not y or not z then @@ -169484,14 +166579,11 @@ local x, y, z = Common.int(a), Common.int(b), Common.int(c) return x, y, z end --- ints(v) -> the numbers of an intArray tag or a list of numbers | nil Common.ints = Mc.ints --- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) Common.blockEntity = Mc.blockEntity Common.flatBlockEntity = Mc.flatBlockEntity --- list(v) -> v when it is an NBT list (array), else an empty list function Common.list(v) if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then return v @@ -169499,7 +166591,6 @@ if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then return {} end --- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) function Common.compound(fields) local o, keys = {}, {} for _, kv in __iter(fields) do @@ -169511,8 +166602,6 @@ local o, keys = {}, {} return Types.object(o, keys) end --- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key --- order (a decoded source compound: its other keys are kept, except those in drop), new keys after function Common.merge(base, fields, drop) if type(base) ~= "table" or not Types.isObject(base) then return Common.compound(fields) @@ -169545,7 +166634,6 @@ if type(base) ~= "table" or not Types.isObject(base) then return Common.compound(out) end --- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) function Common.dedupe(states, indices, n) local first= {} local remap= {} @@ -169576,11 +166664,9 @@ return Common end __FILES["model/schematic/Litematic"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, --- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, --- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state --- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative --- to the region's minimum corner), Entities and pending ticks (kept as they are). +-- model/schematic/Litematic: .litematic, from LitematicaSchematic / LitematicaBitArray as documented by litemapy: +-- Metadata, named Regions (Position, Size may be negative), palette (0 = air), BlockStates spanning longs (>= 2 bits), +-- TileEntities relative to the region's minimum corner, Entities and pending ticks. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -169605,7 +166691,6 @@ local function vec(v) return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) end --- read(root, maxCells) -> { Region }, extra | nil, message function Litematic.read(root, maxCells) if not Types.isObject(root.Regions) then return nil, "no Regions" @@ -169683,8 +166768,6 @@ if not Types.isObject(root.Regions) then } end --- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root --- (Metadata fields and each region's Position / Size signs and pending ticks are kept) function Litematic.write(regions, version, dataVersion, base, title) local baseRegions = (type(base) == "table" and Types.isObject(base.Regions) and{base.Regions }or{nil })[1] local regs, order = {}, {} @@ -169740,7 +166823,6 @@ local baseRegions = (type(base) == "table" and Types.isObject(base.Regions) and{ local b = (baseRegions and{baseRegions[name] }or{nil })[1] local bsize = (type(b) == "table" and{(xyz(b.Size) )}or{nil })[1] if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then - -- keep the source's corner and signs for k = 1, 3 do if bsize[k] < 0 then size[k] = bsize[k] @@ -169793,12 +166875,9 @@ return Litematic end __FILES["model/schematic/Mcedit"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki --- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high --- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name --- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft --- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block --- nearest in colour). +-- model/schematic/Mcedit: MCEdit / WorldEdit .schematic (pre-1.13; Minecraft wiki "Schematic file format"): Width / +-- Height / Length, Blocks + Data (+ AddBlocks high nibbles, high nibble first), Materials = "Alpha", TileEntities, +-- Entities, WEOffset*, and the SchematicaMapping / BlockIDs name tables of Schematica and MCEdit-Unified. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -169808,7 +166887,6 @@ local Mcedit = {} local Packed = Mc.Packed --- read(root, maxCells) -> { Region }, extra | nil, message function Mcedit.read(root, maxCells) local blocks = root.Blocks if type(blocks) ~= "buffer" then @@ -169946,15 +167024,12 @@ local c = Mc.color(state) return bid, bd end --- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other --- fields are kept function Mcedit.write(r, base) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then return nil, "a .schematic is at most 65535 cells on each axis" end local n = sx * sy * sz - -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list local map= {} if type(base) == "table" then if Types.isObject(base.SchematicaMapping) then @@ -170044,10 +167119,9 @@ return Mcedit end __FILES["model/schematic/Sponge"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the --- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the --- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / --- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +-- model/schematic/Sponge: .schem (WorldEdit 7+, FAWE, Amulet), from SpongePowered/Schematic-Specification v1-3: Width / +-- Height / Length, Offset, Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities +-- (TileEntities / BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Mc = __include("codecs/model/Minecraft") @@ -170057,7 +167131,6 @@ local Sponge = {} local Packed = Mc.Packed --- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) function Sponge.read(s, maxCells) local version = Common.int(s.Version) or 1 local function u16(v) @@ -170126,8 +167199,6 @@ local n = Common.int(v) return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } end --- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, --- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept function Sponge.write(r, version, dataVersion, base) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then @@ -170177,12 +167248,8 @@ return Sponge end __FILES["model/smd"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the --- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a --- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation --- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, --- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. --- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). +-- model/smd: Valve SMD (studiomdl "version 1" text, GoldSrc and Source), from the Valve Developer Community "SMD file +-- format" page; no code taken. Units as stored (inches in Valve's games), z up. Not supported: vertex animation (flex). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -170248,14 +167315,9 @@ return Smd end __FILES["model/smd/Read"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, --- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone --- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px --- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). --- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material --- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, --- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond --- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +-- model/smd/Read: sections "nodes" (id, "name", parent), "skeleton" ("time n", "bone px py pz rx ry rz", Euler radians, +-- R = Rz Ry Rx; a bone missing from a later frame keeps its pose), "triangles" (a material line, then "bone px py pz +-- nx ny nz u v [links (bone weight)...]", model space, v up; the rest of the weight goes to the parent bone). local Types = __include("Types") local Rig = __include("codecs/model/Rig") @@ -170269,7 +167331,6 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 local ZERO= { 0, 0, 0, 0, 0, 0 } --- read(text, opts) -> Scene | nil, message function Read.read(text, opts) local lines= {} for line in __iter(string.gmatch(text, "[^\r\n]*")) do @@ -170426,7 +167487,7 @@ local batches= {} local root= { name = opts and opts.name or "smd", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 - -- skeleton (bind pose: the first frame) + -- bind pose: the first frame local joints= {} local bind= frames[1] or {} for k, bn in __iter(bones) do @@ -170435,7 +167496,6 @@ local batches= {} })[1] joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } end local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) - -- meshes if #batches > 0 then local mesh= { primitives = {} } for _, b in __iter(batches) do @@ -170493,7 +167553,6 @@ local batches= {} table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = (#bones > 0 and{skinIndex }or{nil })[1]}) table.insert(root.children, #scene.nodes) end - -- animation if #frames > 1 or (#frames == 1 and #batches == 0) then local fps = opts and opts.fps or 30 local t= {} @@ -170525,14 +167584,8 @@ return Read end __FILES["model/smd/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node --- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose --- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled --- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every --- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material --- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the --- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless --- opts.triangles is true. +-- model/smd/Write: Scene -> SMD version 1: the first skin's joints (or one "root" bone), the bind pose or a sampled +-- animation, world-space triangles with Source links (GoldSrc style: the strongest joint as the parent bone only). local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Flatten = __include("codecs/model/MeshFlatten") @@ -170578,7 +167631,6 @@ local out= {} return out end --- the value of channel ch at time tm (nil when the channel has no keys) local function sample(ch, tm) local input, output = ch.input, ch.output local n = input.count @@ -170617,7 +167669,6 @@ local out= {} return key(n - 1) end --- write(scene, opts) -> text | nil, message function Write.write(scene, opts) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, "expected a Scene" @@ -170705,7 +167756,6 @@ local t = tr or { 0, 0, 0 } end end table.insert(out, "end") - -- triangles if not anim or (opts and opts.triangles) then local m, err = Flatten.merge(scene, function(name) return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" @@ -170777,22 +167827,9 @@ return Write end __FILES["model/stl"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description --- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). --- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the --- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: --- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the --- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in --- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly --- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in --- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final --- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, --- solids, facets }. --- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans --- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after --- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle --- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either --- convention. Not supported: binary-only extensions other than the two colour conventions. +-- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports: +-- the VisCAM / SolidView and Materialise Magics colour conventions, a binary file starting with "solid" (size exactly +-- 84 + 50 * count), several ASCII solids. Not supported: other binary attribute extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -170826,8 +167863,6 @@ local Stl = { - - local readu8, readu32 = buffer.readu8, buffer.readu32 local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 @@ -171068,7 +168103,7 @@ local maxFaces = opts and opts.maxFaces or 2 ^ 25 if size < 84 then return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) end - -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + -- extra bytes after the facets are tolerated return decodeBinary(r, maxFaces, colors) end @@ -171079,7 +168114,6 @@ writef32(scratch, 0, v) return buffer.readf32(scratch, 0) end --- a COLOR_0 component as 0..255 local function byte(a, v) if a.raw then if a.type == "unorm16" then @@ -171119,8 +168153,7 @@ local o= opts or {} })[1] local C = m.attrs.COLOR_0 local corners = m.corners local nf = math.floor(#corners / 3 -) -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) - local function normal(f) +) local function normal(f) local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] if N then return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] @@ -171181,7 +168214,6 @@ v = f32(v) end return buffer.fromstring(table.concat(out)), nil end - -- binary local buf = buffer.create(84 + 50 * nf) local header = o.header or "rosetta STL" if colors == "magics" then @@ -171198,7 +168230,6 @@ v = f32(v) end buffer.writestring(buf, 0, header) writeu32(buf, 80, nf) - -- the attribute words: colours, or the raw words of a single STL-decoded primitive local rawAttr= nil if colors == nil and #m.parts == 1 then local ex = m.parts[1].prim.extras @@ -171248,16 +168279,13 @@ __FILES["model/stl/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 --- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that --- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +-- model/stl/Decode: binary STL facets (50 bytes: normal, 3 vertices, u16 attribute) and the 5-5-5 colours of VisCAM / +-- SolidView and Materialise Magics. Never throws: the caller bounds the facets first. local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift local Decode = {} --- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into --- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). function Decode.binary(b, p, n, pos, nrm, attr) local any = 0 for i = 0, n - 1 do @@ -171289,14 +168317,12 @@ local any = 0 return any end --- 5-bit -> 8-bit, rounded local function x8(v) return math.floor((v * 255 + 15) / 31 )end --- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, --- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, --- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +-- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14. function Decode.colors(attr, n, magics, dr, dg, db, da, out) for i = 0, n - 1 do local w = readu16(attr, i * 2) @@ -171325,22 +168351,10 @@ return Decode end __FILES["model/usda"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text --- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own --- reader / writer (pxr) and Blender's USD exporter. --- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / --- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, --- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one --- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every --- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, --- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / --- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> --- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / --- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). --- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. --- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs --- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel --- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. +-- model/usda: USD ASCII layers (.usda, text .usd) and USDZ packages of them, from the Sdf text format and the UsdGeom / +-- UsdShade / UsdLux docs (OpenUSD 26.x), checked against pxr and Blender's exporter. Not supported: USDC crate files, +-- composition arcs (listed in meta.source.unsupported), UsdSkel, blend shapes, curves / points / NURBS, instancers, +-- MaterialX, writing USDZ. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -171383,7 +168397,6 @@ local function isUsdz(r) if r:peek(4) ~= "PK\3\4" then return false end - -- the first entry is the root layer local lo, hi = r:peekU8(26), r:peekU8(27) if lo < 0 or hi < 0 then return false @@ -171400,7 +168413,7 @@ local head = r:peek(8) return 1 end if head == "PXR-USDC" then - return 0.9 -- recognised so the error says USDC is not supported + return 0.9 -- USDC magic, so the error says it is unsupported end if isUsdz(r) then return 0.95 @@ -171535,7 +168548,6 @@ if type(scene) ~= "table" or scene.kind ~= "scene" then end -- ------------------------------------------------------------------------------------------------ extras --- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover function Usda.parse(text) local layer, msg, at = Parse.layer(text) if not layer then @@ -171548,24 +168560,9 @@ return Usda end __FILES["model/usda/Build"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux --- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; --- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh --- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / --- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. --- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the --- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local --- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); --- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / --- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor --- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every --- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated --- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. --- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with --- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> --- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). --- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in --- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +-- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other +-- attributes than xform ops use their earliest sample (as UsdTimeCode.EarliestTime()). Not supported: composition arcs, +-- UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Parse = __include("model/usda/Parse") @@ -171602,7 +168599,6 @@ if type(v) == "string" then end return nil end --- a tuple / scalar -> numbers (nil when not numeric) local function nums(v) if type(v) == "number" then return { v } @@ -171639,7 +168635,7 @@ if type(v) == "number" then return nil end --- the value of a property: its default, else its earliest time sample +-- a property's default, else its earliest time sample local function propValue(p) if not p then return nil @@ -171666,7 +168662,6 @@ local function joinPath(parent, name) return (parent == "/" and(("/" .. name ))or((parent .. "/" .. name )))end --- resolve a (possibly relative) Sdf path against the prim path that holds it local function resolvePath(base, p) if string.sub(p, 1, 1) == "/" then return p @@ -171687,7 +168682,6 @@ if string.sub(p, 1, 1) == "/" then end return "/" .. table.concat(out, "/") end --- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" local function splitProp(p) local prim, prop = string.match(p, "^(.-)%.([^/]+)$") if prim and prop then @@ -171707,7 +168701,6 @@ local l = math.sqrt(x * x + y * y + z * z + w * w) return Mat4.fromQuat({ x, y, z, w }) end -- ------------------------------------------------------------------------------------------------ xform ops --- the op stack of a prim: ops in xformOpOrder, resetXformStack @@ -171742,7 +168735,6 @@ local order = p.props.xformOpOrder end local AXIS = { X = 1, Y = 2, Z = 3 } --- the matrix of one op for a value local function opMatrix(op, v) local n = nums(v) if not n then @@ -171765,7 +168757,7 @@ local k = op.kind m = table.clone(n) elseif k == "rotate" and op.axes then local axes = op.axes -local r= Types.Scene.IDENTITY -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles +local r= Types.Scene.IDENTITY -- rotateXZY: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles for c = 1, #axes do local a = AXIS[string.sub(axes, c, c)] @@ -171789,7 +168781,6 @@ local na, nb = nums(a), nums(b) end local out = table.create(#na) if quat and #na == 4 then - -- (w, x, y, z): slerp through nlerp with the short path local dot = 0 for k = 1, 4 do dot =dot+ na[k] * nb[k] @@ -171806,7 +168797,7 @@ local na, nb = nums(a), nums(b) return { t = "tuple", v = out } end --- an op's value at time code t (samples interpolated linearly, held outside their range) +-- samples interpolated linearly, held outside their range local function opValueAt(op, t) local p = op.prop local s = p.samples @@ -171858,7 +168849,6 @@ local scene = Types.Scene.new() local unsupported= {} local meta = layer.meta - -- prim index (variants merged), paths local byPath= {} local parentOf= {} local pathOf= {} @@ -171909,7 +168899,7 @@ local scene = Types.Scene.new() parentOf[p] = parent local existing = byPath[path] if existing and existing ~= p then - -- over / def of the same path in one layer: merge into the first spec + -- over / def of the same path in one layer: merged into the first spec for _, pn in __iter(p.order) do if not existing.props[pn] then existing.props[pn] = p.props[pn] @@ -171924,7 +168914,7 @@ local scene = Types.Scene.new() table.insert(existing.children, c) end table.clear(p.children) - p.specifier = "class" -- skipped below + p.specifier = "class" else byPath[path] = p end @@ -171945,7 +168935,6 @@ local scene = Types.Scene.new() unsupported.subLayers = true end - -- a property of a prim path ("/a/b.inputs:x") local function propAt(path) local pp, pn = splitProp(path) local prim = byPath[pp] @@ -171955,7 +168944,6 @@ local pp, pn = splitProp(path) return prim, prim.props[pn] end - -- --------------------------------------------------------------------------------------------- materials local texCoordIndex= {} local texCoordCount = 0 local function texCoordFor(name) @@ -171967,7 +168955,7 @@ local k = texCoordIndex[name] end return k end - -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + -- "st" first, so materials and meshes agree on TEXCOORD_n do local names= {} for _, p in __iter(byPath) do @@ -171996,8 +168984,7 @@ local pa = a == "st" and 0 or(string.sub(a, 1, 2) == "st" and 1 or 2 texCoordFor(nm) end end --- an input's resolved source: a value, or { shader = Prim, output = name } - + local function input(prim, name, depth) local d = depth or 0 @@ -172018,7 +169005,6 @@ local d = depth or 0 if outName and tprim.typeName == "Shader" then return { shader = tprim, output = outName } elseif outName then - -- a NodeGraph output: follow its connection local op = tprim.props[tn] if op and op.connect and #op.connect > 0 then local t2 = resolvePath(tp, op.connect[1]) @@ -172048,7 +169034,6 @@ return str(propValue(p.props["info:id"])) local textureIndex= {} local WRAP= { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } - -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) local function textureRef(shader) if shaderId(shader) ~= "UsdUVTexture" then return nil @@ -172084,7 +169069,7 @@ if shaderId(shader) ~= "UsdUVTexture" then textureIndex[key] = ti end local ref= { texture = ti } - -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + -- st: UsdPrimvarReader_float2, maybe through UsdTransform2d local st = input(shader, "st") local reader = st and st.shader if reader and shaderId(reader) == "UsdTransform2d" then @@ -172136,7 +169121,6 @@ local mi = materialIndex[path] mat.metallic = 0 mat.roughness = 0.5 mat.extras = { usd = { path = path } } - -- the surface shader local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] local shader= nil if surf and surf.connect and #surf.connect > 0 then @@ -172244,7 +169228,7 @@ local s = input(sh, name) return #scene.materials end - -- the bound material of a prim (material:binding, inherited from ancestors) + -- material:binding, inherited from ancestors local function binding(prim, path) local p= prim local pp = path @@ -172281,8 +169265,7 @@ local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) end return mi end --- --------------------------------------------------------------------------------------------- meshes - + local function primvar(p, defaultInterp) if not p then @@ -172340,7 +169323,6 @@ local pts = propValue(prim.props.points) end faceStart[nfaces + 1] = acc end - -- primvars, validated local function sizeOk(pv) local n = ((pv.idx and((#pv.idx ))or((math.floor(#pv.data / pv.w))))) local want = pv.interp == "constant" and 1 @@ -172397,7 +169379,6 @@ if not pv then end end end - -- the value of a primvar for (point, face, corner) (0-based), component c local function get(pv, point, face, corner, c) local e = pv.interp == "constant" and 0 or(pv.interp == "uniform" and{face @@ -172420,7 +169401,6 @@ or(pv.interp == "uniform" and{face end end local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" - -- holes local hole= {} local hv = propValue(prim.props.holeIndices) if isArr(hv) then @@ -172428,7 +169408,7 @@ or(pv.interp == "uniform" and{face hole[f] = true end end - -- face sets: GeomSubsets ("face" elements), the rest + -- face sets: GeomSubsets of "face" elements, then the rest local meshMaterial = binding(prim, path) local constantColor= nil if color and color.interp == "constant" then @@ -172470,9 +169450,8 @@ local sets= {} end local mesh= { name = prim.name, primitives = {} } for _, set in __iter(sets) do - -- vertices: one per point (vertex-rate data) or per corner local keyToVert= {} - local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local vp, vf, vc = {}, {}, {} local nv = 0 local out= {} local faceSizes= {} @@ -172550,7 +169529,6 @@ local a = Types.Scene.accessor(nil, "f32", comps, nv) end local mi = set.material if color and not constantColor then - -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) if opacity then local a = Types.Scene.accessor(nil, "f32", 4, nv) for v = 1, nv do @@ -172597,7 +169575,6 @@ local a = Types.Scene.accessor(nil, "f32", comps, nv) return mesh, nil end - -- --------------------------------------------------------------------------------------------- cameras / lights local function camera(prim) local function f(name, d) return num(propValue(prim.props[name])) or d @@ -172644,7 +169621,6 @@ return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props return l end - -- --------------------------------------------------------------------------------------------- nodes local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 if tcps <= 0 then tcps = 24 @@ -172696,7 +169672,6 @@ if d > 100 then table.insert(scene.nodes, n) local ni = #scene.nodes local ops, reset = xformOps(p) - -- animated ops: the local matrix at the union of their time codes local times= {} do local seen= {} @@ -172741,7 +169716,6 @@ if d > 100 then local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then - -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix local simple = true local stage = 0 for _, op in __iter(ops) do @@ -172837,7 +169811,6 @@ if d > 100 then table.insert(scene.animations, animation) end - -- stage metadata local up = str(meta.upAxis) scene.meta.up = up == "Z" and"z" or"y" local mpu = num(meta.metersPerUnit) @@ -172865,16 +169838,9 @@ return Build end __FILES["model/usda/Parse"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text --- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes --- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, --- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), --- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast --- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. --- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and --- returns nil, message, offset - nothing escapes. +-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads +-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws. local Parse = {} --- values: numbers, booleans, strings, and these tagged tables @@ -172917,12 +169883,10 @@ local function fail(msg, at) error({ usda = msg, at = at }, 0) end --- the parser over one text; positions are 1-based string indices local function parser(s, maxBytes) local n = #s local depth = 0 - -- whitespace and comments (newlines included) local function ws(i) while true do local _, e = sfind(s, "^[ \t\r\n]+", i) @@ -172930,13 +169894,13 @@ while true do i = e + 1 end local c = sbyte(s, i) - if c == 35 then -- # + if c == 35 then local nl = sfind(s, "\n", i, true) i = (nl and((nl + 1 ))or((n + 1 -))) elseif c == 47 and sbyte(s, i + 1) == 47 then -- // +))) elseif c == 47 and sbyte(s, i + 1) == 47 then local nl = sfind(s, "\n", i, true) i = (nl and((nl + 1 ))or((n + 1 -))) elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ +))) elseif c == 47 and sbyte(s, i + 1) == 42 then local _, ce = sfind(s, "*/", i + 2, true) if not ce then fail("unterminated comment", i) @@ -172971,7 +169935,7 @@ if not sfind(str, "\\", 1, true) then end return (string.gsub(str, "\\(x?)(.)", function(x, c) if x == "x" then - return "\\x" .. c -- left alone (rare) + return "\\x" .. c end return ESC[c] or c end)) @@ -173014,7 +169978,6 @@ local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) return v, (e ) + 1 end end - -- inf / -inf / nan local w, e2 = sfind(s, "^[-+]?%a+", i) if w then local word = string.lower(ssub(s, w, e2)) @@ -173029,7 +169992,6 @@ local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) return nil, i end - -- skip a balanced (), [], {} block starting at i (strings and comments respected) local function skipBalanced(i) local open = sbyte(s, i) local level = 0 @@ -173067,7 +170029,6 @@ local open = sbyte(s, i) local value local metadata - -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list local function list(i) local close = sfind(s, "]", i + 1, true) @@ -173082,7 +170043,7 @@ local close = sfind(s, "]", i + 1, true) w =w+ 1 end elseif sfind(body, "[%(%)]") then - w = -1 -- nested tuples: the generic path + w = -1 end if w > 0 then local out= {} @@ -173106,7 +170067,6 @@ local close = sfind(s, "]", i + 1, true) end end end - -- generic local items = {} i =i+ 1 while true do @@ -173122,7 +170082,7 @@ local close = sfind(s, "]", i + 1, true) v, i = value(i) table.insert(items, v) i = ws(i) - if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + if ssub(s, i, i) == "(" then local _ _, i = metadata(i) i = ws(i) @@ -173134,7 +170094,6 @@ local close = sfind(s, "]", i + 1, true) fail("expected ',' or ']' in a list", i) end end - -- all numbers, or all equal-width numeric tuples -> arr local w= nil local flat= {} for _, it in __iter(items) do @@ -173192,7 +170151,6 @@ local items = {} return { t = "tuple", v = items }, i end - -- { type key = value ... } (metadata dictionaries) local function dict(i) local out= {} i =i+ 1 @@ -173269,7 +170227,7 @@ if c == "[" then end local a= { t = "asset", v = path } local j = ws(i) - if ssub(s, j, j) == "<" then -- references = @file@</prim> + if ssub(s, j, j) == "<" then local e = sfind(s, ">", j + 1, true) if not e then fail("unterminated path", j) @@ -173310,7 +170268,6 @@ if c == "[" then return v, i end - -- ( key = value ; "doc" ; prepend key = value ... ) function metadata(i) local out= {} i = expect(i, "(") @@ -173347,9 +170304,7 @@ __DARKLUA_CONTINUE_11=true break local v v, i = value(i + 1) if op == "delete" then - -- deletions only matter for composition elseif op and op ~= "reorder" then - -- prepend / append / add: merge into one list local prev = out[key ] if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then for _, x in __iter(v.v) do @@ -173365,7 +170320,6 @@ __DARKLUA_CONTINUE_11=true break __DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end end - -- time samples: { time: value, ... } local function samples(i) local times, values= {}, {} i = expect(i, "{") @@ -173389,7 +170343,7 @@ __DARKLUA_CONTINUE_13=true break i = expect(i, ":") local v v, i = value(i) - table.insert(times, t ) -- fail() threw on nil + table.insert(times, t ) table.insert(values, v) __DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end return { times = times, values = values }, i @@ -173428,7 +170382,6 @@ i = ws(i) fail("expected a prim type or name", i) end i = ws(i) - -- dotted schema names (rare) while ssub(s, i, i) == "." do local more more, i = ident(i + 1) @@ -173484,7 +170437,7 @@ i = ws(i) end end - -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + -- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] local function property(i, first, p) local word= first local op= nil @@ -173551,7 +170504,6 @@ if typeName then local v v, i = value(i) if op == "delete" then - -- composition only elseif suffix == "connect" then pr.connect = targets(v) elseif isRel then @@ -173621,7 +170573,6 @@ __DARKLUA_CONTINUE_18=true break __DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end end - -- the whole layer local function layer() local i = 1 if ssub(s, 1, 3) == "\239\187\191" then @@ -173665,7 +170616,6 @@ local i = 1 return layer end --- layer(text, opts?) -> Layer | nil, message, offset (0-based) function Parse.layer(text, maxBytes) local run = parser(text, maxBytes or 2 ^ 30) local ok, res = pcall(run) @@ -173678,7 +170628,6 @@ local run = parser(text, maxBytes or 2 ^ 30) return nil, "parse error: " .. tostring(res), nil end --- version(text) -> the "#usda <version>" string function Parse.version(text) return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") end @@ -173687,17 +170636,8 @@ return Parse end __FILES["model/usda/Write"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. --- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, --- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture --- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a --- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, --- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are --- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) --- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), --- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the --- embedded bytes written into opts.files as <name>_<n>.<ext>. Not written: skins, morph targets, weights animation, --- lines / points primitives (counted in the returned notes). +-- model/usda/Write: Scene -> USD ASCII (UsdGeom / UsdShade / UsdLux); new code. timeCodesPerSecond 24. Not written: +-- skins, morph targets, weights animation, lines / points primitives. local Types = __include("Types") local Write = {} @@ -173736,7 +170676,6 @@ if string.find(s, "@", 1, true) then end return "@" .. s .. "@" end --- a valid, sibling-unique prim name local function namer() local used= {} return function(name, fallback) @@ -173757,7 +170696,6 @@ local n = string.gsub(name or "", "[^%w_]", "_") end end --- an accessor's elements as numbers (normalized types to floats) local function values(acc) if not acc then return nil, 0 @@ -173776,7 +170714,6 @@ for i = 0, n - 1 do return out, c end --- array literal of tuples ("[(x, y, z), ...]") or scalars local function arrayText(vals, width, stride, count, map) local st = stride or width local n = count or (math.floor(#vals / st)) @@ -173795,7 +170732,6 @@ local st = stride or width return "[" .. table.concat(parts, ", ") .. "]" end -- ------------------------------------------------------------------------------------------------ primitives --- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points @@ -173864,7 +170800,6 @@ for i = 1, nverts do return counts, out end --- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable local function merge(mesh, notes) local prims= {} for _, p in __iter(mesh.primitives) do @@ -173880,7 +170815,6 @@ local prims= {} if #prims == 0 then return nil end - -- attributes every primitive has local all = { NORMAL = true } local uvSets= {} for k = 0, 7 do @@ -174005,7 +170939,6 @@ local o= opts or {} local rootNames = namer() local rootName = wrap and"root" or rootNames(nodes[roots[1] ].name, "root") - -- texture files local base= o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" local texFile= {} for i, tex in __iter(scene.textures or {}) do @@ -174025,8 +170958,7 @@ local o= opts or {} end texFile[i] = uri end --- animation: per node, per path -> { times, values (components) } - + local tracks= {} local tcps = 24 @@ -174041,7 +170973,7 @@ local tracks= {} if vals and #times > 0 then local stride = comps local per = math.floor(#vals / (comps * #times) -) -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value +) -- CUBICSPLINE: in-tangent, value, out-tangent per key local off = (ch.interpolation == "CUBICSPLINE" and per == 3 and{comps }or{0 })[1] local mult = ch.interpolation == "CUBICSPLINE" and per == 3 and 3 or 1 local tv = {} @@ -174061,7 +170993,6 @@ local tracks= {} end end - -- header table.insert(out, "#usda 1.0") table.insert(out, "(") line(1, "defaultPrim = " .. quote(rootName)) @@ -174085,7 +171016,6 @@ local tracks= {} matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) end - -- xform ops of a node (+ its animation) local function xform(depth, ni, n) local tr= tracks[ni] local order= {} @@ -174106,7 +171036,6 @@ return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) local t, r, s = n.translation, n.rotation, n.scale if n.matrix and #n.matrix == 16 then if tr then - -- animated: start from the matrix's TRS local m = n.matrix local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) @@ -174164,7 +171093,6 @@ return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) if doubleSided then line(depth, "uniform bool doubleSided = 1") end - -- extent local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for i = 0, math.floor(#m.points / 3 )- 1 do for c = 1, 3 do @@ -174322,7 +171250,6 @@ return l.type == "spot" and' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' lightBody(depth + 1, lig ) end local childNames = namer() - -- a camera / light that did not take the node's prim if cam and kind ~= "Camera" then table.insert(out, "") line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) @@ -174366,7 +171293,6 @@ local h = lightHead(l) return table.concat(out, "\n"), notes end --- the Looks scope: materials as UsdPreviewSurface networks function Write._looks(out, depth, scene, matPath, texFile, line) local mats = scene.materials or {} if #mats == 0 then @@ -174383,8 +171309,7 @@ table.insert(out, "") line(depth + 1, "{") local d = depth + 2 line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") --- texture nodes (one per distinct ref) - + local texNodes= {} local function texNode(ref, color) if not ref or not texFile[ref.texture] then @@ -174456,7 +171381,6 @@ if not ref or not texFile[ref.texture] then end line(e, "token outputs:surface") line(d, "}") - -- primvar readers per texCoord set, transforms, textures local readers= {} for _, tn in __iter(texNodes) do local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 @@ -174529,19 +171453,9 @@ return Write end __FILES["model/vox"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) --- and the files MagicaVoxel 0.99.x saves (version 150 and 200). --- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / --- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, --- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown --- chunks are kept raw and written back. --- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per --- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as --- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is --- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. --- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must --- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. --- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. +-- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). +-- Supports: every chunk (unknown, PACK, MATT kept raw); shapes centred on their node like MagicaVoxel. Not supported: +-- writing models over 256 cells per axis (MagicaVoxel's limit); node scale other than mirroring. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -174653,7 +171567,7 @@ local out = {} return out end --- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }); nil when not a permutation local function rotation(b) local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) if i0 > 2 or i1 > 2 or i0 == i1 then @@ -174666,7 +171580,6 @@ return bit32.band(b, bit32.lshift(1, bit)) ~= 0 and-1 or 1 return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } end --- the node transform of a frame dictionary (_r, _t) local function applyFrame(node, f) local t = ints(f._t) local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 @@ -174715,7 +171628,7 @@ local function applyFrame(node, f) end end --- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +-- MATL: _type -> type, the other keys without their "_", numbers as numbers local function material(d) local m= { type = "diffuse" } for k, v in __iter(d) do @@ -174943,7 +171856,6 @@ for k = 1, nc do return out, nil end --- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) local function build(scene, graph, id, depth, visiting, nmodels) local t = graph[id] if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then @@ -174983,7 +171895,6 @@ local t = graph[id] return index end --- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err function Vox.decodeVoxels(r, opts) local p, err = parse(r, opts) if not p then @@ -175076,7 +171987,6 @@ local function wdict(w, d) end end --- a node's transform as a frame dictionary (_r, _t) | nil, message local function frameOf(node, base) local f= {} if base then @@ -175176,7 +172086,6 @@ if value.kind == "voxels" then wdict(w, meta.info) end) end - -- models for _, v in __iter(models) do local sx, sy, sz = v.size[1], v.size[2], v.size[3] chunk("SIZE", function() @@ -175192,7 +172101,6 @@ if value.kind == "voxels" then w.pos = at + count * 4 end) end - -- the scene graph local records= {} local nextId = 0 local function alloc() @@ -175326,7 +172234,6 @@ local node = nodes[index] end end) end - -- layers if type(meta.layers) == "table" then for _, l in __iter(meta.layers) do chunk("LAYR", function() @@ -175344,7 +172251,6 @@ local node = nodes[index] end) end end - -- palette local pal = models[1].palette or DEFAULT_PALETTE chunk("RGBA", function() for i = 1, 256 do @@ -175366,7 +172272,6 @@ local node = nodes[index] end end) end - -- materials local mats = models[1].materials if type(mats) == "table" then local ids = {} @@ -175435,15 +172340,11 @@ end __FILES["model/vox/Grid"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI --- records. Callers check every range first; nothing here throws. +-- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws. local Grid = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the --- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. --- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. function Grid.fill(dst, sx, sy, sz, src, off, n) local skipped = 0 local sxy = sx * sy @@ -175459,7 +172360,6 @@ local skipped = 0 return skipped end --- count(data, cells) -> the number of non-empty cells in data[0, cells) function Grid.count(data, cells) local n = 0 for k = 0, cells - 1 do @@ -175470,8 +172370,7 @@ local n = 0 return n end --- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). --- The caller sizes dst with count() (sx, sy, sz <= 256). +-- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256) function Grid.write(dst, at, data, sx, sy, sz) local p = at local k = 0 @@ -175497,22 +172396,9 @@ return Grid end __FILES["model/vrml"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over --- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. --- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, --- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and --- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, --- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), --- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated --- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> --- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons --- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless --- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). --- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / --- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, --- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). --- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and --- skins on write (the rest pose is written). +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl / .wrz over codecs/model/Vrml; new code. Supports: +-- the scene graph, DEF / USE, PROTO / EXTERNPROTO, the geometry nodes, Viewpoints, lights, interpolator ROUTEs as +-- animations. Not supported: VRML 1.0, Text, Script, sensors, sound, NURBS; morph targets and skins on write. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -175576,22 +172462,9 @@ return Wrl end __FILES["model/x"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", --- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format --- specification and the standard templates, checked against assimp's X importer and test models. --- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per --- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal --- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global --- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, --- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), --- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four --- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, --- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. --- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. --- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in --- meta.source.skippedFaces). --- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key --- interpolation options (keys are linear). +-- model/x: DirectX .x, read only: text ("txt "), binary ("bin "), MSZIP ("tzip" / "bzip"), 32- and 64-bit floats; from +-- Microsoft's DirectX file format spec and templates, checked against assimp. AnimTicksPerSecond defaults to 4800. Not +-- supported: DeclData / FVFData, progressive and patch meshes, non-linear key interpolation. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -175632,8 +172505,7 @@ end -- ------------------------------------------------------------------------------------------------ decode -- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, --- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may --- refer back into the previous block's output). +-- "CK" + deflate data); each block may refer back into the previous block's output. local function mszip(b, p, limit, maxBytes) if p + 4 > limit then return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) @@ -175720,11 +172592,8 @@ return X end __FILES["model/x/Build"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is --- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding --- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). --- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep --- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +-- model/x/Build: the .x object tree to a Scene, from the DirectX template layouts. Direct3D is left-handed (y up, row +-- vectors): z is negated (matrices as S * M * S) and windings reversed, as assimp does; UVs stay top-left. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Rig = __include("codecs/model/Rig") @@ -175734,7 +172603,6 @@ local Build = {} local Scene = Types.Scene local writef32, writeu32 = buffer.writef32, buffer.writeu32 --- a cursor over an object's flattened values @@ -175755,7 +172623,6 @@ local x = c.v[c.i] end return x end --- a non-negative integer (an index) local function index(c, limit) local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -175764,8 +172631,6 @@ local n = num(c) return n end --- a count of items that follow (each takes at least one value: a count past the data is refused before anything --- is allocated for it) local function count(c, limit) local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -175777,7 +172642,7 @@ local n = num(c) return n end --- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +-- S * M * S, S = diag(1, 1, -1) local function mirror(m) local o = table.clone(m) for _, k in __iter({ 3, 7, 9, 10, 12, 15 }) do @@ -175861,7 +172726,6 @@ local n = #values return Scene.accessor(b, "f32", comps, math.floor(n / comps)) end --- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) local function mesh(ctx, m, triangulate) local scene = ctx.scene local c= { v = m.vals, i = 1 } @@ -175889,7 +172753,6 @@ for k = 1, n do end faces[f] = face end - -- the optional data objects local normals= nil local nfaces= nil local uvSets= {} @@ -175964,12 +172827,11 @@ for q = 1, n do table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) end end - -- material per face (a single index applies to every face) + -- a single index applies to every face local function matOf(f) local mi = (#faceMat == 1 and{faceMat[1] }or{faceMat[f] })[1] return (mi and((mi + 1 ))or(1 )) end - -- unique vertices per (position, normal index) local key= {} local srcPos= {} local srcNrm= {} @@ -175985,7 +172847,7 @@ local mi = (#faceMat == 1 and{faceMat[1] }or{faceMat[f] local nface = nfaces and nfaces[f] local vs = (table.create(n) ) for k = 1, n do - local src = k == 1 and 1 or n - k + 2 -- winding reversed, first corner kept + local src = k == 1 and 1 or n - k + 2 local p = face[src] local q = (nface and nface[src] and nface[src] < nNormals and{nface[src] }or{(-1 )})[1] local kk = p * (nNormals + 1) + q + 1 @@ -176022,7 +172884,6 @@ for k = 1, n do return nil, nil end table.sort(order) - -- shared vertex attributes (one vertex buffer for every primitive of the mesh) local nout = #srcPos local P = (table.create(nout * 3) ) for v = 1, nout do @@ -176136,7 +172997,6 @@ local function frame(ctx, f, parent, triangulate, depth) node.matrix = m end elseif k.type == "Mesh" then - -- the first mesh on the frame's node, more as child nodes local mi, bones = mesh(ctx, k, triangulate) if mi then local holder = ni @@ -176257,7 +173117,6 @@ local triangulate = not (opts and opts.triangulate == false) end end end - -- skins: bone names -> frames for _, ps in __iter(ctx.pendingSkins) do local joints= {} local ibm = buffer.create(#ps.bones * 64) @@ -176296,22 +173155,14 @@ return Build end __FILES["model/x/Parse"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the --- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and --- binary tokens), checked against what assimp's XFileParser accepts (no code taken). --- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and --- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), --- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. --- Text: ; and , separators, // and # comments, quoted strings, <guid>s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). --- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and --- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/x/Parse: .x text and binary tokens to { type, name?, vals, kids } objects, from Microsoft's "DirectX File +-- Format Specification", checked against assimp's XFileParser (no code taken). Templates are skipped; Blender's +-- "1.#IND00" / "1.#QNAN0" read as 0. Never throws: bad data returns nil, message. local Parse = {} local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring --- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), --- "punct", "eof"; err holds a message after a bad token @@ -176347,7 +173198,7 @@ while true do return "eof", nil end local c = string.byte(s, p) - if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then local nl = string.find(s, "[\r\n]", p) p = (nl and((nl + 1 ))or((n + 1 ))) else @@ -176496,7 +173347,6 @@ while #queue < k do return (q and{q[1] }or{"eof" })[1] end local budget = maxValues - -- skips a template / unknown block whose "{" was just read local function skipBlock() local depth = 1 while depth > 0 do @@ -176511,8 +173361,7 @@ local depth = 1 end return nil end - local body -- an object whose type token was read: [name] { ... } - + local body local function object(parent, typ, depth) local name= nil local kind, v = take() @@ -176594,7 +173443,6 @@ if depth > 200 then return root, nil end --- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message function Parse.tree(b, from, limit, binary, floatSize, maxValues) local lex = (binary and{(binaryLexer(b, from, limit, floatSize) )}or{(textLexer(readstring(b, from, limit - from)) )})[1] return tree(lex, maxValues) @@ -176604,18 +173452,9 @@ return Parse end __FILES["model/x3d"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, --- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). --- New code. --- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, --- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, --- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / --- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; --- head meta, components and UNIT length (-> meta.unit). --- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the --- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). --- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, --- H-Anim skinning, scripts. +-- model/x3d: X3D (ISO/IEC 19775-1) XML (.x3d, 19776-1) and classic VRML (.x3dv, 19776-2) encodings, plain or gzipped, +-- over codecs/model/Vrml; new code. Supports: the model/vrml set plus the X3D geometry and material nodes. +-- Not supported: binary encodings (.x3db Fast Infoset / EXI), X3D JSON, Text, NURBS, shaders, H-Anim skinning, scripts. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176691,13 +173530,9 @@ return X3d end __FILES["music/669"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and --- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides --- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until --- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), --- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). --- Not supported: UNIS 669's "super fast" speed 0, writing. +-- music/669: Composer 669 / UNIS 669 modules ("if" / "JN"), ported from OpenMPT's Load_669.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Supports: 8 channels, 64-row patterns, played as the "s3m" family with 669's quirks +-- (periods in Hz, auto portamentos, effects D..H, a fixed 78 BPM). Not supported: UNIS 669's speed 0, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176722,11 +173557,11 @@ local Six69 = { local IT = Load.IT --- the 669 effects (high nibble of the effect byte) by name +-- effects: the high nibble of the effect byte local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } -- ------------------------------------------------------------------------------------------------ sniff --- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +-- the 497-byte header (the magic is two bytes only, so the other fields are checked too) local function validHeader(r) if r:size() < 497 then return false @@ -176889,7 +173724,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Six69.open(r, opts) local m, err = Six69.decode(r, opts) if not m then @@ -176902,12 +173736,9 @@ return Six69 end __FILES["music/ahx"] = function() --!strict --- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: --- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). --- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel --- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's --- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. --- Not supported: writing. +-- music/ahx: AHX (Abyss' Highest eXperience) 4-channel Amiga synth modules, "THX\0" .. "THX\2", rendered through +-- codecs/audio/Hively (a port of HivelyTracker's hvl2wav, BSD-3-Clause; at 44.1 kHz, stereo 0, equal to hvl2wav). +-- Supports: tracks, positions with transposes, PList instruments, subsongs. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176944,7 +173775,6 @@ local tune, err = Hively.parse(r.buf, r.base, r.limit) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Ahx.open(r, opts) local song, err = Ahx.decode(r) if not song then @@ -176957,13 +173787,9 @@ return Ahx end __FILES["music/far"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any --- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads --- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods --- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, --- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed --- tempo OpenMPT uses (80 BPM in tracker terms). --- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. +-- music/far: Farandole Composer modules (FAR, 16 channels), ported from OpenMPT's Load_far.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Plays as the "s3m" family with FAR's quirks (periods in Hz, a slide step of +-- 36318 / 1024 Hz, OpenMPT's fixed 80 BPM). Not supported: FAR's tempo effects (D / E), note offset (C), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -176998,7 +173824,7 @@ if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and end -- ------------------------------------------------------------------------------------------------ decode --- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +-- effect byte -> S3M effect, parameter, volume byte (0 = none): OpenMPT's table local function effect(e) local cmd, p = math.floor(e / 16), e % 16 if cmd == 1 then @@ -177178,7 +174004,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Far.open(r, opts) local m, err = Far.decode(r, opts) if not m then @@ -177191,16 +174016,9 @@ return Far end __FILES["music/hmp"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) --- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the --- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE --- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per --- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker --- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a --- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP --- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the --- tracks apply on top. Renders through codecs/audio/MidiRender. --- Not supported: writing; HMP branch tables (skipped). +-- music/hmp: HMI SOS music: HMP ("HMIMIDIP", "HMIMIDIP013195") and HMI ("HMI-MIDISONG061595"), from the layout +-- notes (wildmidi only as a test reference). Decodes to a Types.Midi (format 1, a track per chunk; the tick rate at +-- HMP 0x38 / HMI byte 212, as division 60). Not supported: writing, HMP branch tables. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -177235,8 +174053,7 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; --- otherwise the MIDI encoding +-- HMP deltas: 7-bit groups, least significant first, the last byte has bit 7 set; HMI: the MIDI encoding local function delta(b, p, e, hmp) local v, shift = 0, 1 for _ = 1, 5 do @@ -177269,7 +174086,6 @@ for i = 1, n do return t end --- one track [p, e) -> events (note-offs merged in) | nil, message local function track(b, p, e, hmp, ctx) @@ -177278,7 +174094,7 @@ local list, offs= {}, {} while p < e do local d, q = delta(b, p, e, hmp) if not d then - break -- (a track cut inside its last delta: keep what was read) + break end tick =tick+ d p = q @@ -177362,7 +174178,6 @@ local list, offs= {}, {} return out, nil end --- the chunk table -> { { start, stop } } track ranges | nil, message, kind local function hmpTracks(b, base, limit) local new = buffer.readstring(b, base + 8, 6) == "013195" local n = readu32(b, base + 0x30) @@ -177453,7 +174268,6 @@ local b, base, limit = r.buf, r.base, r.limit end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Hmp.open(r, opts) local midi, err = Hmp.decode(r, opts) if not midi then @@ -177466,12 +174280,9 @@ return Hmp end __FILES["music/hvl"] = function() --!strict --- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, --- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- --- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with --- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer --- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. --- Not supported: writing. +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1" (AHX extended: 4..16 channels, two effect columns, ring +-- modulation, panning, stereo separation), rendered through codecs/audio/Hively (a port of hvl2wav, BSD-3-Clause; at +-- 44.1 kHz equal to hvl2wav). Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -177508,7 +174319,6 @@ local tune, err = Hively.parse(r.buf, r.base, r.limit) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Hvl.open(r, opts) local song, err = Hvl.decode(r) if not song then @@ -177521,14 +174331,9 @@ return Hvl end __FILES["music/it"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to --- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or --- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, --- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo --- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. --- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's --- extension chunks (plugins, extended instrument properties), writing. +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT), played through codecs/audio/Tracker. Supports: 64 channels, +-- instrument / sample mode, old and new instrument headers, envelopes, NNAs, resonant filters (default Zxx macros), +-- IT 2.14 / 2.15 compressed samples, the message. Not supported: embedded MIDI macros, OpenMPT extensions, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -177695,7 +174500,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 if r.err then return nil, r.err end - -- channels: the highest one any pattern uses local nch = 1 local packed= {} local rowsOf= {} @@ -177709,7 +174513,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 end local data = pr:slice(len) packed[p], rowsOf[p] = data, rows - -- scan for the channel count local scan = data:sub(0) local seen= {} while not scan:eof() do @@ -177780,7 +174583,6 @@ __DARKLUA_CONTINUE_12=true until true if not __DARKLUA_CONTINUE_12 then break en local mr = r:sub(msgOff, msgLen) m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") end - -- instruments for i = 1, insnum do local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) if not ins then @@ -177788,7 +174590,6 @@ __DARKLUA_CONTINUE_12=true until true if not __DARKLUA_CONTINUE_12 then break en end m.instruments[i] = ins end - -- samples local total = 0 for i = 1, smpnum do local h = r:sub(smpOff[i], 80) @@ -177870,7 +174671,6 @@ end end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(rowsOf[p], nch) m.patterns[p] = pat @@ -177937,7 +174737,6 @@ __DARKLUA_CONTINUE_20=true until true if not __DARKLUA_CONTINUE_20 then break en end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function It.open(r, opts) local m, err = It.decode(r, opts) if not m then @@ -177951,16 +174750,12 @@ end __FILES["music/it/Itsex"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). --- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of --- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. --- --- Never throws: every read is bounds-checked; corrupt streams return nil, message. +-- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each +-- a u16 length then an LSB-first bit stream of deltas with three width-change methods. local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 local Itsex = {} --- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message function Itsex.decompress(buf, off, limit, frames, bits, it215) local out = buffer.create(frames * 4) local blockLen = bits == 16 and 0x4000 or 0x8000 @@ -177985,7 +174780,6 @@ local out = buffer.create(frames * 4) return nil, "compressed block runs past the end" end p = bend - -- bit reader over [bstart, bend) local bytePos = bstart local bitBuf = 0 local bitCount = 0 @@ -178041,7 +174835,6 @@ local __DARKLUA_CONTINUE_3=false repeat if width < 1 or width > topWidth then __DARKLUA_CONTINUE_3=true break end end - -- a delta, sign-extended from its width local x = v if width < topWidth then local shift = 2 ^ width @@ -178072,16 +174865,9 @@ return Itsex end __FILES["music/med"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, --- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song --- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL --- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks --- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop --- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave --- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, --- default pitch, volume). --- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and --- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. +-- music/med: MED / OctaMED modules (MMD0..MMD3), ported from OpenMPT's Load_med.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); the first song plays as the "xm" family with Amiga periods. Supports: 1..64 tracks, +-- play sequences, hold / decay, IFF multi-octave samples. Not supported: synth / MIDI instruments, echo, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -178148,7 +174934,7 @@ function Med.sniff(r) return validHeader(r) and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +-- OpenMPT's MMDTempoToBPM (SPD / 8-channel / BPM modes) @@ -178166,7 +174952,7 @@ if ctx.bpm and not ctx.is8Ch then return tempo / 0.264 end --- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +-- MED command -> MOD / XM effect, param, note-cut flag: OpenMPT's ConvertMEDEffect local function effect(cmd, p, ctx) local lo = math.min(p, 15) if cmd == 1 or cmd == 2 then @@ -178252,7 +175038,7 @@ local lo = math.min(p, 15) return 0, 0, false end --- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +-- OpenMPT's octave wrapping local function wrapNote(note, vol7bit) local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) if n > 132 and not vol7bit then @@ -178263,7 +175049,6 @@ local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) return (n >= 13 and((n - 12 ))or(0 ))end --- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding local function readBlock(r, off, version, ctx, nch) local br = r:sub(off) local ntracks, nrows, info @@ -178373,7 +175158,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } if numSamples > 0 and smpOff == 0 then return nil, Err.new(Err.CORRUPT, "no sample table") end - -- channels: the widest block (at least 4) local nch = 4 local blockPtr= {} for b = 0, numBlocks - 1 do @@ -178412,7 +175196,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } if ext.nameOff > 0 and ext.nameLen > 0 then m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) end - -- instruments and samples local needInstruments = false local instruments, samples = {}, {} local unsupported = {} @@ -178492,7 +175275,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end end end - -- sample data local list = {} for i = 0, count - 1 do local s = Tracker.newSample(name) @@ -178527,7 +175309,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } frames, ls, le = frames * 2, ls * 2, le * 2 end end - -- the instrument extras if xsize > 0 then if x.hold > 0 and not isSynth then local env = Tracker.newEnvelope() @@ -178664,7 +175445,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end end m.preamp = preamp - -- tempo, speed, volume, the pattern context local ctx= { transpose = 36 + playTranspose - (version > 2 and 24 or 0), is8Ch = bit32.band(flags, 0x40) ~= 0, @@ -178679,7 +175459,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } if masterVol > 0 then m.globalVolume = math.min(masterVol, 64) * 2 end - -- blocks for b = 0, numBlocks - 1 do local p = blockPtr[b + 1] local pat, high = nil, false @@ -178693,7 +175472,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } for at, to in __iter(jumps) do local prev = m.order[at - 1] if prev and prev < 254 and m.patterns[prev + 1] then - -- the block may be played elsewhere: give this order entry its own copy local src = m.patterns[prev + 1] local cp = Tracker.newPattern(src.rows, nch) buffer.copy(cp.data, 0, src.data) @@ -178722,7 +175500,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Med.open(r, opts) local m, err = Med.decode(r, opts) if not m then @@ -178735,16 +175512,9 @@ return Med end __FILES["music/midi"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the --- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). --- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / --- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, --- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: --- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to --- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running --- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and --- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. --- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). +-- music/midi: Standard MIDI Files (SMF 1.0 formats 0 / 1 / 2, PPQ and SMPTE; RIFF RMID read), from the spec. Supports: +-- decode to a Types.Midi, .kar lyrics, encode (byte-identical to python mido by default), the tempo map, rendering +-- through codecs/audio/SoundFont. Not supported: RMID write, XMF / DLS banks, system common bytes in tracks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -178780,8 +175550,7 @@ if r:peek(4) == "MThd" then end -- ------------------------------------------------------------------------------------------------ decode --- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and --- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +-- .kar: FF 01 text in a "Words" track (or after an "@K" / "@T" header) and FF 05 lyrics; "@X" headers -> meta.karaoke[X] local function karaoke(midi) local lyrics= {} local headers= {} @@ -178855,7 +175624,6 @@ return Smf.write(midi, opts) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) function Midi.open(r, opts) local midi, err = Midi.decode(r, opts) if not midi then @@ -178865,38 +175633,30 @@ local midi, err = Midi.decode(r, opts) end -- ------------------------------------------------------------------------------------------------ extras --- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) function Midi.render(midi, opts) return Render.decoder(midi, opts) end --- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) function Midi.tickToSeconds(midi, tick, track) return Render.seconds(Render.tempoMap(midi, track), tick) end --- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) Midi.tempoMap = Render.tempoMap Midi.seconds = Render.seconds --- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +-- as python mido's MidiFile.length (formats 0 / 1) function Midi.length(midi) return Render.length(midi) end --- text(data) -> the bytes of a text meta event as a string Midi.text = Smf.text return Midi end __FILES["music/midi/Smf"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE --- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps --- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are --- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the --- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track --- has none. Written from the SMF 1.0 specification (no third-party code). +-- music/midi/Smf: SMF 1.0 MThd / MTrk <-> Types.Midi (running status also across meta / sysex, RIFF RMID unwrapped). +-- Writes what python mido writes: running status reset after meta / sysex, one end-of-track, track names at tick 0. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -178935,13 +175695,11 @@ end Smf.text = text -- ------------------------------------------------------------------------------------------------ read --- one MTrk body [p, e): events | nil, message, truncated local function readTrack(b, p, e, budget) local events= {} local tick = 0 local running = 0 while p < e do - -- delta time local delta, n = 0, 0 repeat if p >= e then @@ -179032,7 +175790,6 @@ local events= {} return events, nil, false end --- read(r, opts?) -> Midi | nil, Err function Smf.read(r, opts) local strict = opts and opts.strict or false local budget = { opts and opts.maxEvents or 2 ^ 24 } @@ -179159,7 +175916,6 @@ if type(d) ~= "table" then return d end --- write(midi, opts?) -> buffer | nil, Err function Smf.write(midi, opts) if type(midi) ~= "table" or type(midi.tracks) ~= "table" then return nil, Err.new(Err.ARG, "needs a Midi value with tracks") @@ -179190,7 +175946,6 @@ if type(midi) ~= "table" or type(midi.tracks) ~= "table" then })[1] if type(events) ~= "table" then return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") end - -- stable order by tick local sorted = true local last = 0 for i, ev in __iter(events) do @@ -179216,7 +175971,7 @@ if a.tick ~= c.tick then return order[a] < order[c] end) end - -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own +-- a track-name meta event (0x03) at tick 0 when the track has none (as mido) if type(track.name) == "string" and track.name ~= "" then local named = false for _, ev in __iter(list) do @@ -179311,13 +176066,9 @@ return Smf end __FILES["music/mod"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, --- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or --- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through --- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" --- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). --- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter --- (E0x), PowerPacker-packed files. +-- music/mod: ProTracker / NoiseTracker / StarTrekker MODs (M.K., M!K!, FLT4, xCHN, xxCH, xxCN, CD81, OKTA, TDZx; +-- 15-sample Soundtracker by name or extension), from the ProTracker 2.3 docs. Writes 31-sample MODs from "mod" modules +-- and XM ones that fit. Not supported: FLT8's split patterns (read as 8 channels), the E0x filter, PowerPacker files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179358,7 +176109,7 @@ local FIXED= { ["EXO8"] = 8, } --- channels from the 4-byte signature at 1080, or nil +-- the 4-byte signature at offset 1080 local function signatureChannels(sig) local fixed = FIXED[sig] if fixed then @@ -179455,7 +176206,6 @@ local m = Tracker.newModule("mod", nch) m.restart = (restart < songLength and{restart }or{0 })[1] m.meta.signature = (nsamples == 31 and{sig }or{nil })[1] m.flags.amigaLimits = nch == 4 - -- patterns local npat = maxPat + 1 local patBytes = 64 * nch * 4 if not r:need(npat * patBytes) then @@ -179480,7 +176230,7 @@ local m = Tracker.newModule("mod", nch) m.patterns[p + 1] = pat end r:skip(npat * patBytes) - -- sample data (8-bit signed; the last samples of a truncated file are cut short) +-- sample data: 8-bit signed local total = 0 for i = 1, nsamples do local s = m.samples[i] @@ -179518,8 +176268,6 @@ local function writeName(w, s, n) w:fill(0, n - #t) end --- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to --- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. function Mod.encode(m, _opts) local ok, verr = Tracker.validate(m) if not ok then @@ -179532,7 +176280,6 @@ local ok, verr = Tracker.validate(m) if nch > 32 then return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") end - -- the sample for each instrument number local smpOf= {} if m.format == "xm" then for i, ins in __iter(m.instruments) do @@ -179585,7 +176332,6 @@ local ok, verr = Tracker.validate(m) local len = math.min(s.length, 131070) local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) if s.channels == 2 then - -- mix stereo samples down local mono = buffer.create(len * 4) for k = 0, len - 1 do buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) @@ -179661,7 +176407,6 @@ local ok, verr = Tracker.validate(m) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mod.open(r, opts) local m, err = Mod.decode(r, opts) if not m then @@ -179674,12 +176419,9 @@ return Mod end __FILES["music/mtm"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared --- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): --- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk --- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). --- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. +-- music/mtm: MultiTracker modules (MTM, 1..32 channels, patterns of shared tracks), ported from OpenMPT's Load_mtm.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "xm" family with Amiga periods, as OpenMPT does. Not supported: +-- MultiTracker's E9x / EDx retrigger timing and vibrato start phase (played as in XM), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179779,7 +176521,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } for i = 1, nch do m.channelPan[i] = (pans[i] % 16) * 16 + 8 end - -- samples local sizes= {} for i = 1, numSamples do local s = Tracker.newSample(r:fixed(22)) @@ -179810,7 +176551,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } })[1] s.length = frames m.samples[i] = s end - -- the order list for i = 1, 128 do local o = r:u8() if i <= lastOrder + 1 then @@ -179889,7 +176629,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mtm.open(r, opts) local m, err = Mtm.decode(r, opts) if not m then @@ -179902,15 +176641,9 @@ return Mtm end __FILES["music/mus"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format --- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter --- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel --- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at --- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without --- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per --- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / --- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. --- Not supported: writing (save as .mid through the midi format's encoder). +-- music/mus: DMX MUS ("MUS\x1a"; Doom, Heretic, Hexen, Strife), from Vladimir Arnost's "MUS File Format" (wildmidi +-- only as a test reference). Decodes to a Types.Midi as the usual converters map it (MUS channel 15 -> 9; 140 ticks/s +-- as division 70 at 500000 us per quarter). Not supported: writing (encode as .mid with the midi format). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -179946,7 +176679,6 @@ end -- ------------------------------------------------------------------------------------------------ decode local readu8 = buffer.readu8 --- the score [p, e) -> events | nil, message local function score(b, p, e, primary, maxEvents) local events= { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } local map= { [15] = 9 } @@ -180054,7 +176786,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Mus.open(r, opts) local midi, err = Mus.decode(r, opts) if not midi then @@ -180067,13 +176798,9 @@ return Mus end __FILES["music/okt"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can --- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style --- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with --- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample --- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: --- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. --- Not supported: the Amiga LED filter (F), writing. +-- music/okt: Oktalyzer modules (OKTASONG, 4..8 channels: each Amiga channel may be a mixed pair), ported from OpenMPT's +-- Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, loops as sustain +-- loops (released by R), the three arpeggios and note slides. Not supported: the LED filter (F), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180107,7 +176834,6 @@ return r:peek(8) == "OKTASONG" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode --- a negative arpeggio offset as the equivalent positive one local function invert(p) p =p% 16 if p == 0 then @@ -180116,7 +176842,6 @@ p =p% 16 return (p <= 12 and((12 - p ))or((24 - p )))end --- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off local function effect(e, p, paired) if e == 1 and p > 0 then return "portaup", p, -1, false -- "portamento down (period)": the period goes down @@ -180342,7 +177067,6 @@ __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Okt.open(r, opts) local m, err = Okt.decode(r, opts) if not m then @@ -180355,13 +177079,9 @@ return Okt end __FILES["music/ptm"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD --- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx --- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, --- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the --- byte stream, as PolyTracker stores them), ping-pong loops. --- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. +-- music/ptm: PolyTracker modules (PTMF, up to 32 channels), ported from OpenMPT's Load_ptm.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts PTM. Not supported: +-- reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180415,7 +177135,6 @@ local n = math.max(0, math.min(frames, math.floor((limit - off) / 2))) return raw, n end --- a PolyTracker effect -> name?, param local function effect(cmd, param) if cmd == 0x10 then return "globalvol", math.min(param, 0x40) * 2 @@ -180510,7 +177229,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } if r.err then return nil, r.err end - -- samples local buf = r.buf for i = 1, nsmp do local h = r:slice(80) @@ -180571,7 +177289,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ptm.open(r, opts) local m, err = Ptm.decode(r, opts) if not m then @@ -180584,12 +177301,9 @@ return Ptm end __FILES["music/s3m"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio --- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning --- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 --- speed reference, as IT shows S3M files). --- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC). Supports: 32 PCM channels, 8 / 16-bit mono / stereo +-- samples, the panning table, ST3.00 fast slides, every ST3 effect; notes stored an octave up (S3M C-4 = note 61, as IT +-- shows S3M files). Not supported: AdLib (OPL) instruments (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180671,7 +177385,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } - -- orders, parapointers, panning r:seek(96) for i = 1, ordnum do local o = r:u8() @@ -180711,7 +177424,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 m.channelPan[i] = pan m.channelMute[i] = c >= 16 end - -- samples local total = 0 local unsigned = ffi ~= 1 for i = 1, insnum do @@ -180739,7 +177451,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 local nchs = bit32.band(sflags, 2) ~= 0 and 2 or 1 local off = (hi * 65536 + lo) * 16 len = math.min(len, 2 ^ 26) - -- a short file: keep what is there local avail = math.floor(math.max(0, r:size() - off) / (math.floor(nchs * bits / 8)) ) len = math.min(len, avail) total =total+ len * nchs * 4 @@ -180755,7 +177466,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(64, nch) m.patterns[p] = pat @@ -180815,7 +177525,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function S3m.open(r, opts) local m, err = S3m.decode(r, opts) if not m then @@ -180828,11 +177537,9 @@ return S3m end __FILES["music/sf2"] = function() --!strict --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the --- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), --- presets / instruments / sample headers with global zones, generator merging into playable regions. --- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). --- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 spec), read-only, over codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: INFO, 16 / 24-bit (sm24) samples, presets / instruments with global zones, generators merged into regions. +-- Not supported: writing, SF3 (Vorbis samples), modulators (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -180866,7 +177573,6 @@ return SoundFont.parse(r, opts) end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback @@ -180874,12 +177580,9 @@ return Sf2 end __FILES["music/stm"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). --- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module --- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the --- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump --- happens at the end of the pattern or at the next Cxx). --- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro), ported from OpenMPT's +-- Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "s3m" family with ST2's tempo, no effect memory and +-- its deferred Bxx. Not supported: STX, ST2's noise for samples at volume 0 (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181096,7 +177799,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Stm.open(r, opts) local m, err = Stm.decode(r, opts) if not m then @@ -181109,14 +177811,9 @@ return Stm end __FILES["music/ult"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored --- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). --- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects --- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect --- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone --- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. --- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the --- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004, up to 32 channels), ported from OpenMPT's Load_ult.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts ULT. Not +-- supported: reverse (5x2), "no loop" (5x1), E0x, offsets past 64 KiB, pre-1.4 log volumes, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181155,7 +177852,7 @@ local v = r:peekU8(14) end -- ------------------------------------------------------------------------------------------------ decode --- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +-- OpenMPT's TranslateULTCommands local function translate(e, param, version) local name = EFFECTS[e] if e == 0 then @@ -181204,7 +177901,7 @@ local name = EFFECTS[e] return name, param end --- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +-- OpenMPT's CombineEffects (volume slide + vibrato / tone portamento without a parameter) local function combine(a, pa, b, pb) if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then return b == "vibrato" and"vibratovol" or"toneportavol", pa, nil, 0 @@ -181214,8 +177911,7 @@ if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then return a, pa, b, pb end --- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, --- lost global effect (name?, param) +-- event: [0xFC repeat] note instrument effects param1 param2 local function readEvent(r, version) local rep = 1 local b = r:u8() @@ -181407,7 +178103,6 @@ local budget = { left = opts and opts.maxBytes or 2 ^ 28 } end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ult.open(r, opts) local m, err = Ult.decode(r, opts) if not m then @@ -181420,14 +178115,9 @@ return Ult end __FILES["music/umx"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package --- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): --- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each --- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first --- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and --- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is --- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. --- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. +-- music/umx: Unreal Engine 1 music packages (.umx, versions up to 128), ported from OpenMPT's UMXTools.cpp / +-- ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): the IT / S3M / XM / MOD module of a "music" export; decode +-- needs opts.decodeModule (the api passes it). Not supported: Unreal Engine 2+ packages (.uax), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181525,8 +178215,6 @@ local h = header(r) end -- ------------------------------------------------------------------------------------------------ decode --- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: --- a guess from the inner module's signature: "it", "s3m", "xm", "mod") function Umx.extract(r) local h = header(r) if not h then @@ -181631,7 +178319,6 @@ m.meta = (type(m.meta) == "table" and{m.meta }or{{} end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Umx.open(r, opts) local m, err = Umx.decode(r, opts) if not m then @@ -181644,14 +178331,9 @@ return Umx end __FILES["music/xm"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / --- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and --- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit --- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga --- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files --- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). --- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's --- stereo-sample / extra-effect extensions on write. +-- music/xm: FastTracker 2 Extended Modules (XM 1.04), from the XM spec and FT2 behaviour notes. Supports: 8 / 16-bit +-- delta and ModPlug ADPCM samples, envelopes, linear / Amiga tables, every FT2 effect; writes "xm" (byte-identical in +-- FT2's layout) and "mod" modules. Not supported: OpenMPT's stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -181708,7 +178390,6 @@ local e = Tracker.newEnvelope() e.loop = bit32.band(typ, 4) ~= 0 e.susStart, e.susEnd = sus + 1, sus + 1 e.loopStart, e.loopEnd = ls + 1, le + 1 - -- the raw fields, for a faithful re-save e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } return e end @@ -181751,7 +178432,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 end m.meta.tracker = tracker m.meta.source = { format = "xm", tracker = tracker, version = version } - -- patterns if not r:seek(hdrStart + hdrSize) then return nil, r.err end @@ -181803,7 +178483,7 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 param = pr:u8() end if pr.err then - break -- a short pattern: the rest stays empty + break end if note == 97 then note = 255 @@ -181822,7 +178502,6 @@ local maxBytes = opts and opts.maxBytes or 2 ^ 28 end end end - -- instruments and their samples local total = 0 for i = 1, nins do local __DARKLUA_CONTINUE_7=false repeat local start = r:tell() @@ -181831,7 +178510,6 @@ local __DARKLUA_CONTINUE_7=false repeat local start = r:tell() r:u8() local ns = r:u16le() if r.err then - -- a file cut inside the instruments: keep what was read r.err = nil break end @@ -181888,8 +178566,7 @@ __DARKLUA_CONTINUE_7=true break s.pan = h.pan local frames = math.floor(h.len / bps ) if h.res == 0xAD and bits == 8 then - -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps - -- the samples whose nibbles are present +-- ModPlug ADPCM: a 16-byte delta table, then 4 bits per sample frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) total =total+ frames * 4 if total > maxBytes then @@ -181945,7 +178622,6 @@ local function writeName(w, s, n) w:fill(0, n - #t) end --- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } local function instrumentsOf(m) local out = {} if m.format == "mod" then @@ -182010,7 +178686,7 @@ if not e then local typ = (e.enabled and 1 or 0) + (e.sustain and 2 or 0) + (e.loop and 4 or 0) local raw = e.raw if raw and raw.type % 8 == typ then - typ = raw.type -- keep unknown bits + typ = raw.type end local function idx(v) return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) @@ -182023,7 +178699,6 @@ return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) return n, typ, sus, ls, le end --- encode(module, opts) -> XM bytes ("xm" or "mod" modules) function Xm.encode(m, opts) local ok, verr = Tracker.validate(m) if not ok then @@ -182124,7 +178799,6 @@ local ok, verr = Tracker.validate(m) w:u16le(buffer.len(data)) w:bytes(data) end - -- instruments for _, it in __iter(insts) do local __DARKLUA_CONTINUE_23=false repeat local ins = it.ins local smps = it.samples @@ -182206,7 +178880,6 @@ __DARKLUA_CONTINUE_23=true until true if not __DARKLUA_CONTINUE_23 then break en end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Xm.open(r, opts) local m, err = Xm.decode(r, opts) if not m then @@ -182219,14 +178892,9 @@ return Xm end __FILES["music/xmi"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, --- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description --- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, --- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's --- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second --- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the --- first tempo event's value, unused). Renders through codecs/audio/MidiRender. --- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. +-- music/xmi: Miles XMIDI (IFF: optional FORM XDIR, then CAT XMID of FORM XMID songs with TIMB / RBRN / EVNT), from +-- the XMIDI notes (Miles AIL, Ryan Nunn; wildmidi only as a test reference). Decodes one song to a Types.Midi at the +-- fixed 120 ticks per second (division 60). Not supported: writing, the RBRN branch table, MT-32 -> GM mapping. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -182265,7 +178933,6 @@ local readu8 = buffer.readu8 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a MIDI variable-length number at p -> value, next p (nil past e) local function vlq(b, p, e) local v = 0 for _ = 1, 4 do @@ -182290,7 +178957,6 @@ for i = 1, n do return t end --- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message local function events(b, p, e, maxEvents) local list, offs= {}, {} local tick, tempo = 0, nil @@ -182357,7 +179023,6 @@ local list, offs= {}, {} return Render.merge(list, offs), tick, tempo end --- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree local function songs(b, base, limit) local out = {} local function form(c) @@ -182423,7 +179088,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Xmi.open(r, opts) local midi, err = Xmi.decode(r, opts) if not midi then @@ -182436,20 +179100,8 @@ return Xmi end __FILES["ops/AudioOps"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an --- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), --- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. --- --- local AudioOps = require("rosetta.ops.AudioOps") -- F.ops.audio in the api --- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder --- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) --- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) --- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) --- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's --- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) --- local both = AudioOps.concat({ a, b }) --- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape --- +-- ops/AudioOps: editing on the standard Audio: collect, gain, normalize, mix, remix, resample (codecs/audio/Resample), +-- trim, concat, fades, peak / RMS. New code. -- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders -- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the -- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot @@ -182465,7 +179117,6 @@ local AudioOps = {} local readf32, writef32 = buffer.readf32, buffer.writef32 local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt --- ------------------------------------------------------------------------------------------------ validation local function isAudio(a) return type(a) == "table" and a.kind == "audio" @@ -182482,7 +179133,6 @@ local function bad(what) return nil, Err.new(Err.ARG, what) end --- a new Audio with a's rate / tags / meta and the given layout local function like(a, channels, frames, rate) local out = Types.Audio.new(rate or a.sampleRate, channels, frames) out.tags = table.clone(a.tags or {}) @@ -182490,9 +179140,6 @@ local out = Types.Audio.new(rate or a.sampleRate, channels, frames) return out end --- ------------------------------------------------------------------------------------------------ conversion --- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT --- past it; default 2^31) function AudioOps.toAudio(v, opts) if isAudio(v) then return v, nil @@ -182505,8 +179152,6 @@ if isAudio(v) then end AudioOps.fromDecoder = AudioOps.toAudio --- ------------------------------------------------------------------------------------------------ levels --- gain(a, factor) -> Audio with every sample times factor function AudioOps.gain(a, factor) if not isAudio(a) then return bad("gain: expected an Audio") @@ -182523,7 +179168,6 @@ if not isAudio(a) then return out, nil end --- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) function AudioOps.gainDb(a, db) if type(db) ~= "number" or db ~= db then return bad("gainDb: dB must be a number") @@ -182531,7 +179175,6 @@ if type(db) ~= "number" or db ~= db then return AudioOps.gain(a, 10 ^ (db / 20)) end --- peak(a) -> the largest |sample|, { per channel } function AudioOps.peak(a) if not isAudio(a) then return nil, Err.new(Err.ARG, "peak: expected an Audio") @@ -182555,7 +179198,6 @@ if not isAudio(a) then return m, per end --- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) function AudioOps.rms(a) if not isAudio(a) then return nil, Err.new(Err.ARG, "rms: expected an Audio") @@ -182579,7 +179221,6 @@ if not isAudio(a) then return sqrt(total / (n * ch)), per end --- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) function AudioOps.normalize(a, target) local p, perr = AudioOps.peak(a) if not p then @@ -182592,7 +179233,6 @@ end return AudioOps.gain(a, (p > 0 and((t / p ))or(1))) end --- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps function AudioOps.fade(a, inSec, outSec) if not isAudio(a) then return bad("fade: expected an Audio") @@ -182623,7 +179263,6 @@ if not isAudio(a) then return out, nil end --- ------------------------------------------------------------------------------------------------ channels -- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) local LAYOUT= { { "C" }, @@ -182642,7 +179281,7 @@ local TO_STEREO= { SR = { 0, H }, BC = { 0.5, 0.5 }, } --- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +-- m[o][i]: output channel o = sum m[o][i] * input i local function matrix(from, to) local m= (table.create(to) ) for o = 1, to do @@ -182733,7 +179372,6 @@ end end end AudioOps.matrix = matrix --- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) function AudioOps.remix(a, channels, m) if not isAudio(a) then return bad("remix: expected an Audio") @@ -182775,7 +179413,6 @@ if not isAudio(a) then return out, nil end --- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) function AudioOps.downmix(a, channels) if not isAudio(a) then return bad("downmix: expected an Audio") @@ -182787,7 +179424,6 @@ if not isAudio(a) then return AudioOps.remix(a, n) end --- upmix(a, channels) -> Audio with more channels function AudioOps.upmix(a, channels) if not isAudio(a) then return bad("upmix: expected an Audio") @@ -182798,8 +179434,6 @@ if not isAudio(a) then return AudioOps.remix(a, channels) end --- ------------------------------------------------------------------------------------------------ time --- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") function AudioOps.resample(a, rate, opts) if not isAudio(a) then return bad("resample: expected an Audio") @@ -182814,7 +179448,6 @@ if not isAudio(a) then return out, nil end --- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) function AudioOps.trim(a, start, stop) if not isAudio(a) then return bad("trim: expected an Audio") @@ -182830,7 +179463,6 @@ if not isAudio(a) then return out, nil end --- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err local function conform(list, what) if type(list) ~= "table" or #list == 0 then return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") @@ -182864,7 +179496,6 @@ if type(list) ~= "table" or #list == 0 then return out, nil end --- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) function AudioOps.concat(list) local items, err = conform(list, "concat") if not items then @@ -182885,8 +179516,6 @@ local items, err = conform(list, "concat") return out, nil end --- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at --- the first one's rate and channel count function AudioOps.mix(list, weights) local items, err = conform(list, "mix") if not items then @@ -182920,17 +179549,8 @@ return AudioOps end __FILES["ops/ImageOps"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion, --- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as --- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and --- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources. --- --- local Ops = require("rosetta.ops.ImageOps") --- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws) --- local grey = Ops.convert(img, "gray8") --- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over" --- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation --- +-- ops/ImageOps: editing on the standard Image: conversion, crop, resize, flips, rotation, compositing, pixel access, +-- animation helpers. New code; the resampling and compositing follow Pillow's C sources. -- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as -- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's -- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and @@ -182944,7 +179564,6 @@ local ImageOps = {} local MAX_PIXELS = 2 ^ 26 --- ------------------------------------------------------------------------------------------------ validation local function arg(msg) @@ -182963,7 +179582,6 @@ if fmt == "yuv420p" then return (bpp and((w * h * bpp ))or(nil ))end --- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough) local function check(img) if type(img) ~= "table" or type(img.pixels) ~= "buffer" then return arg("expected an Image") @@ -182990,7 +179608,6 @@ local max= (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS return true, nil end --- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames local function like(img, w, h, fmt) local out = Types.Image.new(w, h, (fmt or img.format) ) for k, v in __iter(img.meta) do @@ -183000,8 +179617,6 @@ local out = Types.Image.new(w, h, (fmt or img.format) ) return out end --- ------------------------------------------------------------------------------------------------ basics --- new(w, h, format?) -> a zero-filled Image | nil, Err function ImageOps.new(w, h, format) local fmt = format or "rgba8" if not isInt(w) or not isInt(h) or w < 1 or h < 1 then @@ -183017,7 +179632,6 @@ local fmt = format or "rgba8" return Types.Image.new(w, h, fmt ), nil end --- copy(img) -> a deep copy of the pixels (frames are shared) function ImageOps.copy(img) local ok, e = check(img) if not ok then @@ -183029,8 +179643,6 @@ local ok, e = check(img) return out, nil end --- ------------------------------------------------------------------------------------------------ convert --- convert(img, format) -> a new Image in format (a copy when it is already) function ImageOps.convert(img, format) local ok, e = check(img) if not ok then @@ -183079,10 +179691,8 @@ local res, e = f(rgba) return ImageOps.convert(res, "yuv420p") end --- ------------------------------------------------------------------------------------------------ geometry local ALPHA_CH= { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } --- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) function ImageOps.crop(img, x, y, w, h) local ok, e = check(img) if not ok then @@ -183104,7 +179714,6 @@ local out = like(im, x1 - x0, y1 - y0) end) end --- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom) function ImageOps.flip(img, axis) local ok, e = check(img) if not ok then @@ -183120,7 +179729,6 @@ local out = like(im, im.width, im.height) end) end --- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise) function ImageOps.rotate90(img, turns) local ok, e = check(img) if not ok then @@ -183141,7 +179749,6 @@ local swap = t ~= 2 end) end --- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels) function ImageOps.resize(img, w, h, filter, opts) @@ -183196,9 +179803,6 @@ local out = like(im, w, h) end) end --- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's --- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered --- pixels are zero (transparent). opts.maxPixels. function ImageOps.rotate(img, degrees, opts) local ok, e = check(img) if not ok then @@ -183258,12 +179862,8 @@ local out = like(im, nw, nh) end) end --- ------------------------------------------------------------------------------------------------ compositing local RGBA= { rgba8 = true, rgba16 = true, rgbaf32 = true } --- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's --- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite --- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only). function ImageOps.blit(dst, src, x, y, opts) @@ -183286,7 +179886,6 @@ local ok, e = check(dst) if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then return arg("blit: opacity must be 0..1") end - -- clip local sx, sy = math.max(0, -x), math.max(0, -y) local dx, dy = math.max(0, x), math.max(0, y) local w = math.min(src.width - sx, dst.width - dx) @@ -183324,7 +179923,6 @@ end return dst, nil end --- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it function ImageOps.composite(dst, src, x, y, opts) local out, e = ImageOps.copy(dst) if not out then @@ -183347,7 +179945,6 @@ local out, e = ImageOps.copy(img) return out, nil end --- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) function ImageOps.premultiply(img) return premul(img, false) end @@ -183355,11 +179952,8 @@ function ImageOps.unpremultiply(img) return premul(img, true) end --- ------------------------------------------------------------------------------------------------ pixels local MAXV= { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } --- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; --- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. function ImageOps.getPixel(img, x, y) local ok, e = check(img) if not ok then @@ -183399,8 +179993,6 @@ local j = ((y % 2) * rgba.width + (x % 2)) * 4 return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 end --- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and --- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p. function ImageOps.setPixel(img, x, y, r, g, b, a) local ok, e = check(img) if not ok then @@ -183467,7 +180059,6 @@ if max == 1 then return true, nil end --- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) function ImageOps.fill(img, r, g, b, a) local ok, e = check(img) if not ok then @@ -183491,8 +180082,6 @@ local n = img.width * img.height * bpp return img, nil end --- ------------------------------------------------------------------------------------------------ animation --- frameCount(img) -> the number of frames (1 for a still image) function ImageOps.frameCount(img) if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then return #img.frames @@ -183500,7 +180089,6 @@ if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then return 1 end --- durations(img) -> { seconds } per frame ({ 0 } for a still image) function ImageOps.durations(img) local out = {} if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then @@ -183512,10 +180100,7 @@ local out = {} return { 0 } end --- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 / --- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's --- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores --- the canvas from before the frame). A still image gives { img }. +-- coalesce: dispose "none" keeps the canvas, "background" clears the frame's rectangle, "previous" restores it function ImageOps.coalesce(img) local ok, e = check(img) if not ok then @@ -183571,9 +180156,6 @@ local out = {} return out, nil end --- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, --- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds } --- (default 0.1). All images need the same size and format. function ImageOps.fromFrames(images, delays) if type(images) ~= "table" or #images == 0 then return arg("fromFrames: a non-empty list of Images") @@ -183613,12 +180195,9 @@ __FILES["ops/ImageOps/Kernels"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller --- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by --- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers). --- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by --- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through --- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c. +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps; callers validate, so indexes are in range by construction. +-- Sample kinds: 1 = u8, 2 = u16, 4 = f32 (little endian). Resampling follows Pillow's Resample.c (separable, 22-bit +-- fixed point for 8-bit) and Geometry.c (affine through pixel centres); compositing is Pillow's AlphaComposite.c. local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 local floor, clamp = math.floor, math.clamp @@ -183648,7 +180227,6 @@ local function wr(b, o, kind, v) end end --- ------------------------------------------------------------------------------------------------ convert -- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } @@ -183667,7 +180245,6 @@ if from == to then ) end return v / 65535 end - -- float if v ~= v then v = 0 end @@ -183813,8 +180390,6 @@ function K.yuvToRgba(src, w, h, dst) local _ = ch end --- ------------------------------------------------------------------------------------------------ geometry --- flip(src, dst, w, h, bpp, horizontal) function K.flip(src, dst, w, h, bpp, horizontal) local stride = w * bpp if not horizontal then @@ -183831,7 +180406,7 @@ function K.flip(src, dst, w, h, bpp, horizontal) end end --- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3 +-- counter-clockwise quarter turns 1..3 function K.rotate90(src, dst, w, h, bpp, turns) for y = 0, h - 1 do for x = 0, w - 1 do @@ -183853,7 +180428,6 @@ function K.rotate90(src, dst, w, h, bpp, turns) end end --- ------------------------------------------------------------------------------------------------ resample local function bilinearF(x) if x < 0 then x = -x @@ -183915,7 +180489,6 @@ for xx = 0, outSize - 1 do return { start = start, count = count, weights = weights } end --- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind. function K.resamplePass(src, w, h, ch, kind, dst, outN, c, horizontal) local start, count, weights = c.start, c.count, c.weights local size = kind @@ -183995,8 +180568,8 @@ function K.nearest(src, w, h, bpp, dst, ow, oh) end end --- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src --- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow) +-- affine: dst pixel centres through m = { a, b, c, d, e, f } (xin = a x + b y + c), bilinear with clamped +-- neighbours; centres outside the source -> zeros (Pillow) function K.affine(src, w, h, ch, kind, dst, ow, oh, m) local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] local size = kind @@ -184033,8 +180606,7 @@ __DARKLUA_CONTINUE_32=true until true if not __DARKLUA_CONTINUE_32 then break en end end --- ------------------------------------------------------------------------------------------------ compositing --- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place +-- Pillow's alpha_composite of src onto dst, in place function K.overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity) for y = 0, h - 1 do for x = 0, w - 1 do @@ -184087,14 +180659,12 @@ __DARKLUA_CONTINUE_38=true until true if not __DARKLUA_CONTINUE_38 then break en end end --- copyRect: rows of a rectangle (bpp bytes per pixel) function K.copyRect(dst, dw, src, sw, sx, sy, dx, dy, w, h, bpp) for y = 0, h - 1 do buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) end end --- premultiply / unpremultiply in place: ch channels, alpha last, kind function K.premultiply(b, n, ch, kind, un) local max = kind == 1 and 255 or(kind == 2 and 65535 or 1 ) local px = ch * kind @@ -184136,13 +180706,6 @@ local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat -- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an -- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and -- grey layer masks; every frame as an animated Image; walking the leaves. --- --- local LayerOps = require("rosetta.ops.LayerOps") --- local img = LayerOps.flatten(layered) -- frame 1 / the layers --- local img3 = LayerOps.flatten(layered, { frame = 3 }) --- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) --- for layer, depth in LayerOps.leaves(layered.layers) do ... end --- -- Never throws: bad values return nil, Err.ARG. local Err = __include("core/Err") local Types = __include("Types") @@ -184150,7 +180713,6 @@ local Blend = __include("codecs/image/Blend") local LayerOps = {} --- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err @@ -184188,7 +180750,6 @@ if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.h return img, nil end --- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) function LayerOps.flattenFrames(layered, opts) local first, err = LayerOps.flatten(layered, opts) if not first then @@ -184212,7 +180773,6 @@ o.frame = i return first, nil end --- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top function LayerOps.leaves(layers) local stack= { { layers, 0, 0 } } return function() @@ -184236,18 +180796,9 @@ return LayerOps end __FILES["ops/MeshOps"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear --- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), --- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an --- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis --- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). --- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type --- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). --- --- local MeshOps = require("rosetta.ops.MeshOps") -- F.ops.mesh in the api (when it lists ops) --- local prim = MeshOps.merge(scene) -- one triangle primitive in world space --- MeshOps.computeNormals(prim) --- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +-- ops/MeshOps: editing meshes in the standard Scene type: triangulate, transform, normals (area weighted or flat), +-- tangents (Lengyel 2001), weld, bounds, merge into world space, unit / up-axis changes, greedy voxel meshing. Inputs +-- may use any accessor type; outputs are f32 attributes and u32 indices. Never throws. local Err = __include("core/Err") local Types = __include("Types") local Greedy = __include("ops/MeshOps/Greedy") @@ -184262,8 +180813,6 @@ local Scene = Types.Scene local readf32, writef32 = buffer.readf32, buffer.writef32 local readu32, writeu32 = buffer.readu32, buffer.writeu32 --- ------------------------------------------------------------------------------------------------ accessors --- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one function MeshOps.f32(acc) if acc.type == "f32" then return acc @@ -184284,7 +180833,6 @@ if acc.type == "f32" then return a end --- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 local function indexBuffer(prim) local ind = prim.indices if ind then @@ -184351,7 +180899,6 @@ if type(prim) ~= "table" or type(prim.attributes) ~= "table" then end MeshOps.check = checkPrim --- ------------------------------------------------------------------------------------------------ triangulate -- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck local function earclip(poly, P, out) local k = #poly @@ -184443,9 +180990,7 @@ local n = #list return Scene.accessor(b, "u32", 1, n) end --- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" --- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). --- Lines and points come back unchanged. +-- strips and fans unroll with glTF's alternating strip winding function MeshOps.triangulate(prim, opts) local err = checkPrim(prim) if err then @@ -184531,7 +181076,6 @@ for a = 0, k - 1 do }, nil end --- ------------------------------------------------------------------------------------------------ transform local function det3(m) return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) end @@ -184554,8 +181098,7 @@ local a, b, c = m[1], m[5], m[9] } end --- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). --- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +-- a mirroring matrix (negative determinant) reverses the winding so faces stay front-facing function MeshOps.transform(prim, m) local err = checkPrim(prim) if err then @@ -184660,10 +181203,6 @@ attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) return prim, nil end --- ------------------------------------------------------------------------------------------------ normals / tangents --- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | --- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle --- modes are triangulated first (the returned primitive is then a new one). function MeshOps.computeNormals(prim, opts) local p = prim if (prim.mode or "triangles") ~= "triangles" then @@ -184719,8 +181258,7 @@ end end return p, nil end --- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | --- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_<opts.texCoord or 0>. +-- TANGENT: f32 vec4, xyz orthogonal to the normal, w = +-1 handedness function MeshOps.computeTangents(prim, opts) local p = prim if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then @@ -184802,7 +181340,6 @@ end end return p, nil end --- ------------------------------------------------------------------------------------------------ weld / unweld local function gather(acc, ib, n) local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components local out = buffer.create(n * size) @@ -184814,7 +181351,6 @@ local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components return a end --- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) function MeshOps.unweld(prim) local ib, n = indexBuffer(prim) local attrs = {} @@ -184835,10 +181371,6 @@ local ib, n = indexBuffer(prim) return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } end --- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. --- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other --- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). --- Morph targets are kept per merged vertex (the first one's). function MeshOps.weld(prim, opts) local err = checkPrim(prim) if err then @@ -184917,9 +181449,6 @@ local pd = pos.data }, nil end --- ------------------------------------------------------------------------------------------------ bounds --- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and --- voxel shape cell corners excluded) | nil, nil when there are no positions function MeshOps.bounds(x) local lo = { math.huge, math.huge, math.huge } local hi = { -math.huge, -math.huge, -math.huge } @@ -184973,7 +181502,6 @@ local lo = { math.huge, math.huge, math.huge } return lo, hi end --- ------------------------------------------------------------------------------------------------ merge -- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) local function defaultFor(name, k) if string.sub(name, 1, 6) == "COLOR_" then @@ -184985,11 +181513,6 @@ if string.sub(name, 1, 6) == "COLOR_" then return 0 end --- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | --- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input --- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. --- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets --- are not applied (the rest pose). function MeshOps.merge(input, opts) local placed= {} if type(input) ~= "table" then @@ -185002,7 +181525,6 @@ local placed= {} placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } end end - -- triangulate + bake each local groups= {} local order= {} local allPoints = #placed > 0 @@ -185098,7 +181620,6 @@ local names= {} return concat(all, first and first.material), nil end --- ------------------------------------------------------------------------------------------------ units / up axis local function scaleAccessor(acc, f) if not acc then return nil @@ -185114,9 +181635,6 @@ if a == acc then return a end --- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and --- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by --- factor (the same physical size in smaller units). function MeshOps.scale(scene, f) if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") @@ -185193,7 +181711,6 @@ if a == ibm then return scene, nil end --- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) function MeshOps.setUnit(scene, metresPerUnit) if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") @@ -185202,8 +181719,6 @@ if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= return MeshOps.scale(scene, from / metresPerUnit) end --- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. --- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). function MeshOps.setUp(scene, up) if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") @@ -185221,17 +181736,12 @@ if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") return scene, nil end --- ------------------------------------------------------------------------------------------------ voxels local function linear(c) local s = c / 255 return (s <= 0.04045 and((s / 12.92 ))or((((s + 0.055) / 1.055) ^ 2.4 )))end --- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, --- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. --- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); --- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or --- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +-- pivot "center": MagicaVoxel's placement (cell x spans x - floor(sx / 2) ..) function MeshOps.voxelsToPrimitive(v, opts) if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a Voxels grid") @@ -185288,9 +181798,6 @@ local out = buffer.create(size) return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil end --- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node --- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as --- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids). function MeshOps.meshVoxels(scene, opts) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, Err.new(Err.ARG, "expected a Scene") @@ -185336,7 +181843,7 @@ local Greedy = {} local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 --- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale +-- vertex position = (cell corner + (ox, oy, oz)) * scale @@ -185415,7 +181922,6 @@ local cap = 1024 writei32(mask, (i + k + jj * nu) * 4, 0) end end - -- emit the rectangle if quads == cap then local ncap = cap * 2 local function grow2(b, per) @@ -185430,7 +181936,6 @@ cap = ncap corner[u + 1] = i corner[v + 1] = j local cx, cy, cz = corner[1], corner[2], corner[3] - -- the u and v edge vectors local ux = (u == 0 and{w }or{0 })[1] local uy = (u == 1 and{w }or{0 })[1] local uz = (u == 2 and{w }or{0 @@ -185494,18 +181999,8 @@ return Greedy end __FILES["ops/MusicOps"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the --- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, --- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / --- addInstrument / note in the api (also F.ops.music). --- --- local M = require("rosetta.ops.MusicOps") --- local song = M.new({ format = "mod", channels = 4, title = "demo" }) --- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 --- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list --- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) --- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod --- +-- ops/MusicOps: building and editing tracker Modules over codecs/audio/Tracker without touching the engine's internal +-- layout (5-byte cells, f32 samples, tuning fields). New code. -- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample -- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 -- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering @@ -185529,8 +182024,6 @@ end local function int(v, lo, hi) return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi end --- ------------------------------------------------------------------------------------------------ module --- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format @@ -185568,9 +182061,6 @@ local o= opts or {} return m, nil end --- ------------------------------------------------------------------------------------------------ patterns --- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). --- The pattern is appended to the order list unless opts.order == false. function MusicOps.addPattern(m, rows, opts) if not isModule(m) then return bad("addPattern: needs a tracker Module") @@ -185590,8 +182080,6 @@ end local NAMES= { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } local SPECIAL= { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } --- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, --- "Db4" = 50, "off", "cut", "fade" function MusicOps.note(v) if type(v) == "number" then if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then @@ -185643,7 +182131,6 @@ if not isModule(m) then return p, nil end --- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) function MusicOps.setCell(m, pattern, row, channel, cell) local p, err = patternAt(m, pattern, row, channel) if not p then @@ -185670,7 +182157,6 @@ local p, err = patternAt(m, pattern, row, channel) return true, nil end --- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err function MusicOps.getCell(m, pattern, row, channel) local p, err = patternAt(m, pattern, row, channel) if not p then @@ -185679,7 +182165,6 @@ local p, err = patternAt(m, pattern, row, channel) local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil end --- ------------------------------------------------------------------------------------------------ samples @@ -185698,9 +182183,8 @@ end local LOOPS= { none = 0, forward = 1, pingpong = 2 } --- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for --- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, --- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). +-- tuning: c5speed for S3M / IT; relativeNote + finetune (1/128 semitone from 8363 Hz) for MOD / XM (MOD stores +-- only the finetune, -1..+7/8 semitone) function MusicOps.addSample(m, spec) if not isModule(m) then return bad("addSample: needs a tracker Module") @@ -185777,10 +182261,8 @@ local rate = spec.rate table.insert(m.samples, s) return #m.samples, nil end --- ------------------------------------------------------------------------------------------------ instruments --- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / --- S3M cells name samples directly). +-- instruments: XM and IT only (MOD / S3M cells name samples directly) @@ -185865,18 +182347,9 @@ return MusicOps end __FILES["playlist/m3u"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no --- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain --- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / --- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media --- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, --- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base --- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, --- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. --- --- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) --- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" --- local out = M3u.encode(pl, { title = "My Mix" }) +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists, absorbed from playlist-luau 3fc7fd3 (same author). Supports: +-- #EXTM3U / #EXTINF / #PLAYLIST, plain lists, BOM, CRLF / CR, Windows-1252, HLS master and media playlists; locations +-- resolve per RFC 3986; mp3 HLS segments are playable, .ts / .aac / fMP4 are flagged. Not supported: writing HLS tags. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -185936,12 +182409,10 @@ local M3u = { - local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } --- The extension of a URL's path (lower case), or nil local function extension(url) local p = Url.split(url).path local ext = string.match(p, "%.([%w]+)$") @@ -186167,7 +182638,6 @@ __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function M3u.decode(r, opts) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -186192,8 +182662,6 @@ local n = r.limit - r.pos end -- ------------------------------------------------------------------------------------------------ encode --- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1. --- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. local function serialize(entries, opts) local out = { "#EXTM3U" } local function clean(s) @@ -186216,8 +182684,6 @@ __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end return table.concat(out, "\n") .. "\n" end --- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of --- entries ({ url, title?, duration? }) function M3u.encode(value, opts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -186234,14 +182700,9 @@ return M3u end __FILES["playlist/pls"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case --- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a --- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / --- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. --- --- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) --- local out = Pls.encode(pl) +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version), absorbed from +-- playlist-luau 3fc7fd3 (same author) plus a new writer. Supports: keys in any case / order, comments, BOM, CRLF / CR, +-- Windows-1252, numbering gaps; locations resolve per RFC 3986. Encode: Version=2, Length -1 for unknown durations. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186298,7 +182759,6 @@ local Pls = { - local function duration(s) @@ -186364,7 +182824,6 @@ __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function Pls.decode(r, opts) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -186388,8 +182847,6 @@ local n = r.limit - r.pos end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a --- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. function Pls.encode(value, _opts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -186421,17 +182878,9 @@ return Pls end __FILES["playlist/xspf"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau --- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, --- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, --- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; --- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other --- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- playlist/xspf: XSPF 1 (https://xspf.org/spec) playlists on codecs/text/Xml. Supports: playlist and track metadata, +-- every track location (entry.locations), duration (ms), xml:base then opts.baseUrl (RFC 3986). -- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. --- --- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) --- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end --- local out = Xspf.encode(pl) -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186465,7 +182914,6 @@ local function trim(s) return ((string.match(s, "^%s*(.-)%s*$") )) end --- the text of the first child element with this local name, trimmed (nil when missing or empty) local function field(node, name) for _, c in __iter(node.children) do if type(c) == "table" and Xml.localName(c.name) == name then @@ -186497,8 +182945,6 @@ local s = r:peek(1024) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd --- tracks become warnings) function Xspf.decode(r, opts) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -186583,8 +183029,6 @@ local xb = node.attrs and node.attrs["xml:base"] end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list --- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. function Xspf.encode(value, opts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") @@ -186637,16 +183081,9 @@ return Xspf end __FILES["subtitle/ass"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of --- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] --- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the --- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any --- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. --- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become --- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. --- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, --- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: --- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. +-- subtitle/ass: ASS (v4.00+) / SSA (v4.00) scripts (de-facto spec of Aegisub / libass / ffmpeg). Supports: Script +-- Info, Styles, Events (Dialogue / Comment), other sections verbatim, H:MM:SS.cc; {\i1} {\b1} {\u1} {\s1} as the shared +-- markup (cue.raw keeps the original). Not supported: rendering, karaoke timing (\k), embedded font / graphic decoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -186701,7 +183138,6 @@ local STYLE_DEFAULT= { Encoding = "0", } local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } --- event fields -> cue keys (the rest keep their field name) local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } local function trim(s) @@ -186716,7 +183152,6 @@ local out = {} return out end --- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil local function time(s) local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") if not h then @@ -186726,7 +183161,6 @@ local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") )) return (tonumber(h) )* 3600 + (tonumber(m) )* 60 + (tonumber(sec) )+ fr end --- ASS text -> the shared markup local TAGS = { i = "i", b = "b", u = "u", s = "s" } function Ass.toMarkup(raw) local open= {} @@ -186767,7 +183201,6 @@ local acc = {} return out end --- the shared markup -> ASS text function Ass.fromMarkup(text) local s = string.gsub(text, "\r\n?", "\n") s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close, tag) @@ -186830,7 +183263,7 @@ __DARKLUA_CONTINUE_5=true break end if section == "script info" then if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then - table.insert(infoOrder, line) -- a comment line, kept in place + table.insert(infoOrder, line) -- `;` / `!` comment line, kept in place else local k, v = string.match(line, "^([^:]+):%s?(.*)$") if k then @@ -186903,7 +183336,7 @@ for fi = 1, #eventFormat do end if ok then if k == "Comment" then - cue.after = #subs.cues -- written back after that many dialogue lines + cue.after = #subs.cues table.insert(comments, cue) else table.insert(subs.cues, cue ) @@ -186924,7 +183357,6 @@ __DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end subs.meta.comments = comments end if #sections > 0 then - -- drop trailing blank lines (the writer adds its own) for _, sec in __iter(sections) do while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do table.remove(sec.lines) @@ -186974,7 +183406,6 @@ if type(subs) ~= "table" or type(subs.cues) ~= "table" then end table.sort(rest) table.move(rest, 1, #rest, #out + 1, out) - -- styles local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" local sfmt= (type(meta.styleFormat) == "table" and{meta.styleFormat }or{STYLE_FORMAT })[1] table.insert(out, "") @@ -187012,7 +183443,6 @@ if type(subs) ~= "table" or type(subs.cues) ~= "table" then end table.insert(out, "Style: " .. table.concat(vals, ",")) end - -- events local efmt= (type(meta.eventFormat) == "table" and{meta.eventFormat }or{EVENT_FORMAT })[1] if efmt[#efmt] ~= "Text" then return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") @@ -187095,13 +183525,9 @@ return Ass end __FILES["subtitle/srt"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or --- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing --- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends --- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / --- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. --- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. --- Not supported: positioning beyond keeping the coordinates; the tags are not validated. +-- subtitle/srt: SubRip text (de-facto; matches ffmpeg's srt demuxer / muxer). Supports: numbered or unnumbered +-- cues, `,` / `.` decimals, X1/Y1 coordinates (cue.settings), inner blank lines, BOM, CRLF / CR; text kept as is. +-- Not supported: positioning beyond keeping the coordinates; tags are not validated. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -187129,7 +183555,6 @@ local Srt = { local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" --- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) local function text(r) local s = buffer.readstring(r.buf, r.base, r.limit - r.base) if string.find(s, "\0", 1, true) then @@ -187145,7 +183570,6 @@ local function frac(digits) return ((tonumber(digits) )) / 10 ^ #digits end --- timing(line) -> start, stop, settings | nil local function timing(line) local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) if not h1 then @@ -187208,7 +183632,7 @@ local l = lines[k] while i <= n do local l = lines[i] if string.match(l, "^%s*$") then - -- blank: the end of the cue unless more text follows before the next cue + -- a blank line ends the cue only before the next index / timing line local k = i while k <= n and string.match(lines[k], "^%s*$") do k =k+ 1 @@ -187221,7 +183645,7 @@ local l = lines[k] end i = k elseif timing(l) then - break -- a cue without the blank separator + break else table.insert(body, l) i =i+ 1 @@ -187263,7 +183687,6 @@ if type(subs) ~= "table" or type(subs.cues) ~= "table" then if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") end - -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue local body = string.gsub(c.text, "\r\n?", "\n") local settings = (type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") and((" " .. c.settings ))or("" )) out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl @@ -187275,12 +183698,9 @@ return Srt end __FILES["subtitle/vtt"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in --- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments --- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept --- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). --- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text --- are dropped and `-->` escaped (WebVTT cue text cannot hold them). +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the header (meta.header), cue ids, `[hh:]mm:ss.ttt` timings, +-- cue settings, NOTE (meta.notes), STYLE (meta.css) and REGION (meta.regions) blocks, BOM, CRLF / CR; cue text as +-- written. Encode drops blank lines in cue text and escapes `-->` (cue text cannot hold them). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -187308,7 +183728,6 @@ local function frac(digits) return ((tonumber(digits) )) / 10 ^ #digits end --- one timestamp at the start of s: seconds, the rest | nil local function timestamp(s) local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") if h then @@ -187321,7 +183740,6 @@ end return nil, s end --- timing(line) -> start, stop, settings | nil local function timing(line) local a, rest = timestamp((string.gsub(line, "^%s+", ""))) if not a then @@ -187386,7 +183804,6 @@ local __DARKLUA_CONTINUE_2=false repeat if lines[i] == "" then i =i+ 1 __DARKLUA_CONTINUE_2=true break end - -- a block: lines up to the next blank local first = i while i <= n and lines[i] ~= "" do i =i+ 1 @@ -187436,7 +183853,6 @@ local ms = math.floor(t * 1000 + 0.5) return string.format("%02d:%02d:%02d.%03d", math.floor(ms / 3600000), math.floor(ms / 60000 )% 60, math.floor(ms / 1000 )% 60, ms % 1000) end --- one block's text: no blank lines (they end a block), no `-->` local function clean(s) s = string.gsub(s, "\r\n?", "\n") s = string.gsub(s, "\n[ \t]*\n", "\n") @@ -187485,17 +183901,9 @@ return Vtt end __FILES["vector/svg"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs --- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg --- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from --- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / --- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and --- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path --- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). --- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and --- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. --- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also --- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. +-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms, +-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported +-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -187563,8 +183971,6 @@ local s, err = Write.vector(v) end -- ------------------------------------------------------------------------------------------------ extras --- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox --- maps onto w x h by its preserveAspectRatio. function Svg.rasterize(v, w, h, opts) if type(v) ~= "table" or type(v.paths) ~= "table" then return nil, Err.new(Err.ARG, "needs a Vector value") @@ -187581,13 +183987,7 @@ return Svg end __FILES["vector/svg/Parse"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, --- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space --- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into --- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a --- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. --- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. --- Never throws. +-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips. local Xml = __include("codecs/text/Xml") local Types = __include("Types") local Style = __include("vector/svg/Style") @@ -187672,7 +184072,7 @@ if s == nil then return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") end --- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +-- cascade: presentation attributes < CSS rules (by specificity, then order) < style="" local function specified(n, ctx) local out= {} for k, v in pairs(n.attrs ) do @@ -187712,7 +184112,6 @@ if a.selector.specificity ~= b.selector.specificity then return out end --- computed(parent, n) -> the element's computed property strings local function computed(parent, n, ctx) local out= {} for k in pairs(INHERITED) do @@ -187770,7 +184169,6 @@ local list = {} return list end --- a gradient attribute, looked up through href templates local function gattr(g, k, ctx) local cur= g local guard = 0 @@ -187832,7 +184230,6 @@ local v = gattr(g, k, ctx) or default return p end --- paint(value, opacity, st) -> Paint | nil (none) local function paint(value, opacity, st, ctx) if value == nil then return nil @@ -187952,7 +184349,6 @@ local t = attr(n, "transform") return IDENTITY end --- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. local function clip(ref, ctm, bbox, st, ctx) local cp = ctx.ids[ref] if cp == nil or local_(cp) ~= "clipPath" then @@ -188090,7 +184486,6 @@ if sw <= 0 then table.insert(ctx.vector.paths, p) end --- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) function Parse.viewTransform(vb, par, x, y, w, h) if vb == nil or vb[3] <= 0 or vb[4] <= 0 then return { 1, 0, 0, 1, x, y } @@ -188135,7 +184530,6 @@ local v = Style.numbers(attr(n, "viewBox")) end local function container(n, st, ctm, group, ctx, children) - -- a layer for opacity / clip-path local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) local clipRef = refId(st["clip-path"]) local g = group @@ -188145,7 +184539,6 @@ local function container(n, st, ctm, group, ctx, children) local bbox= nil local cp = ctx.ids[clipRef] if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then - -- the group's bounding box in its user space: walk once into a scratch vector local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips local scratch = Types.Vector.new(0, 0) ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} @@ -188192,7 +184585,7 @@ local function container(n, st, ctm, group, ctx, children) end end --- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +-- nested svg / symbol: overflow is hidden unless it says otherwise local function viewportGroup(n, m, x, y, w, h, group, ctx) local ov = attr(n, "overflow") if ov == "visible" or ov == "auto" then @@ -188280,7 +184673,6 @@ local vb = viewBox(n) end -- ------------------------------------------------------------------------------------------------ entry --- document(doc, opts) -> Vector | nil, message function Parse.document(doc) local root = doc.root if root == nil or Xml.localName(root.name) ~= "svg" then @@ -188341,11 +184733,8 @@ return Parse end __FILES["vector/svg/PathData"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands --- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the --- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a --- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the --- commands so far are kept, as the spec's error handling says). +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes +-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says). local PathData = {} @@ -188355,7 +184744,6 @@ local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } --- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out local function arc(x1, y1, rx, ry, phiDeg, fa, fs, x2, y2, out) if x1 == x2 and y1 == y2 then return @@ -188423,14 +184811,13 @@ x, y = x * rx, y * ry end PathData.arc = arc --- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) function PathData.parse(d) local out= {} local i, n = 1, #d - local cx, cy = 0, 0 -- current point - local sx, sy = 0, 0 -- subpath start - local lcx, lcy = 0, 0 -- last control point (for S / T) - local last = "" -- previous command letter (upper case) + local cx, cy = 0, 0 + local sx, sy = 0, 0 + local lcx, lcy = 0, 0 + local last = "" local cmd= nil local rel = false local nums= (table.create(7) ) @@ -188591,15 +184978,12 @@ __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end return out, true end --- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box --- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves function PathData.bounds(cmds) local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge local px, py = 0, 0 for _, c in __iter(cmds) do local op = c.op if op == "C" then - -- the curve's exact extrema local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] for axis = 1, 2 do local p0 = (axis == 1 and{px }or{py @@ -188670,7 +185054,6 @@ local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge return x0, y0, x1, y1 end --- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) local function num(v) if v ~= v or v == math.huge or v == -math.huge then return "0" @@ -188685,7 +185068,6 @@ if v ~= v or v == math.huge or v == -math.huge then end PathData.num = num --- serialize(cmds) -> path data text function PathData.serialize(cmds) local out = {} for _, c in __iter(cmds) do @@ -188702,7 +185084,6 @@ local out = {} return table.concat(out, " ") end --- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } function PathData.toRaster(cmds) local out = table.create(#cmds) @@ -188720,11 +185101,7 @@ return PathData end __FILES["vector/svg/Render"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, --- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and --- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, --- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox --- maps onto the image by meta.preserveAspectRatio. Never throws. +-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend. local Types = __include("Types") local Raster = __include("codecs/image/Raster") local Blend = __include("codecs/image/Blend") @@ -188763,7 +185140,6 @@ local n = #stops return s[2], s[3], s[4], s[5] end --- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds local function gradientFn(p, device, bbox) local stops = p.stops if type(stops) ~= "table" or #stops == 0 then @@ -188849,7 +185225,6 @@ local gx, gy = a * x + c * y + e, b * x + d * y + f end -- ------------------------------------------------------------------------------------------------ dashes --- subpaths of a command list with their closed flag local function subpaths(cmds) local out = {} local cur= nil @@ -188872,7 +185247,6 @@ local out = {} return out end --- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) local function polyline(cmds, tol) local pts= {} local px, py = 0, 0 @@ -188988,7 +185362,6 @@ __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end return out end -- ------------------------------------------------------------------------------------------------ rendering --- the device transform scale (for stroke flattening tolerances) @@ -188999,7 +185372,6 @@ local function scaleOf(m) return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) end --- rasterize(v, w, h, opts?) -> rgba8 Image function Render.rasterize(v, w, h, opts) local o= opts or {} local img = Types.Image.new(w, h) @@ -189018,7 +185390,6 @@ local o= opts or {} })[1] local clips= (type(meta.clips) == "table" and{meta.clips }or{{} })[1] local tol = o.tolerance or 0.1 local clipCache= {} - -- a clip's coverage over the whole image (1 byte per pixel) local function clipMask(id) if clipCache[id] then return clipCache[id] @@ -189046,7 +185417,6 @@ if clipCache[id] then clipCache[id] = mask return mask end - -- the layer stack: { group id, image } local stack= { { id = nil, img = img } } local function chain(g) local out = {} @@ -189086,7 +185456,6 @@ if paint.type == "color" then local __DARKLUA_CONTINUE_18=false repeat if type(p) ~= "table" or type(p.d) ~= "table" then __DARKLUA_CONTINUE_18=true break end - -- groups: pop the layers this path is not in, push the ones it needs local want = chain(p.group) local keep = 1 while keep < #stack and stack[keep + 1].id == want[keep] do @@ -189149,11 +185518,7 @@ return Render end __FILES["vector/svg/Style"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / --- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), --- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated --- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). --- Never throws. +-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset. local Raster = __include("codecs/image/Raster") local Style = {} @@ -189207,7 +185572,6 @@ t =t% 1 return p end --- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value function Style.color(s, current) s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) if s == "none" then @@ -189286,7 +185650,7 @@ if p == nil then return nil end --- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +-- SVG number: sign? digits? ("." digits)? exponent? local function scan(s, i) local n = #s local st = i @@ -189344,7 +185708,6 @@ local n = #s return tonumber(string.sub(s, st, i - 1)), i end --- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) local UNITS= { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } function Style.length(s, ref, fontSize) if s == nil then @@ -189369,7 +185732,6 @@ local x, j = scan(t, 1) return (k and((x * k ))or(nil ))end --- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else function Style.numbers(s) local out = {} if s == nil then @@ -189392,7 +185754,6 @@ local out = {} return out end --- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error local mul = Raster.multiply Style.multiply = mul function Style.transform(s) @@ -189435,7 +185796,6 @@ if name == "matrix" and #v == 6 then return m end --- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) function Style.declarations(s) local out= {} for decl in __iter(string.gmatch(s, "[^;]+")) do @@ -189483,7 +185843,6 @@ end return sel end --- css(text, rules?) -> rules (appended to the list given) function Style.css(text, rules) local out= rules or {} text = string.gsub(text, "/%*.-%*/", "") @@ -189512,7 +185871,6 @@ local out= rules or {} return out end --- matches(sel, tag, id, classes) -> boolean function Style.matches(sel, tag, id, classes) if sel.tag and sel.tag ~= tag then return false @@ -189532,9 +185890,7 @@ return Style end __FILES["vector/svg/Write"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients --- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> --- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message). local Xml = __include("codecs/text/Xml") local Types = __include("Types") local PathData = __include("vector/svg/PathData") @@ -189574,7 +185930,6 @@ if type(m) ~= "table" or #m < 6 then return "matrix(" .. table.concat(parts, " ") .. ")" end --- write(v) -> SVG text | nil, message function Write.vector(v) if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then return nil, "needs a Vector value" @@ -189584,7 +185939,6 @@ if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" o })[1] local clips= (type(meta.clips) == "table" and{meta.clips }or{{} })[1] local defs = {} local gradients = 0 - -- paints -> attribute values (gradients go to defs) local function paintAttrs(p, which) if type(p) ~= "table" then return { { which, "none" } } @@ -189642,7 +185996,6 @@ if id == nil or type(clips[id]) ~= "table" then return "url(#" .. clipIds[id] .. ")" end local root = {} - -- the open <g> stack: { id, children } local stack= { { id = nil, kids = root } } local function chain(g) local out = {} @@ -189737,16 +186090,9 @@ return Write end __FILES["vector/tiled"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map --- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / --- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, --- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, --- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets --- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay --- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the --- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". --- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external --- tilesets or images (callers resolve `source` / `imageSource` paths themselves). +-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON +-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties, +-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -189810,8 +186156,6 @@ local h = head(r) end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its --- meta.tileset is true) | nil, Err function Tiled.decode(r, opts) local maxBytes = opts and opts.maxBytes or 2 ^ 28 if r.limit - r.base > maxBytes then @@ -189926,14 +186270,12 @@ return Tiled end __FILES["vector/tiled/Data"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) --- to gids and back; property values and their types; number formatting. Never throws. +-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers. local Base64 = __include("core/Base64") local Deflate = __include("codecs/compress/Deflate") local Data = {} --- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message function Data.csv(text) local out = {} for tok in __iter(string.gmatch(text, "[^,%s]+")) do @@ -189946,7 +186288,6 @@ local out = {} return out, nil end --- base64(text, compression) -> { gid } | nil, message, unsupported? function Data.base64(text, compression) local raw, err = Base64.decode(text) if not raw then @@ -189976,7 +186317,6 @@ for i = 0, n - 1 do return out, nil, nil end --- toBase64(gids, compression?, level?) -> text | nil, message function Data.toBase64(gids, compression, level) local b = buffer.create(#gids * 4) for i, g in __iter(gids) do @@ -190000,7 +186340,7 @@ local b = buffer.create(#gids * 4) return Base64.encode(b), nil end --- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print function Data.num(v) if v % 1 == 0 and math.abs(v) < 2 ^ 53 then return string.format("%.0f", v) @@ -190012,7 +186352,7 @@ if v % 1 == 0 and math.abs(v) < 2 ^ 53 then return s end --- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +-- Tiled's CSV layout: one row per line function Data.csvText(gids, width) local rows = {} local row = {} @@ -190029,7 +186369,7 @@ local rows = {} return "\n" .. table.concat(rows, ",\n") .. "\n" end --- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque function Data.color(s) if type(s) ~= "string" then return nil @@ -190041,7 +186381,6 @@ if type(s) ~= "string" then return "#" .. h end --- property values: TMX / TMJ type names -> a Luau value from text function Data.value(typ, text) if typ == "int" or typ == "float" or typ == "object" then return tonumber(text) or 0 @@ -190053,7 +186392,6 @@ if typ == "int" or typ == "float" or typ == "object" then return text end --- typeOf(v, declared?) -> the Tiled type to write for v function Data.typeOf(v, declared) if declared then return declared @@ -190068,7 +186406,6 @@ if declared then return "string" end --- sortedKeys(t) -> its string keys, sorted function Data.sortedKeys(t) local out = {} for k in pairs(t) do @@ -190084,8 +186421,7 @@ return Data end __FILES["vector/tiled/Tmj"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ --- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap. local Types = __include("Types") local Data = __include("vector/tiled/Data") @@ -190330,7 +186666,6 @@ if type(v) ~= "table" then return nil, "unknown layer type " .. tostring(v.type) end --- tileset(v) -> Tileset (a map's entry, or a .tsj root) function Tmj.tileset(v) local ts= { firstGid = n(v.firstgid, 1), @@ -190382,7 +186717,6 @@ return x.id < y.id return ts end --- read(value) -> TileMap | nil, message, unsupported? function Tmj.read(v) if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then return nil, "not a Tiled map (type is not \"map\")" @@ -190620,7 +186954,6 @@ if enc == "base64" then return obj(fields), nil end --- tilesetValue(ts, inMap) -> a JSON object function Tmj.tilesetValue(ts, inMap) if inMap and type(ts.source) == "string" then return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -190675,7 +187008,6 @@ if inMap and type(ts.source) == "string" then }) end --- write(map, opts) -> a JSON value | nil, message function Tmj.write(map, o) local layers = {} for _, l in __iter(map.layers) do @@ -190720,8 +187052,7 @@ return Tmj end __FILES["vector/tiled/Tmx"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. --- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap. local Xml = __include("codecs/text/Xml") local Types = __include("Types") local Data = __include("vector/tiled/Data") @@ -190749,7 +187080,6 @@ local v = a(n, k) end -- ------------------------------------------------------------------------------------------------ read --- <properties> -> values, types (types only for the non-string ones) local function properties(n) local props= {} local types= nil @@ -190789,7 +187119,6 @@ local function withProps(t, n) end end --- the gids of a <data> (or <chunk>) node local function gids(d, encoding, compression) if encoding == "csv" then return Data.csv(Xml.text(d)) @@ -190954,7 +187283,6 @@ local name = n.name return nil end --- a <tileset> element (in a map, or a .tsx root) -> Tileset function Tmx.tileset(n) local ts= { firstGid = num(n, "firstgid", 1), @@ -191008,7 +187336,6 @@ local ts= { return ts end --- read(root) -> TileMap | nil, message, unsupported? function Tmx.read(root) if root.name ~= "map" then return nil, "the root element is <" .. root.name .. ">, not <map>" @@ -191050,8 +187377,7 @@ end -local function el(name, attrs, children) -- attrs in order; nil / default values dropped by the caller - +local function el(name, attrs, children) local o = Types.object() for _, kv in __iter(attrs) do if kv[2] ~= nil then @@ -191254,7 +187580,6 @@ if enc == "csv" then return nil, "unknown layer type " .. tostring(t) end --- tilesetNode(ts, inMap) -> <tileset> function Tmx.tilesetNode(ts, inMap) if inMap and type(ts.source) == "string" then return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -191299,7 +187624,6 @@ if inMap and type(ts.source) == "string" then }, kids) end --- write(map, opts) -> an XML document node | nil, message function Tmx.write(map, o) local kids = {} addProps(kids, map) @@ -191340,15 +187664,9 @@ return Tmx end __FILES["video/avi"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. --- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, --- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is --- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, --- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. --- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's --- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. --- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -191511,7 +187829,6 @@ local f = s.strf return t end --- demux(r, opts?) -> the Demuxer | nil, Err function AviFormat.demux(r, _opts) local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) if not ok then @@ -191538,7 +187855,6 @@ local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) end local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } local dmx = Demux.new("avi", tracks, r.buf, meta) - -- packets in file order across streams: merge by offset local items= {} for k, st in __iter(streams) do local s, t= st[1], st[2] @@ -191568,7 +187884,6 @@ return a[1] < b[1] end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value, opts) local o= table.clone(opts or {}) o.quality = o.quality or 90 @@ -191619,7 +187934,6 @@ local o= table.clone(opts or {}) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks in time order (the video packets already repeated to the constant rate) local chunks= {} for _, item in __iter(Source.interleave(streams)) do table.insert(chunks, { item[1], item[2].data, true }) @@ -191632,7 +187946,6 @@ local o= table.clone(opts or {}) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function AviFormat.open(r, opts) local dmx, err = AviFormat.demux(r, opts) if not dmx then @@ -191645,14 +187958,9 @@ return AviFormat end __FILES["video/fli"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC --- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). --- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: --- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, --- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 --- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the --- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. --- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -191702,7 +188010,6 @@ local s = r:peek(18) end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer | nil, Err function Fli.demux(r, opts) local b, base, limit = r.buf, r.base, r.limit local n = limit - base @@ -191754,7 +188061,6 @@ local b, base, limit = r.buf, r.base, r.limit default = true, bitsPerPixel = depth, } - -- the frame chunks local offs, sizes = {}, {} local p = base + HEADER while p + 6 <= limit do @@ -191765,7 +188071,7 @@ local b, base, limit = r.buf, r.base, r.limit end if (cm == FRAME or cm == FRAME2) and size > 6 then if p + size > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, size) @@ -191791,7 +188097,6 @@ local b, base, limit = r.buf, r.base, r.limit end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Fli.open(r, opts) local dmx, err = Fli.demux(r, opts) if not dmx then @@ -191804,22 +188109,9 @@ return Fli end __FILES["video/flv"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's --- FourCC video tags). New in rosetta. --- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... --- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by --- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 --- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks --- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets --- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), --- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through --- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. --- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / --- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at --- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data --- rates, codec ids, file size). --- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx --- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -191923,7 +188215,6 @@ local c = buffer.create(n) return c end --- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil local function frameSize(codec, b, p, n) if codec == "flv1" then local h = H263.header(b, p, n, true) @@ -191957,7 +188248,6 @@ if codec == "flv1" then return nil, nil end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Flv.demux(r, opts) local o= opts or {} local b, base, limit = r.buf, r.base, r.limit @@ -191974,7 +188264,7 @@ local o= opts or {} local tracks= {} local dmx = Demux.new("flv", tracks, b, meta) local vt, at= nil, nil - local keyOff, keyLen = -1, 0 -- the first video keyframe + local keyOff, keyLen = -1, 0 local maxPackets = o.maxPackets or 2 ^ 24 local count = 0 local p = base + dataOffset + 4 -- after PreviousTagSize0 @@ -192121,7 +188411,6 @@ local o= opts or {} end p = d + size + 4 end - -- the track facts onMetaData and the codec headers give local md= meta.metadata or {} if type(md.duration) == "number" and md.duration > 0 then meta.duration = md.duration @@ -192143,7 +188432,6 @@ local o= opts or {} if type(fr) == "number" and fr > 0 and fr < 1000 then vt.frameRate = fr else - -- from the timestamps: the frames over the time they span local n = dmx:count(vt.id) local t0 = (n > 0 and{(dmx:info(vt.id, 1) )}or{nil })[1] local t1 = (n > 1 and{(dmx:info(vt.id, n) )}or{nil @@ -192160,7 +188448,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer function Flv.encode(value, opts) local o= opts or {} local streams, err = Source.streams(value, o, { @@ -192170,7 +188457,6 @@ local o= opts or {} if not streams then return nil, err end - -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true for i = #streams, 1, -1 do local s = streams[i] local why = s.kind == "audio" and Mux.audioProblem(s) @@ -192192,7 +188478,6 @@ local o= opts or {} end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Flv.open(r, opts) local ok, dmx, err = pcall(Flv.demux, r, opts) if not ok then @@ -192208,13 +188493,8 @@ return Flv end __FILES["video/flv/Amf"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 --- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference --- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the --- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. --- --- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } --- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. local Bytes = __include("core/Bytes") local Amf = {} @@ -192299,13 +188579,11 @@ if depth > MAX_DEPTH or r:remaining() < 1 then return nil end --- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) function Amf.value(r) local ok, v = pcall(readValue, r, 0, {}) return (ok and not r.err and{v }or{nil })[1]end --- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil function Amf.script(r) local name = Amf.value(r) if type(name) ~= "string" then @@ -192326,7 +188604,6 @@ local function writeString(w, s) w:string(s) end --- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null function Amf.writeValue(w, v) local t = type(v) if t == "number" then @@ -192348,8 +188625,6 @@ function Amf.writeValue(w, v) end end --- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as --- { key, { pairs = { ... } } } becomes an object) function Amf.writeEcma(w, list, object) if object then w:u8(3) @@ -192376,12 +188651,8 @@ return Amf end __FILES["video/flv/Mux"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag --- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 --- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source --- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), --- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made --- from the first ADTS header. Interpreted; never throws (returns nil, Err). +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Amf = __include("video/flv/Amf") @@ -192407,7 +188678,6 @@ if s.track and s.track.adts then return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 end --- audioProblem(stream) -> why FLV cannot hold this audio stream | nil function Mux.audioProblem(s) local fmt = AUDIO_FORMATS[s.codec] if not fmt then @@ -192501,7 +188771,6 @@ local function f64At(b, at, v) end end --- mux(streams) -> buffer | nil, Err function Mux.mux(streams) local video, audio = nil , nil for _, s in __iter(streams) do @@ -192544,7 +188813,6 @@ for _, s in __iter(streams) do end end end - -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative local shift = 0 local duration = 0 local vBytes, aBytes = 0, 0 @@ -192588,7 +188856,6 @@ return math.floor((t + shift) * 1000 + 0.5) w:u32be(11 + n) end - -- onMetaData local props= { { "duration", duration } } if video then table.insert(props, { "width", video.width or 0 }) @@ -192615,7 +188882,6 @@ return math.floor((t + shift) * 1000 + 0.5) tag(18, 0, {}, metaBody) local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker - -- sequence headers local vid = (video and{VIDEO_IDS[video.codec] }or{0 })[1] if video and video.codec == "h264" then tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) @@ -192666,14 +188932,9 @@ return Mux end __FILES["video/h264"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg --- `-f h264` output, the JVT conformance bitstreams). New in rosetta. --- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw --- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). --- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, --- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -192732,7 +188993,6 @@ local s = r:peek(5) end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err function Format.demux(r, opts) local buf, base, limit = r.buf, r.base, r.limit local units = H264.accessUnits(buf, base, limit - base) @@ -192773,7 +189033,6 @@ local buf, base, limit = r.buf, r.base, r.limit end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) function Format.encode(value, _opts) local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) if not streams then @@ -192800,7 +189059,6 @@ local streams, err = Source.streams(value, { audio = false }, { video = { copy = end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Format.open(r, opts) local dmx, err = Format.demux(r, opts) if not dmx then @@ -192813,18 +189071,9 @@ return Format end __FILES["video/mkv"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in --- rosetta, on containers/Ebml. --- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio --- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text --- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. --- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied --- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from --- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, --- track.unsupported says why), chapters / attachments (skipped), writing subtitles. +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -192881,7 +189130,6 @@ if r:peek(4) ~= "\26\69\223\163" then return 0.5 end --- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r) local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then @@ -192891,8 +189139,6 @@ local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) --- or a Demuxer function Mkv.encode(value, opts) local o= opts or {} local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") @@ -192935,7 +189181,6 @@ if webm then end -- ------------------------------------------------------------------------------------------------ open --- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err function Mkv.demux(r, opts) local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) if not ok then @@ -192944,7 +189189,6 @@ local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) return dmx, err end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Mkv.open(r, opts) local dmx, err = Mkv.demux(r, opts) if not dmx then @@ -192954,7 +189198,6 @@ local dmx, err = Mkv.demux(r, opts) end -- ------------------------------------------------------------------------------------------------ extras --- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil function Mkv.subtitles(dmx, trackId) local track = nil for _, t in __iter(dmx.tracks) do @@ -192984,11 +189227,8 @@ return Mkv end __FILES["video/mkv/Mux"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), --- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of --- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative --- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). local Err = __include("core/Err") local Ebml = __include("containers/Ebml") local Video = __include("codecs/video/Video") @@ -193021,7 +189261,6 @@ local AUDIO_IDS= { } Mux.AUDIO_IDS = AUDIO_IDS --- codecId(stream) -> the Matroska CodecID | nil function Mux.codecId(kind, codec) if kind == "video" then local e = Video.entry(codec) @@ -193042,7 +189281,6 @@ local b = string.match(codec, "^pcm_[suf](%d+)") return nil end --- mux(streams, opts) -> buffer | nil, Err @@ -193054,7 +189292,6 @@ function Mux.mux(streams, opts) local webm = opts.webm == true local app = opts.app or "rosetta" local clusterSpan = opts.clusterSeconds or 2 - -- tracks local ids= {} local videoIndex = 0 for i, s in __iter(streams) do @@ -193135,7 +189372,6 @@ local webm = opts.webm == true end body:close(tracks) - -- clusters local cues= {} -- { time ms, track, cluster offset in body } local cl= nil local clTime = 0 @@ -193249,7 +189485,6 @@ local w = Ebml.writer(256) bodyBuf = nb end - -- the file local out = Ebml.writer(buffer.len(bodyBuf) + 256) local eb = out:open(ID.EBML) out:uint(0x4286, 1) @@ -193271,11 +189506,8 @@ return Mux end __FILES["video/mkv/Parse"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles --- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, --- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, --- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by --- default). Interpreted (it only walks headers); never throws. +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. local Err = __include("core/Err") local Types = __include("Types") local Ebml = __include("containers/Ebml") @@ -193410,7 +189642,6 @@ local SUBS= { ["S_HDMV/PGS"] = "pgs", } --- codecFor(CodecID, bitDepth) -> our codec id local function codecFor(id, kind, bits) if kind == "video" then return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) @@ -193491,8 +189722,7 @@ local function parseAudio(buf, off, len, t) end end --- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption --- are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption local function parseEncodings(buf, off, len, t) for id, o, n in __iter(Ebml.children(buf, off, off + len)) do if id == ID.ContentEncoding then @@ -193681,7 +189911,7 @@ local function parseTags(buf, off, len, meta) end end --- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +-- Block / SimpleBlock: track, relative timecode, flags, lacing @@ -193815,7 +190045,6 @@ local function block(ctx, off, len, clusterTime, simple, keyHint, durTicks, disc end end --- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended local function cluster(ctx, off, limit, unknown) local buf = ctx.buf local pos = off @@ -193861,9 +190090,6 @@ local buf = ctx.buf return pos end --- parse(buf, base, limit, opts) -> a Demux | nil, Err --- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data --- offset | nil, Err function Parse.docType(buf, base, limit) @@ -193892,7 +190118,6 @@ local docType, size, data = Parse.docType(buf, base, limit) return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) end local pos = data + size - -- the Segment (skip anything else at the top level) local segData, segEnd = -1, limit while pos < limit do local sid, ssize, sdata = Ebml.header(buf, pos, limit) @@ -193935,7 +190160,6 @@ local tracks= {} tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) elseif cid == ID.Cluster then if unknown then - -- find its end: walk children until a top-level ID local p = cdata while p < segEnd do local xid, xsize, xdata = Ebml.header(buf, p, segEnd) @@ -194003,20 +190227,9 @@ return Parse end __FILES["video/mp4"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on --- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. --- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first --- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG --- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through --- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / --- 'lpcm' / 'ipcm'). --- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied --- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v --- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV --- only; MP4 drops other audio unless opts.audio = true, which fails). --- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented --- writing, timed text tracks, encrypted tracks. +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194110,7 +190323,6 @@ local p = t.pcm return "pcm_s" .. bits .. ((p == nil or p.little )and"le" or"be") end --- demux(r, opts?) -> the Demuxer | nil, Err function Mp4.demux(r, opts) local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) if not ok then @@ -194168,7 +190380,6 @@ local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { ma table.insert(src, it) end local dmx = Demux.new(movie.brand == "qt " and"mov" or"mp4", tracks, r.buf, { brand = movie.brand }) - -- samples in file order across tracks local items= {} for k, it in __iter(src) do -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio @@ -194219,7 +190430,6 @@ if not head or buffer.len(head) < 19 then return w:finish() end --- encode(video, opts?) -> buffer | nil, Err function Mp4.encode(value, opts) local o= table.clone(opts or {}) o.quality = o.quality or 90 @@ -194333,7 +190543,6 @@ for i, p in __iter(s.packets) do end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Mp4.open(r, opts) local dmx, err = Mp4.demux(r, opts) if not dmx then @@ -194346,14 +190555,9 @@ return Mp4 end __FILES["video/mpegps"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / --- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both --- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get --- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). --- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its --- sequence extension), audio through the api's opts.openAudio hook. --- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194395,7 +190599,6 @@ if r:peek(4) == "\0\0\1\186" then end -- ------------------------------------------------------------------------------------------------ decode --- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps local function videoPackets(dmx, buf, s, t) local total = 0 for _, p in __iter(s.pes) do @@ -194466,7 +190669,6 @@ local timed = next(ptsOf) ~= nil end end --- demux(r, opts?) -> the Demuxer | nil, Err function Ps.demux(r, _opts) if r:peek(4) == "\0\0\1\179" then -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps @@ -194528,7 +190730,6 @@ for _, p in __iter(s.pes) do end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ps.open(r, opts) local dmx, err = Ps.demux(r, opts) if not dmx then @@ -194541,15 +190742,9 @@ return Ps end __FILES["video/mpegts"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, --- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS --- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the --- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, --- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / --- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. --- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, --- PES without PTS for video before the first one (dropped). +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194594,8 +190789,7 @@ local CODEC= { } -- ------------------------------------------------------------------------------------------------ sniff --- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart --- (fewer in a short file) within the first 2 KB +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB local function packetSize(r) local n = r:remaining() for start = 0, math.min(n, 2048) - 1 do @@ -194654,7 +190848,6 @@ local d= u.data return "mp2" end --- demux(r, opts?) -> the Demuxer | nil, Err function Ts.demux(r, _opts) local size, off = packetSize(r) if size == 0 then @@ -194706,7 +190899,6 @@ local t = byPid[pid] for _, u in __iter(units) do track(u.pid, u.kind, u.codec, u.streamType, nil) end - -- codec details from the first unit local seen= {} for _, u in __iter(units) do local t = byPid[u.pid] @@ -194776,7 +190968,6 @@ local t = byPid[pid] end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ts.open(r, opts) local dmx, err = Ts.demux(r, opts) if not dmx then @@ -194789,17 +190980,9 @@ return Ts end __FILES["video/ogv"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, --- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. --- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from --- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, --- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / --- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's --- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. --- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied --- (the audio pages come from containers/AudioWrap and are interleaved by time). --- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), --- encoding Theora (there is no encoder: other sources cannot be written). +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -194839,8 +191022,7 @@ local Ogv = { local AUDIO = { vorbis = true, opus = true, flac = true } -- ------------------------------------------------------------------------------------------------ sniff --- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain --- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) function Ogv.sniff(r) if r:peek(4) ~= "OggS" then return 0 @@ -194868,7 +191050,6 @@ if r:peek(4) ~= "OggS" then end -- ------------------------------------------------------------------------------------------------ encode --- the pages of an Ogg buffer: { offset, size, serial, granule, bos } local function pages(b) local out = {} local pos = 0 @@ -194883,7 +191064,6 @@ local out = {} return out end --- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) function Ogv.encode(value, opts) local o= opts or {} local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) @@ -194927,7 +191107,6 @@ local headers = Theora.splitConfig(v.config ) s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) end local video = mux:finish() - -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time local audio= nil local arate, askip = 1, 0 if as and o.audio ~= false then @@ -195020,7 +191199,6 @@ local w = Bytes.writer(64) return w:finish() end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Ogv.demux(r, opts) @@ -195091,7 +191269,7 @@ local __DARKLUA_CONTINUE_14=false repeat local p = rd:nextPacket() break end if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then -__DARKLUA_CONTINUE_14=true break -- a stray header +__DARKLUA_CONTINUE_14=true break end table.insert(packets, p) if base == nil and p.granule >= 0 then @@ -195182,7 +191360,6 @@ local pa, pc = all[a].page, all[c].page return dmx, nil end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Ogv.open(r, opts) local ok, dmx, err = pcall(Ogv.demux, r, opts) if not ok then @@ -195198,18 +191375,9 @@ return Ogv end __FILES["video/smk"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description --- (MultimediaWiki "Smacker"). --- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio --- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette --- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() --- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the --- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio --- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it --- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that --- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, --- track) the Decoder of any of its audio tracks. --- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -195258,7 +191426,6 @@ local s = r:peek(4) end -- ------------------------------------------------------------------------------------------------ decode --- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed local function palette(b, p, stop, old) local pal = buffer.create(1024) buffer.copy(pal, 0, old, 0, 1024) @@ -195295,7 +191462,6 @@ local v = (p < stop and{(buffer.readu8(b, p) )}or{0 return pal end --- demux(r, opts?) -> the Demuxer | nil, Err function Smk.demux(r, opts) local b, base, limit = r.buf, r.base, r.limit if limit - base < HEADER then @@ -195446,7 +191612,6 @@ or math.floor(len / frameBytes end -- ------------------------------------------------------------------------------------------------ open --- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err function Smk.openAudio(dmx, track) local codec = track.codec if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then @@ -195498,7 +191663,6 @@ return floats }) end --- open(r, opts?) -> a VideoDecoder | nil, Err function Smk.open(r, opts) local dmx, err = Smk.demux(r, opts) if not dmx then @@ -195522,20 +191686,15 @@ __FILES["video/smk/Audio"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker --- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), --- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ --- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per --- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / --- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives --- them. Never throws: trees are bounded and every read past the packet gives zero bits. +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). local Smacker = __include("codecs/video/Legacy/Smacker") local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} --- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message function Audio.decode(d, channels, bits, packed) local n = buffer.len(d) if not packed then @@ -195564,7 +191723,7 @@ local n = buffer.len(d) local br = Smacker.bits(d, 4, n - 4) local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk if bit(br) == 0 then - return 0, {} -- no data + return 0, {} end local stereo = bit(br) local wide = bit(br) @@ -195645,13 +191804,9 @@ return Audio end __FILES["video/y4m"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. --- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder --- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono --- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. --- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), --- alpha (C444alpha drops it). +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") @@ -195682,7 +191837,6 @@ local Y4m = { - local MAGIC = "YUV4MPEG2 " -- C tag -> pixel format, bits local COLOR= { @@ -195723,7 +191877,6 @@ local bps = bits > 8 and 2 or 1 return w * h * bps end --- demux(r, opts?) -> the raw-video Demuxer | nil, Err function Y4m.demux(r, opts) local buf, base, limit = r.buf, r.base, r.limit local nl = -1 @@ -195810,7 +191963,7 @@ end end local data = e + 1 if data + size > limit then - break -- a truncated last frame is dropped + break end dmx:add(1, k, k, 1, true, data, size) k =k+ 1 @@ -195821,7 +191974,6 @@ end end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value, opts) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) if not streams then @@ -195843,7 +191995,6 @@ local streams, err = Source.streams(value, { audio = false }, { video = { copy = end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Y4m.open(r, opts) local dmx, err = Y4m.demux(r, opts) if not dmx then diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index e8c3926..f96757d 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -1,539 +1,539 @@ [ -[689, "src/Rosetta/init.luau"], -[1617, "src/Rosetta/Registry.luau"], -[3726, "src/Rosetta/Types.luau"], -[4883, "src/Rosetta/archive/7z/init.luau"], -[5276, "src/Rosetta/archive/7z/Header.luau"], -[5808, "src/Rosetta/archive/adf/init.luau"], -[6098, "src/Rosetta/archive/applesingle/init.luau"], -[6290, "src/Rosetta/archive/ar/init.luau"], -[6702, "src/Rosetta/archive/arj/init.luau"], -[6916, "src/Rosetta/archive/binhex/init.luau"], -[7172, "src/Rosetta/archive/br/init.luau"], -[7250, "src/Rosetta/archive/bz2/init.luau"], -[7316, "src/Rosetta/archive/cab/init.luau"], -[7745, "src/Rosetta/archive/cab/Sum.luau"], -[7789, "src/Rosetta/archive/cpio/init.luau"], -[7963, "src/Rosetta/archive/d64/init.luau"], -[8389, "src/Rosetta/archive/fat/init.luau"], -[8515, "src/Rosetta/archive/grp/init.luau"], -[8632, "src/Rosetta/archive/gzip/init.luau"], -[8821, "src/Rosetta/archive/iso/init.luau"], -[8898, "src/Rosetta/archive/lha/init.luau"], -[9334, "src/Rosetta/archive/lz4/init.luau"], -[9689, "src/Rosetta/archive/macbinary/init.luau"], -[9892, "src/Rosetta/archive/mpq/init.luau"], -[10313, "src/Rosetta/archive/mpq/Crypt.luau"], -[10380, "src/Rosetta/archive/pak/init.luau"], -[10517, "src/Rosetta/archive/rpm/init.luau"], -[10852, "src/Rosetta/archive/tar/init.luau"], -[10974, "src/Rosetta/archive/uu/init.luau"], -[11252, "src/Rosetta/archive/vpk/init.luau"], -[11571, "src/Rosetta/archive/wad/init.luau"], -[12047, "src/Rosetta/archive/wad/Map.luau"], -[12490, "src/Rosetta/archive/wad/Picture.luau"], -[12601, "src/Rosetta/archive/xz/init.luau"], -[12704, "src/Rosetta/archive/yenc/init.luau"], -[12983, "src/Rosetta/archive/z/init.luau"], -[13083, "src/Rosetta/archive/zip/init.luau"], -[13323, "src/Rosetta/archive/zoo/init.luau"], -[13522, "src/Rosetta/archive/zst/init.luau"], -[13587, "src/Rosetta/audio/aac/init.luau"], -[13798, "src/Rosetta/audio/ac3/init.luau"], -[13947, "src/Rosetta/audio/adpcm/init.luau"], -[14104, "src/Rosetta/audio/adx/init.luau"], -[14343, "src/Rosetta/audio/aiff/init.luau"], -[14745, "src/Rosetta/audio/ape/init.luau"], -[14881, "src/Rosetta/audio/au/init.luau"], -[15044, "src/Rosetta/audio/brstm/init.luau"], -[15344, "src/Rosetta/audio/caf/init.luau"], -[16014, "src/Rosetta/audio/flac/init.luau"], -[16177, "src/Rosetta/audio/flac/Meta.luau"], -[16402, "src/Rosetta/audio/flac/Stream.luau"], -[16787, "src/Rosetta/audio/m4a/init.luau"], -[17129, "src/Rosetta/audio/mp3/init.luau"], -[17409, "src/Rosetta/audio/mp3/Index.luau"], -[17605, "src/Rosetta/audio/mp3/Stream.luau"], -[17840, "src/Rosetta/audio/mp3/Tags.luau"], -[18159, "src/Rosetta/audio/mpc/init.luau"], -[18257, "src/Rosetta/audio/opus/init.luau"], -[18661, "src/Rosetta/audio/opus/Encode.luau"], -[18780, "src/Rosetta/audio/qoa/init.luau"], -[18967, "src/Rosetta/audio/tta/init.luau"], -[19092, "src/Rosetta/audio/vag/init.luau"], -[19325, "src/Rosetta/audio/voc/init.luau"], -[19605, "src/Rosetta/audio/vorbis/init.luau"], -[20077, "src/Rosetta/audio/vorbis/Encode.luau"], -[20906, "src/Rosetta/audio/wav/init.luau"], -[21551, "src/Rosetta/audio/wav/Codecs.luau"], -[21726, "src/Rosetta/audio/wavpack/init.luau"], -[21947, "src/Rosetta/cad/step/init.luau"], -[22359, "src/Rosetta/cad/step/Brep.luau"], -[22609, "src/Rosetta/cad/step/Parse.luau"], -[23184, "src/Rosetta/cad/step/Write.luau"], -[23438, "src/Rosetta/codecs/audio/Aac/init.luau"], -[23757, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[24640, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24975, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[25134, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[26019, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[26120, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26874, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[27176, "src/Rosetta/codecs/audio/Alac/init.luau"], -[27410, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27829, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[28241, "src/Rosetta/codecs/audio/Ape/init.luau"], -[28456, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[29217, "src/Rosetta/codecs/audio/ApeTag.luau"], -[29314, "src/Rosetta/codecs/audio/Flac/init.luau"], -[29325, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[30274, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30871, "src/Rosetta/codecs/audio/Hively/init.luau"], -[31067, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[31316, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[32274, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[32493, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[32677, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32886, "src/Rosetta/codecs/audio/MidiRender.luau"], -[33232, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[33246, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[33305, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34908, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[35200, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[35585, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[36226, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[36367, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[36593, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36938, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[37819, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[38197, "src/Rosetta/codecs/audio/Opus/init.luau"], -[38211, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[40058, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[41123, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[41183, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[41643, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41980, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[42213, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[44249, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[44623, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44886, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[45183, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[45465, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45824, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45878, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[46021, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[46534, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[47315, "src/Rosetta/codecs/audio/Stream.luau"], -[47476, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47958, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[48236, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[48405, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[48533, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[50521, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[50637, "src/Rosetta/codecs/audio/Tta/init.luau"], -[50754, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[51006, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[51019, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[51403, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51969, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[52390, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[52429, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[52481, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[52703, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[54158, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[54221, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[54308, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[55277, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[56145, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[56193, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[56709, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[57035, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[57455, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57890, "src/Rosetta/codecs/compress/Explode.luau"], -[58086, "src/Rosetta/codecs/compress/Lz4.luau"], -[58355, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58959, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[59499, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[59537, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[60010, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[60186, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[60454, "src/Rosetta/codecs/compress/Lzx.luau"], -[60888, "src/Rosetta/codecs/compress/PackBits.luau"], -[60978, "src/Rosetta/codecs/compress/Quantum.luau"], -[61215, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[61519, "src/Rosetta/codecs/compress/Xxh32.luau"], -[61588, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[61645, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[62603, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[62755, "src/Rosetta/codecs/entropy/Huffman.luau"], -[63037, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[63048, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[63262, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[63506, "src/Rosetta/codecs/font/Bitmap.luau"], -[63707, "src/Rosetta/codecs/font/Cff/init.luau"], -[64348, "src/Rosetta/codecs/font/GlyphNames.luau"], -[64498, "src/Rosetta/codecs/font/TrueType/init.luau"], -[64812, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[65204, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[65706, "src/Rosetta/codecs/image/Bcn/init.luau"], -[65813, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[66302, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[66731, "src/Rosetta/codecs/image/Blend.luau"], -[67110, "src/Rosetta/codecs/image/Dct/init.luau"], -[67491, "src/Rosetta/codecs/image/Etc.luau"], -[67789, "src/Rosetta/codecs/image/Half.luau"], -[67858, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[68212, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[68620, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68857, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[69617, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[70498, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70944, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[71022, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[71089, "src/Rosetta/codecs/image/Pixels.luau"], -[71353, "src/Rosetta/codecs/image/Quantize/init.luau"], -[71812, "src/Rosetta/codecs/image/Raster.luau"], -[72509, "src/Rosetta/codecs/image/Texel.luau"], -[72882, "src/Rosetta/codecs/image/Texture.luau"], -[73027, "src/Rosetta/codecs/image/Vp8/init.luau"], -[73157, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[75113, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[75372, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[75621, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[75740, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75844, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[76697, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[77649, "src/Rosetta/codecs/image/Yuv.luau"], -[77917, "src/Rosetta/codecs/model/Draco/init.luau"], -[78249, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[78718, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79907, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[80056, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[80415, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[81377, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81851, "src/Rosetta/codecs/model/Mat4.luau"], -[82110, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[82638, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[83190, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[83269, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[83376, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[83582, "src/Rosetta/codecs/model/Polygon.luau"], -[83816, "src/Rosetta/codecs/model/Rbx/init.luau"], -[84053, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[84807, "src/Rosetta/codecs/model/Rig.luau"], -[85050, "src/Rosetta/codecs/model/Sampler.luau"], -[85210, "src/Rosetta/codecs/model/Vrml/init.luau"], -[85358, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85932, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[86095, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86844, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[87366, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[88093, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[88325, "src/Rosetta/codecs/text/Json/init.luau"], -[88594, "src/Rosetta/codecs/text/Json/Decode.luau"], -[89008, "src/Rosetta/codecs/text/Json/Encode.luau"], -[89310, "src/Rosetta/codecs/text/Nbt/init.luau"], -[89663, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[90355, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90995, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[91233, "src/Rosetta/codecs/text/Text/init.luau"], -[91324, "src/Rosetta/codecs/text/Url/init.luau"], -[91529, "src/Rosetta/codecs/text/Xml/init.luau"], -[91932, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[92672, "src/Rosetta/codecs/video/Dsp.luau"], -[93395, "src/Rosetta/codecs/video/H263/init.luau"], -[93551, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[94409, "src/Rosetta/codecs/video/H263/Tables.luau"], -[94612, "src/Rosetta/codecs/video/H264/init.luau"], -[94985, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[95260, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[96391, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[97159, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[97417, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[98426, "src/Rosetta/codecs/video/H264/Inter.luau"], -[98680, "src/Rosetta/codecs/video/H264/Intra.luau"], -[99087, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99993, "src/Rosetta/codecs/video/H264/Params.luau"], -[100440, "src/Rosetta/codecs/video/H264/Slice.luau"], -[100691, "src/Rosetta/codecs/video/H264/Tables.luau"], -[100732, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100897, "src/Rosetta/codecs/video/Legacy/init.luau"], -[101095, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[101392, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[101759, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101877, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101985, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[102258, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[102653, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102830, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102842, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[103209, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[104716, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104855, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104993, "src/Rosetta/codecs/video/Theora/init.luau"], -[105256, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[106520, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106883, "src/Rosetta/codecs/video/Video/init.luau"], -[107440, "src/Rosetta/codecs/video/Video/Source.luau"], -[107725, "src/Rosetta/containers/Archive.luau"], -[108018, "src/Rosetta/containers/AudioWrap.luau"], -[108539, "src/Rosetta/containers/Avi/init.luau"], -[109111, "src/Rosetta/containers/Chunks.luau"], -[109255, "src/Rosetta/containers/Cpio.luau"], -[109697, "src/Rosetta/containers/Demux.luau"], -[109995, "src/Rosetta/containers/Ebml/init.luau"], -[110332, "src/Rosetta/containers/Fat.luau"], -[111041, "src/Rosetta/containers/Iso9660.luau"], -[111568, "src/Rosetta/containers/IsoBmff/init.luau"], -[111758, "src/Rosetta/containers/IsoBmff/Box.luau"], -[111953, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[112817, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[113347, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[113868, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[113990, "src/Rosetta/containers/MacFile.luau"], -[114150, "src/Rosetta/containers/MpegEs.luau"], -[114325, "src/Rosetta/containers/MpegPs/init.luau"], -[114551, "src/Rosetta/containers/MpegTs/init.luau"], -[115368, "src/Rosetta/containers/Ogg/init.luau"], -[115826, "src/Rosetta/containers/Ogg/Mux.luau"], -[116036, "src/Rosetta/containers/Ogg/Page.luau"], -[116213, "src/Rosetta/containers/Riff/init.luau"], -[116558, "src/Rosetta/containers/Tar.luau"], -[116986, "src/Rosetta/containers/Zip/init.luau"], -[117646, "src/Rosetta/core/Adler32.luau"], -[117698, "src/Rosetta/core/Base64.luau"], -[117867, "src/Rosetta/core/Bits.luau"], -[118179, "src/Rosetta/core/Bytes.luau"], -[118748, "src/Rosetta/core/Crc16.luau"], -[118802, "src/Rosetta/core/Crc32.luau"], -[118925, "src/Rosetta/core/Err.luau"], -[119021, "src/Rosetta/core/Input.luau"], -[119105, "src/Rosetta/core/Md5.luau"], -[119271, "src/Rosetta/core/Sniff.luau"], -[119309, "src/Rosetta/data/cbor/init.luau"], -[119411, "src/Rosetta/data/cbor/Codec.luau"], -[119988, "src/Rosetta/data/csv/init.luau"], -[120305, "src/Rosetta/data/ini/init.luau"], -[120556, "src/Rosetta/data/json/init.luau"], -[120649, "src/Rosetta/data/msgpack/init.luau"], -[120741, "src/Rosetta/data/msgpack/Codec.luau"], -[121189, "src/Rosetta/data/nbt/init.luau"], -[121251, "src/Rosetta/data/plist/init.luau"], -[121559, "src/Rosetta/data/plist/Binary.luau"], -[121832, "src/Rosetta/data/snbt/init.luau"], -[121897, "src/Rosetta/data/toml/init.luau"], -[121969, "src/Rosetta/data/toml/Decode.luau"], -[122606, "src/Rosetta/data/toml/Encode.luau"], -[122822, "src/Rosetta/data/xml/init.luau"], -[122879, "src/Rosetta/data/yaml/init.luau"], -[122958, "src/Rosetta/data/yaml/Emit.luau"], -[123259, "src/Rosetta/data/yaml/Parse.luau"], -[124583, "src/Rosetta/font/bdf/init.luau"], -[124880, "src/Rosetta/font/bmfont/init.luau"], -[125322, "src/Rosetta/font/bmfont/Parse.luau"], -[125781, "src/Rosetta/font/eot/init.luau"], -[126016, "src/Rosetta/font/fon/init.luau"], -[126306, "src/Rosetta/font/hershey/init.luau"], -[126508, "src/Rosetta/font/pcf/init.luau"], -[126800, "src/Rosetta/font/psf/init.luau"], -[127130, "src/Rosetta/font/ttf/init.luau"], -[127184, "src/Rosetta/font/type1/init.luau"], -[127554, "src/Rosetta/font/type1/Charstring.luau"], -[127839, "src/Rosetta/font/woff/init.luau"], -[127973, "src/Rosetta/font/woff2/init.luau"], -[128032, "src/Rosetta/font/woff2/Rebuild.luau"], -[128582, "src/Rosetta/host/init.luau"], -[128634, "src/Rosetta/host/Love.luau"], -[128785, "src/Rosetta/host/LuaJIT.luau"], -[128835, "src/Rosetta/host/Luau.luau"], -[128858, "src/Rosetta/host/Roblox.luau"], -[129249, "src/Rosetta/image/ani/init.luau"], -[129434, "src/Rosetta/image/blp/init.luau"], -[129702, "src/Rosetta/image/bmp/init.luau"], -[130133, "src/Rosetta/image/dds/init.luau"], -[130632, "src/Rosetta/image/exr/init.luau"], -[131416, "src/Rosetta/image/exr/Codec.luau"], -[131535, "src/Rosetta/image/exr/Piz.luau"], -[131904, "src/Rosetta/image/gif/init.luau"], -[132440, "src/Rosetta/image/gif/Decode.luau"], -[132510, "src/Rosetta/image/hdr/init.luau"], -[132746, "src/Rosetta/image/hdr/Codec.luau"], -[132967, "src/Rosetta/image/icns/init.luau"], -[133306, "src/Rosetta/image/ico/init.luau"], -[133590, "src/Rosetta/image/ico/Dib.luau"], -[133691, "src/Rosetta/image/ilbm/init.luau"], -[134017, "src/Rosetta/image/jpeg/init.luau"], -[134168, "src/Rosetta/image/ktx/init.luau"], -[134842, "src/Rosetta/image/pcx/init.luau"], -[135110, "src/Rosetta/image/png/init.luau"], -[135708, "src/Rosetta/image/png/Apng.luau"], -[135792, "src/Rosetta/image/png/Decode.luau"], -[136047, "src/Rosetta/image/png/Encode.luau"], -[136211, "src/Rosetta/image/pnm/init.luau"], -[136597, "src/Rosetta/image/pnm/Codec.luau"], -[136888, "src/Rosetta/image/qoi/init.luau"], -[137012, "src/Rosetta/image/qoi/Codec.luau"], -[137166, "src/Rosetta/image/sgi/init.luau"], -[137454, "src/Rosetta/image/sunras/init.luau"], -[137703, "src/Rosetta/image/tga/init.luau"], -[137981, "src/Rosetta/image/tga/Codec.luau"], -[138140, "src/Rosetta/image/tiff/init.luau"], -[138984, "src/Rosetta/image/tiff/Pixels.luau"], -[139385, "src/Rosetta/image/tim/init.luau"], -[139634, "src/Rosetta/image/vtf/init.luau"], -[139881, "src/Rosetta/image/webp/init.luau"], -[140510, "src/Rosetta/image/webp/Alpha.luau"], -[140588, "src/Rosetta/image/webp/Anim.luau"], -[140752, "src/Rosetta/image/xbm/init.luau"], -[140916, "src/Rosetta/image/xpm/init.luau"], -[141190, "src/Rosetta/image/xpm/Names.luau"], -[141249, "src/Rosetta/layered/aseprite/init.luau"], -[142005, "src/Rosetta/layered/ora/init.luau"], -[142300, "src/Rosetta/layered/psd/init.luau"], -[143045, "src/Rosetta/layered/psd/Channels.luau"], -[143416, "src/Rosetta/model/3ds/init.luau"], -[143518, "src/Rosetta/model/3ds/Build.luau"], -[144183, "src/Rosetta/model/3ds/Read.luau"], -[144691, "src/Rosetta/model/3ds/Write.luau"], -[145520, "src/Rosetta/model/3mf/init.luau"], -[145617, "src/Rosetta/model/3mf/Read.luau"], -[146217, "src/Rosetta/model/3mf/Write.luau"], -[146636, "src/Rosetta/model/b3d/init.luau"], -[146706, "src/Rosetta/model/b3d/Read.luau"], -[147284, "src/Rosetta/model/bsp/init.luau"], -[147436, "src/Rosetta/model/bsp/Brush.luau"], -[147729, "src/Rosetta/model/bsp/Quake3.luau"], -[147992, "src/Rosetta/model/dae/init.luau"], -[148200, "src/Rosetta/model/dae/Math.luau"], -[148248, "src/Rosetta/model/dae/Read.luau"], -[150130, "src/Rosetta/model/dae/Write.luau"], -[150508, "src/Rosetta/model/fbx/init.luau"], -[150676, "src/Rosetta/model/fbx/Ascii.luau"], -[150952, "src/Rosetta/model/fbx/Binary.luau"], -[151415, "src/Rosetta/model/fbx/Read.luau"], -[152801, "src/Rosetta/model/fbx/Write.luau"], -[153799, "src/Rosetta/model/fbx/Xform.luau"], -[153843, "src/Rosetta/model/gltf/init.luau"], -[154097, "src/Rosetta/model/gltf/Pack.luau"], -[154173, "src/Rosetta/model/gltf/Read.luau"], -[154922, "src/Rosetta/model/gltf/Write.luau"], -[155620, "src/Rosetta/model/iqm/init.luau"], -[155704, "src/Rosetta/model/iqm/Read.luau"], -[156065, "src/Rosetta/model/iqm/Write.luau"], -[156773, "src/Rosetta/model/ldraw/init.luau"], -[156880, "src/Rosetta/model/ldraw/Colors.luau"], -[157201, "src/Rosetta/model/ldraw/Read.luau"], -[157783, "src/Rosetta/model/lwo/init.luau"], -[157871, "src/Rosetta/model/lwo/Build.luau"], -[158342, "src/Rosetta/model/lwo/Parse.luau"], -[158895, "src/Rosetta/model/mca/init.luau"], -[159252, "src/Rosetta/model/mca/Chunk.luau"], -[159389, "src/Rosetta/model/mca/Lz4Block.luau"], -[159461, "src/Rosetta/model/md2/init.luau"], -[159672, "src/Rosetta/model/md3/init.luau"], -[159908, "src/Rosetta/model/md5/init.luau"], -[159993, "src/Rosetta/model/md5/Read.luau"], -[160435, "src/Rosetta/model/mdl/init.luau"], -[160521, "src/Rosetta/model/mdl/HalfLife.luau"], -[160863, "src/Rosetta/model/mdl/Quake.luau"], -[161087, "src/Rosetta/model/ms3d/init.luau"], -[161171, "src/Rosetta/model/ms3d/Read.luau"], -[161637, "src/Rosetta/model/ms3d/Write.luau"], -[162125, "src/Rosetta/model/obj/init.luau"], -[162890, "src/Rosetta/model/obj/Mtl.luau"], -[163186, "src/Rosetta/model/off/init.luau"], -[163668, "src/Rosetta/model/ply/init.luau"], -[164818, "src/Rosetta/model/ply/Binary.luau"], -[165032, "src/Rosetta/model/pmx/init.luau"], -[165111, "src/Rosetta/model/pmx/Build.luau"], -[165420, "src/Rosetta/model/pmx/Pmd.luau"], -[165761, "src/Rosetta/model/pmx/Read.luau"], -[166174, "src/Rosetta/model/qb/init.luau"], -[166577, "src/Rosetta/model/rbxm/init.luau"], -[167184, "src/Rosetta/model/rbxmx/init.luau"], -[167853, "src/Rosetta/model/robloxmesh/init.luau"], -[168539, "src/Rosetta/model/robloxmesh/Parse.luau"], -[169001, "src/Rosetta/model/robloxmesh/Write.luau"], -[169112, "src/Rosetta/model/schematic/init.luau"], -[169448, "src/Rosetta/model/schematic/Common.luau"], -[169578, "src/Rosetta/model/schematic/Litematic.luau"], -[169795, "src/Rosetta/model/schematic/Mcedit.luau"], -[170046, "src/Rosetta/model/schematic/Sponge.luau"], -[170179, "src/Rosetta/model/smd/init.luau"], -[170250, "src/Rosetta/model/smd/Read.luau"], -[170527, "src/Rosetta/model/smd/Write.luau"], -[170779, "src/Rosetta/model/stl/init.luau"], -[171248, "src/Rosetta/model/stl/Decode.luau"], -[171327, "src/Rosetta/model/usda/init.luau"], -[171550, "src/Rosetta/model/usda/Build.luau"], -[172867, "src/Rosetta/model/usda/Parse.luau"], -[173689, "src/Rosetta/model/usda/Write.luau"], -[174531, "src/Rosetta/model/vox/init.luau"], -[175436, "src/Rosetta/model/vox/Grid.luau"], -[175499, "src/Rosetta/model/vrml/init.luau"], -[175578, "src/Rosetta/model/x/init.luau"], -[175722, "src/Rosetta/model/x/Build.luau"], -[176298, "src/Rosetta/model/x/Parse.luau"], -[176606, "src/Rosetta/model/x3d/init.luau"], -[176693, "src/Rosetta/music/669/init.luau"], -[176904, "src/Rosetta/music/ahx/init.luau"], -[176959, "src/Rosetta/music/far/init.luau"], -[177193, "src/Rosetta/music/hmp/init.luau"], -[177468, "src/Rosetta/music/hvl/init.luau"], -[177523, "src/Rosetta/music/it/init.luau"], -[177952, "src/Rosetta/music/it/Itsex.luau"], -[178074, "src/Rosetta/music/med/init.luau"], -[178737, "src/Rosetta/music/midi/init.luau"], -[178893, "src/Rosetta/music/midi/Smf.luau"], -[179313, "src/Rosetta/music/mod/init.luau"], -[179676, "src/Rosetta/music/mtm/init.luau"], -[179904, "src/Rosetta/music/mus/init.luau"], -[180069, "src/Rosetta/music/okt/init.luau"], -[180357, "src/Rosetta/music/ptm/init.luau"], -[180586, "src/Rosetta/music/s3m/init.luau"], -[180830, "src/Rosetta/music/sf2/init.luau"], -[180876, "src/Rosetta/music/stm/init.luau"], -[181111, "src/Rosetta/music/ult/init.luau"], -[181422, "src/Rosetta/music/umx/init.luau"], -[181646, "src/Rosetta/music/xm/init.luau"], -[182221, "src/Rosetta/music/xmi/init.luau"], -[182438, "src/Rosetta/ops/AudioOps.luau"], -[182922, "src/Rosetta/ops/ImageOps/init.luau"], -[183613, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[184135, "src/Rosetta/ops/LayerOps.luau"], -[184238, "src/Rosetta/ops/MeshOps/init.luau"], -[185327, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[185496, "src/Rosetta/ops/MusicOps.luau"], -[185867, "src/Rosetta/playlist/m3u/init.luau"], -[186236, "src/Rosetta/playlist/pls/init.luau"], -[186423, "src/Rosetta/playlist/xspf/init.luau"], -[186639, "src/Rosetta/subtitle/ass/init.luau"], -[187097, "src/Rosetta/subtitle/srt/init.luau"], -[187277, "src/Rosetta/subtitle/vtt/init.luau"], -[187487, "src/Rosetta/vector/svg/init.luau"], -[187583, "src/Rosetta/vector/svg/Parse.luau"], -[188343, "src/Rosetta/vector/svg/PathData.luau"], -[188722, "src/Rosetta/vector/svg/Render.luau"], -[189151, "src/Rosetta/vector/svg/Style.luau"], -[189534, "src/Rosetta/vector/svg/Write.luau"], -[189739, "src/Rosetta/vector/tiled/init.luau"], -[189928, "src/Rosetta/vector/tiled/Data.luau"], -[190086, "src/Rosetta/vector/tiled/Tmj.luau"], -[190722, "src/Rosetta/vector/tiled/Tmx.luau"], -[191342, "src/Rosetta/video/avi/init.luau"], -[191647, "src/Rosetta/video/fli/init.luau"], -[191806, "src/Rosetta/video/flv/init.luau"], -[192210, "src/Rosetta/video/flv/Amf.luau"], -[192378, "src/Rosetta/video/flv/Mux.luau"], -[192668, "src/Rosetta/video/h264/init.luau"], -[192815, "src/Rosetta/video/mkv/init.luau"], -[192986, "src/Rosetta/video/mkv/Mux.luau"], -[193273, "src/Rosetta/video/mkv/Parse.luau"], -[194005, "src/Rosetta/video/mp4/init.luau"], -[194348, "src/Rosetta/video/mpegps/init.luau"], -[194543, "src/Rosetta/video/mpegts/init.luau"], -[194791, "src/Rosetta/video/ogv/init.luau"], -[195200, "src/Rosetta/video/smk/init.luau"], -[195522, "src/Rosetta/video/smk/Audio.luau"], -[195647, "src/Rosetta/video/y4m/init.luau"] +[660, "src/Rosetta/init.luau"], +[1504, "src/Rosetta/Registry.luau"], +[3613, "src/Rosetta/Types.luau"], +[4696, "src/Rosetta/archive/7z/init.luau"], +[5081, "src/Rosetta/archive/7z/Header.luau"], +[5608, "src/Rosetta/archive/adf/init.luau"], +[5890, "src/Rosetta/archive/applesingle/init.luau"], +[6076, "src/Rosetta/archive/ar/init.luau"], +[6479, "src/Rosetta/archive/arj/init.luau"], +[6689, "src/Rosetta/archive/binhex/init.luau"], +[6938, "src/Rosetta/archive/br/init.luau"], +[7013, "src/Rosetta/archive/bz2/init.luau"], +[7077, "src/Rosetta/archive/cab/init.luau"], +[7490, "src/Rosetta/archive/cab/Sum.luau"], +[7531, "src/Rosetta/archive/cpio/init.luau"], +[7699, "src/Rosetta/archive/d64/init.luau"], +[8113, "src/Rosetta/archive/fat/init.luau"], +[8235, "src/Rosetta/archive/grp/init.luau"], +[8349, "src/Rosetta/archive/gzip/init.luau"], +[8534, "src/Rosetta/archive/iso/init.luau"], +[8606, "src/Rosetta/archive/lha/init.luau"], +[9031, "src/Rosetta/archive/lz4/init.luau"], +[9375, "src/Rosetta/archive/macbinary/init.luau"], +[9573, "src/Rosetta/archive/mpq/init.luau"], +[9979, "src/Rosetta/archive/mpq/Crypt.luau"], +[10044, "src/Rosetta/archive/pak/init.luau"], +[10178, "src/Rosetta/archive/rpm/init.luau"], +[10502, "src/Rosetta/archive/tar/init.luau"], +[10620, "src/Rosetta/archive/uu/init.luau"], +[10890, "src/Rosetta/archive/vpk/init.luau"], +[11201, "src/Rosetta/archive/wad/init.luau"], +[11651, "src/Rosetta/archive/wad/Map.luau"], +[12081, "src/Rosetta/archive/wad/Picture.luau"], +[12183, "src/Rosetta/archive/xz/init.luau"], +[12283, "src/Rosetta/archive/yenc/init.luau"], +[12555, "src/Rosetta/archive/z/init.luau"], +[12651, "src/Rosetta/archive/zip/init.luau"], +[12870, "src/Rosetta/archive/zoo/init.luau"], +[13066, "src/Rosetta/archive/zst/init.luau"], +[13130, "src/Rosetta/audio/aac/init.luau"], +[13336, "src/Rosetta/audio/ac3/init.luau"], +[13482, "src/Rosetta/audio/adpcm/init.luau"], +[13627, "src/Rosetta/audio/adx/init.luau"], +[13858, "src/Rosetta/audio/aiff/init.luau"], +[14249, "src/Rosetta/audio/ape/init.luau"], +[14377, "src/Rosetta/audio/au/init.luau"], +[14538, "src/Rosetta/audio/brstm/init.luau"], +[14829, "src/Rosetta/audio/caf/init.luau"], +[15491, "src/Rosetta/audio/flac/init.luau"], +[15639, "src/Rosetta/audio/flac/Meta.luau"], +[15861, "src/Rosetta/audio/flac/Stream.luau"], +[16231, "src/Rosetta/audio/m4a/init.luau"], +[16565, "src/Rosetta/audio/mp3/init.luau"], +[16825, "src/Rosetta/audio/mp3/Index.luau"], +[17016, "src/Rosetta/audio/mp3/Stream.luau"], +[17239, "src/Rosetta/audio/mp3/Tags.luau"], +[17551, "src/Rosetta/audio/mpc/init.luau"], +[17645, "src/Rosetta/audio/opus/init.luau"], +[18023, "src/Rosetta/audio/opus/Encode.luau"], +[18134, "src/Rosetta/audio/qoa/init.luau"], +[18314, "src/Rosetta/audio/tta/init.luau"], +[18432, "src/Rosetta/audio/vag/init.luau"], +[18655, "src/Rosetta/audio/voc/init.luau"], +[18930, "src/Rosetta/audio/vorbis/init.luau"], +[19384, "src/Rosetta/audio/vorbis/Encode.luau"], +[20197, "src/Rosetta/audio/wav/init.luau"], +[20818, "src/Rosetta/audio/wav/Codecs.luau"], +[20984, "src/Rosetta/audio/wavpack/init.luau"], +[21191, "src/Rosetta/cad/step/init.luau"], +[21573, "src/Rosetta/cad/step/Brep.luau"], +[21808, "src/Rosetta/cad/step/Parse.luau"], +[22365, "src/Rosetta/cad/step/Write.luau"], +[22613, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22932, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23815, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24150, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24309, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25194, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25295, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26049, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26351, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26585, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27004, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27416, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27631, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28392, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28489, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28500, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29449, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30046, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30242, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30491, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31449, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31668, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31852, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32061, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32407, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32421, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32480, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34083, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34375, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34760, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35401, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35542, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35768, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36113, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36994, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37372, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37386, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39233, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40298, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40358, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40818, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41155, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41388, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43424, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43798, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44061, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44358, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44640, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44999, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45053, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45196, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45709, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46490, "src/Rosetta/codecs/audio/Stream.luau"], +[46651, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47133, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47411, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47580, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47708, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49696, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49812, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49929, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50181, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50194, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50578, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51144, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51565, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51604, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51656, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51878, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53333, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53396, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53483, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54452, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55320, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55368, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55884, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56210, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56630, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57065, "src/Rosetta/codecs/compress/Explode.luau"], +[57261, "src/Rosetta/codecs/compress/Lz4.luau"], +[57530, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58134, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58674, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58712, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59185, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59361, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59629, "src/Rosetta/codecs/compress/Lzx.luau"], +[60063, "src/Rosetta/codecs/compress/PackBits.luau"], +[60153, "src/Rosetta/codecs/compress/Quantum.luau"], +[60390, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60694, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60763, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60820, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61778, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61930, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62212, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62223, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62437, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62681, "src/Rosetta/codecs/font/Bitmap.luau"], +[62882, "src/Rosetta/codecs/font/Cff/init.luau"], +[63523, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63673, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63987, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64379, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64881, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64988, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65477, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65906, "src/Rosetta/codecs/image/Blend.luau"], +[66285, "src/Rosetta/codecs/image/Dct/init.luau"], +[66666, "src/Rosetta/codecs/image/Etc.luau"], +[66964, "src/Rosetta/codecs/image/Half.luau"], +[67033, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67387, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67795, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68032, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68792, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69673, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70119, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70197, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70264, "src/Rosetta/codecs/image/Pixels.luau"], +[70528, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70987, "src/Rosetta/codecs/image/Raster.luau"], +[71684, "src/Rosetta/codecs/image/Texel.luau"], +[72057, "src/Rosetta/codecs/image/Texture.luau"], +[72202, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72332, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74288, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74547, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74796, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74915, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75019, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75872, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76824, "src/Rosetta/codecs/image/Yuv.luau"], +[77092, "src/Rosetta/codecs/model/Draco/init.luau"], +[77424, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77893, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79082, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79231, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[79590, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[80552, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81026, "src/Rosetta/codecs/model/Mat4.luau"], +[81285, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81813, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[82365, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[82444, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[82551, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82757, "src/Rosetta/codecs/model/Polygon.luau"], +[82991, "src/Rosetta/codecs/model/Rbx/init.luau"], +[83228, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83982, "src/Rosetta/codecs/model/Rig.luau"], +[84225, "src/Rosetta/codecs/model/Sampler.luau"], +[84385, "src/Rosetta/codecs/model/Vrml/init.luau"], +[84533, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85107, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[85270, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86019, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[86541, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[87268, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[87500, "src/Rosetta/codecs/text/Json/init.luau"], +[87769, "src/Rosetta/codecs/text/Json/Decode.luau"], +[88183, "src/Rosetta/codecs/text/Json/Encode.luau"], +[88485, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88838, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[89530, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[90170, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[90408, "src/Rosetta/codecs/text/Text/init.luau"], +[90499, "src/Rosetta/codecs/text/Url/init.luau"], +[90704, "src/Rosetta/codecs/text/Xml/init.luau"], +[91107, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91847, "src/Rosetta/codecs/video/Dsp.luau"], +[92570, "src/Rosetta/codecs/video/H263/init.luau"], +[92726, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[93584, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93787, "src/Rosetta/codecs/video/H264/init.luau"], +[94160, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[94435, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[95566, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[96334, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[96592, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[97601, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97855, "src/Rosetta/codecs/video/H264/Intra.luau"], +[98262, "src/Rosetta/codecs/video/H264/Mb.luau"], +[99168, "src/Rosetta/codecs/video/H264/Params.luau"], +[99615, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99866, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99907, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100072, "src/Rosetta/codecs/video/Legacy/init.luau"], +[100270, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[100567, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100934, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101052, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[101160, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[101433, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101828, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102005, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102017, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[102384, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103891, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104030, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[104168, "src/Rosetta/codecs/video/Theora/init.luau"], +[104431, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105695, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106058, "src/Rosetta/codecs/video/Video/init.luau"], +[106615, "src/Rosetta/codecs/video/Video/Source.luau"], +[106900, "src/Rosetta/containers/Archive.luau"], +[107167, "src/Rosetta/containers/AudioWrap.luau"], +[107670, "src/Rosetta/containers/Avi/init.luau"], +[108222, "src/Rosetta/containers/Chunks.luau"], +[108357, "src/Rosetta/containers/Cpio.luau"], +[108785, "src/Rosetta/containers/Demux.luau"], +[109060, "src/Rosetta/containers/Ebml/init.luau"], +[109373, "src/Rosetta/containers/Fat.luau"], +[110061, "src/Rosetta/containers/Iso9660.luau"], +[110566, "src/Rosetta/containers/IsoBmff/init.luau"], +[110736, "src/Rosetta/containers/IsoBmff/Box.luau"], +[110924, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[111769, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[112290, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[112806, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[112923, "src/Rosetta/containers/MacFile.luau"], +[113072, "src/Rosetta/containers/MpegEs.luau"], +[113238, "src/Rosetta/containers/MpegPs/init.luau"], +[113458, "src/Rosetta/containers/MpegTs/init.luau"], +[114250, "src/Rosetta/containers/Ogg/init.luau"], +[114675, "src/Rosetta/containers/Ogg/Mux.luau"], +[114870, "src/Rosetta/containers/Ogg/Page.luau"], +[115039, "src/Rosetta/containers/Riff/init.luau"], +[115356, "src/Rosetta/containers/Tar.luau"], +[115770, "src/Rosetta/containers/Zip/init.luau"], +[116402, "src/Rosetta/core/Adler32.luau"], +[116448, "src/Rosetta/core/Base64.luau"], +[116607, "src/Rosetta/core/Bits.luau"], +[116900, "src/Rosetta/core/Bytes.luau"], +[117427, "src/Rosetta/core/Crc16.luau"], +[117479, "src/Rosetta/core/Crc32.luau"], +[117591, "src/Rosetta/core/Err.luau"], +[117673, "src/Rosetta/core/Input.luau"], +[117749, "src/Rosetta/core/Md5.luau"], +[117908, "src/Rosetta/core/Sniff.luau"], +[117937, "src/Rosetta/data/cbor/init.luau"], +[118036, "src/Rosetta/data/cbor/Codec.luau"], +[118605, "src/Rosetta/data/csv/init.luau"], +[118917, "src/Rosetta/data/ini/init.luau"], +[119163, "src/Rosetta/data/json/init.luau"], +[119255, "src/Rosetta/data/msgpack/init.luau"], +[119344, "src/Rosetta/data/msgpack/Codec.luau"], +[119786, "src/Rosetta/data/nbt/init.luau"], +[119845, "src/Rosetta/data/plist/init.luau"], +[120151, "src/Rosetta/data/plist/Binary.luau"], +[120418, "src/Rosetta/data/snbt/init.luau"], +[120481, "src/Rosetta/data/toml/init.luau"], +[120548, "src/Rosetta/data/toml/Decode.luau"], +[121176, "src/Rosetta/data/toml/Encode.luau"], +[121385, "src/Rosetta/data/xml/init.luau"], +[121441, "src/Rosetta/data/yaml/init.luau"], +[121514, "src/Rosetta/data/yaml/Emit.luau"], +[121804, "src/Rosetta/data/yaml/Parse.luau"], +[123097, "src/Rosetta/font/bdf/init.luau"], +[123386, "src/Rosetta/font/bmfont/init.luau"], +[123813, "src/Rosetta/font/bmfont/Parse.luau"], +[124266, "src/Rosetta/font/eot/init.luau"], +[124498, "src/Rosetta/font/fon/init.luau"], +[124781, "src/Rosetta/font/hershey/init.luau"], +[124976, "src/Rosetta/font/pcf/init.luau"], +[125256, "src/Rosetta/font/psf/init.luau"], +[125576, "src/Rosetta/font/ttf/init.luau"], +[125627, "src/Rosetta/font/type1/init.luau"], +[125986, "src/Rosetta/font/type1/Charstring.luau"], +[126264, "src/Rosetta/font/woff/init.luau"], +[126396, "src/Rosetta/font/woff2/init.luau"], +[126453, "src/Rosetta/font/woff2/Rebuild.luau"], +[126993, "src/Rosetta/host/init.luau"], +[127038, "src/Rosetta/host/Love.luau"], +[127181, "src/Rosetta/host/LuaJIT.luau"], +[127231, "src/Rosetta/host/Luau.luau"], +[127254, "src/Rosetta/host/Roblox.luau"], +[127613, "src/Rosetta/image/ani/init.luau"], +[127793, "src/Rosetta/image/blp/init.luau"], +[128051, "src/Rosetta/image/bmp/init.luau"], +[128466, "src/Rosetta/image/dds/init.luau"], +[128949, "src/Rosetta/image/exr/init.luau"], +[129709, "src/Rosetta/image/exr/Codec.luau"], +[129820, "src/Rosetta/image/exr/Piz.luau"], +[130177, "src/Rosetta/image/gif/init.luau"], +[130693, "src/Rosetta/image/gif/Decode.luau"], +[130756, "src/Rosetta/image/hdr/init.luau"], +[130985, "src/Rosetta/image/hdr/Codec.luau"], +[131196, "src/Rosetta/image/icns/init.luau"], +[131527, "src/Rosetta/image/ico/init.luau"], +[131804, "src/Rosetta/image/ico/Dib.luau"], +[131899, "src/Rosetta/image/ilbm/init.luau"], +[132218, "src/Rosetta/image/jpeg/init.luau"], +[132354, "src/Rosetta/image/ktx/init.luau"], +[133014, "src/Rosetta/image/pcx/init.luau"], +[133278, "src/Rosetta/image/png/init.luau"], +[133858, "src/Rosetta/image/png/Apng.luau"], +[133938, "src/Rosetta/image/png/Decode.luau"], +[134178, "src/Rosetta/image/png/Encode.luau"], +[134333, "src/Rosetta/image/pnm/init.luau"], +[134711, "src/Rosetta/image/pnm/Codec.luau"], +[134988, "src/Rosetta/image/qoi/init.luau"], +[135110, "src/Rosetta/image/qoi/Codec.luau"], +[135260, "src/Rosetta/image/sgi/init.luau"], +[135545, "src/Rosetta/image/sunras/init.luau"], +[135791, "src/Rosetta/image/tga/init.luau"], +[136061, "src/Rosetta/image/tga/Codec.luau"], +[136213, "src/Rosetta/image/tiff/init.luau"], +[137040, "src/Rosetta/image/tiff/Pixels.luau"], +[137430, "src/Rosetta/image/tim/init.luau"], +[137672, "src/Rosetta/image/vtf/init.luau"], +[137907, "src/Rosetta/image/webp/init.luau"], +[138517, "src/Rosetta/image/webp/Alpha.luau"], +[138593, "src/Rosetta/image/webp/Anim.luau"], +[138748, "src/Rosetta/image/xbm/init.luau"], +[138909, "src/Rosetta/image/xpm/init.luau"], +[139177, "src/Rosetta/image/xpm/Names.luau"], +[139233, "src/Rosetta/layered/aseprite/init.luau"], +[139971, "src/Rosetta/layered/ora/init.luau"], +[140258, "src/Rosetta/layered/psd/init.luau"], +[140993, "src/Rosetta/layered/psd/Channels.luau"], +[141345, "src/Rosetta/model/3ds/init.luau"], +[141428, "src/Rosetta/model/3ds/Build.luau"], +[142075, "src/Rosetta/model/3ds/Read.luau"], +[142571, "src/Rosetta/model/3ds/Write.luau"], +[143376, "src/Rosetta/model/3mf/init.luau"], +[143458, "src/Rosetta/model/3mf/Read.luau"], +[144046, "src/Rosetta/model/3mf/Write.luau"], +[144451, "src/Rosetta/model/b3d/init.luau"], +[144506, "src/Rosetta/model/b3d/Read.luau"], +[145077, "src/Rosetta/model/bsp/init.luau"], +[145222, "src/Rosetta/model/bsp/Brush.luau"], +[145500, "src/Rosetta/model/bsp/Quake3.luau"], +[145755, "src/Rosetta/model/dae/init.luau"], +[145944, "src/Rosetta/model/dae/Math.luau"], +[145991, "src/Rosetta/model/dae/Read.luau"], +[147841, "src/Rosetta/model/dae/Write.luau"], +[148210, "src/Rosetta/model/fbx/init.luau"], +[148358, "src/Rosetta/model/fbx/Ascii.luau"], +[148628, "src/Rosetta/model/fbx/Binary.luau"], +[149083, "src/Rosetta/model/fbx/Read.luau"], +[150445, "src/Rosetta/model/fbx/Write.luau"], +[151430, "src/Rosetta/model/fbx/Xform.luau"], +[151471, "src/Rosetta/model/gltf/init.luau"], +[151708, "src/Rosetta/model/gltf/Pack.luau"], +[151777, "src/Rosetta/model/gltf/Read.luau"], +[152508, "src/Rosetta/model/gltf/Write.luau"], +[153188, "src/Rosetta/model/iqm/init.luau"], +[153264, "src/Rosetta/model/iqm/Read.luau"], +[153619, "src/Rosetta/model/iqm/Write.luau"], +[154306, "src/Rosetta/model/ldraw/init.luau"], +[154384, "src/Rosetta/model/ldraw/Colors.luau"], +[154702, "src/Rosetta/model/ldraw/Read.luau"], +[155279, "src/Rosetta/model/lwo/init.luau"], +[155355, "src/Rosetta/model/lwo/Build.luau"], +[155817, "src/Rosetta/model/lwo/Parse.luau"], +[156360, "src/Rosetta/model/mca/init.luau"], +[156702, "src/Rosetta/model/mca/Chunk.luau"], +[156835, "src/Rosetta/model/mca/Lz4Block.luau"], +[156905, "src/Rosetta/model/md2/init.luau"], +[157104, "src/Rosetta/model/md3/init.luau"], +[157332, "src/Rosetta/model/md5/init.luau"], +[157413, "src/Rosetta/model/md5/Read.luau"], +[157846, "src/Rosetta/model/mdl/init.luau"], +[157928, "src/Rosetta/model/mdl/HalfLife.luau"], +[158256, "src/Rosetta/model/mdl/Quake.luau"], +[158474, "src/Rosetta/model/ms3d/init.luau"], +[158546, "src/Rosetta/model/ms3d/Read.luau"], +[158992, "src/Rosetta/model/ms3d/Write.luau"], +[159461, "src/Rosetta/model/obj/init.luau"], +[160203, "src/Rosetta/model/obj/Mtl.luau"], +[160490, "src/Rosetta/model/off/init.luau"], +[160952, "src/Rosetta/model/ply/init.luau"], +[162057, "src/Rosetta/model/ply/Binary.luau"], +[162258, "src/Rosetta/model/pmx/init.luau"], +[162327, "src/Rosetta/model/pmx/Build.luau"], +[162623, "src/Rosetta/model/pmx/Pmd.luau"], +[162958, "src/Rosetta/model/pmx/Read.luau"], +[163362, "src/Rosetta/model/qb/init.luau"], +[163755, "src/Rosetta/model/rbxm/init.luau"], +[164347, "src/Rosetta/model/rbxmx/init.luau"], +[165000, "src/Rosetta/model/robloxmesh/init.luau"], +[165659, "src/Rosetta/model/robloxmesh/Parse.luau"], +[166116, "src/Rosetta/model/robloxmesh/Write.luau"], +[166225, "src/Rosetta/model/schematic/init.luau"], +[166546, "src/Rosetta/model/schematic/Common.luau"], +[166666, "src/Rosetta/model/schematic/Litematic.luau"], +[166877, "src/Rosetta/model/schematic/Mcedit.luau"], +[167121, "src/Rosetta/model/schematic/Sponge.luau"], +[167250, "src/Rosetta/model/smd/init.luau"], +[167317, "src/Rosetta/model/smd/Read.luau"], +[167586, "src/Rosetta/model/smd/Write.luau"], +[167829, "src/Rosetta/model/stl/init.luau"], +[168279, "src/Rosetta/model/stl/Decode.luau"], +[168353, "src/Rosetta/model/usda/init.luau"], +[168562, "src/Rosetta/model/usda/Build.luau"], +[169840, "src/Rosetta/model/usda/Parse.luau"], +[170638, "src/Rosetta/model/usda/Write.luau"], +[171455, "src/Rosetta/model/vox/init.luau"], +[172341, "src/Rosetta/model/vox/Grid.luau"], +[172398, "src/Rosetta/model/vrml/init.luau"], +[172464, "src/Rosetta/model/x/init.luau"], +[172594, "src/Rosetta/model/x/Build.luau"], +[173157, "src/Rosetta/model/x/Parse.luau"], +[173454, "src/Rosetta/model/x3d/init.luau"], +[173532, "src/Rosetta/music/669/init.luau"], +[173738, "src/Rosetta/music/ahx/init.luau"], +[173789, "src/Rosetta/music/far/init.luau"], +[174018, "src/Rosetta/music/hmp/init.luau"], +[174282, "src/Rosetta/music/hvl/init.luau"], +[174333, "src/Rosetta/music/it/init.luau"], +[174751, "src/Rosetta/music/it/Itsex.luau"], +[174867, "src/Rosetta/music/med/init.luau"], +[175514, "src/Rosetta/music/midi/init.luau"], +[175657, "src/Rosetta/music/midi/Smf.luau"], +[176068, "src/Rosetta/music/mod/init.luau"], +[176421, "src/Rosetta/music/mtm/init.luau"], +[176643, "src/Rosetta/music/mus/init.luau"], +[176800, "src/Rosetta/music/okt/init.luau"], +[177081, "src/Rosetta/music/ptm/init.luau"], +[177303, "src/Rosetta/music/s3m/init.luau"], +[177539, "src/Rosetta/music/sf2/init.luau"], +[177582, "src/Rosetta/music/stm/init.luau"], +[177813, "src/Rosetta/music/ult/init.luau"], +[178117, "src/Rosetta/music/umx/init.luau"], +[178333, "src/Rosetta/music/xm/init.luau"], +[178894, "src/Rosetta/music/xmi/init.luau"], +[179102, "src/Rosetta/ops/AudioOps.luau"], +[179551, "src/Rosetta/ops/ImageOps/init.luau"], +[180195, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[180705, "src/Rosetta/ops/LayerOps.luau"], +[180798, "src/Rosetta/ops/MeshOps/init.luau"], +[181834, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[182001, "src/Rosetta/ops/MusicOps.luau"], +[182349, "src/Rosetta/playlist/m3u/init.luau"], +[182702, "src/Rosetta/playlist/pls/init.luau"], +[182880, "src/Rosetta/playlist/xspf/init.luau"], +[183083, "src/Rosetta/subtitle/ass/init.luau"], +[183527, "src/Rosetta/subtitle/srt/init.luau"], +[183700, "src/Rosetta/subtitle/vtt/init.luau"], +[183903, "src/Rosetta/vector/svg/init.luau"], +[183989, "src/Rosetta/vector/svg/Parse.luau"], +[184735, "src/Rosetta/vector/svg/PathData.luau"], +[185103, "src/Rosetta/vector/svg/Render.luau"], +[185520, "src/Rosetta/vector/svg/Style.luau"], +[185892, "src/Rosetta/vector/svg/Write.luau"], +[186092, "src/Rosetta/vector/tiled/init.luau"], +[186272, "src/Rosetta/vector/tiled/Data.luau"], +[186423, "src/Rosetta/vector/tiled/Tmj.luau"], +[187054, "src/Rosetta/vector/tiled/Tmx.luau"], +[187666, "src/Rosetta/video/avi/init.luau"], +[187960, "src/Rosetta/video/fli/init.luau"], +[188111, "src/Rosetta/video/flv/init.luau"], +[188495, "src/Rosetta/video/flv/Amf.luau"], +[188653, "src/Rosetta/video/flv/Mux.luau"], +[188934, "src/Rosetta/video/h264/init.luau"], +[189073, "src/Rosetta/video/mkv/init.luau"], +[189229, "src/Rosetta/video/mkv/Mux.luau"], +[189508, "src/Rosetta/video/mkv/Parse.luau"], +[190229, "src/Rosetta/video/mp4/init.luau"], +[190557, "src/Rosetta/video/mpegps/init.luau"], +[190744, "src/Rosetta/video/mpegts/init.luau"], +[190982, "src/Rosetta/video/ogv/init.luau"], +[191377, "src/Rosetta/video/smk/init.luau"], +[191686, "src/Rosetta/video/smk/Audio.luau"], +[191806, "src/Rosetta/video/y4m/init.luau"] ]