diff --git a/README.md b/README.md index 116c697..0e38c0b 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -178 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +181 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -120,6 +120,7 @@ adds each format's capabilities. | 3D models | iqm | .iqm | yes | yes | | 3D models | ldraw | .ldr .mpd .dat | yes | - | | 3D models | lwo | .lwo .lxo | yes | - | +| 3D models | map | .map | yes | yes | | 3D models | mca | .mca .mcr | yes | - | | 3D models | md2 | .md2 | yes | - | | 3D models | md3 | .md3 | yes | - | @@ -139,6 +140,8 @@ adds each format's capabilities. | 3D models | sourcemdl | .mdl | yes | - | | 3D models | stl | .stl | yes | yes | | 3D models | usda | .usda .usd .usdz | yes | yes | +| 3D models | vbsp | .bsp | yes | - | +| 3D models | vmf | .vmf .vmx | yes | yes | | 3D models | vox | .vox | yes | yes | | 3D models | vrml | .wrl .wrz .vrml | yes | yes | | 3D models | x | .x | yes | - | @@ -243,8 +246,8 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs//` | compress | Brotli, Bzip2, Deflate, Explode, Lz4, Lzh, Lzma, Lzw, Lzx, PackBits, Quantum, UnixCompress, Xxh32, Zstd | | entropy | Huffman, RangeCoder | | font | Bitmap, Cff, GlyphNames, TrueType | -| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | -| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml | +| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Miptex, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | +| model | Brush, Displacement, Draco, Mat4, MeshFlatten, Minecraft, Patch, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml | | text | Json, KeyValues, Nbt, Text, Url, Xml | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | diff --git a/build/Rosetta.luau b/build/Rosetta.luau index 6eee2cd..cbc8ce3 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -1624,7 +1624,7 @@ local list: { Entry } = { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, load = function() return __include("model/bsp") @@ -1714,6 +1714,18 @@ local list: { Entry } = { return __include("model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return __include("model/map") + end, + }, { name = "mca", category = "model", @@ -1942,6 +1954,30 @@ local list: { Entry } = { return __include("model/usda") end, }, + { + name = "vbsp", + category = "model", + path = "model/vbsp", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, + load = function() + return __include("model/vbsp") + end, + }, + { + name = "vmf", + category = "model", + path = "model/vmf", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, + load = function() + return __include("model/vmf") + end, + }, { name = "vox", category = "model", @@ -69694,12 +69730,229 @@ end return Yuv end +__FILES["codecs/image/Miptex"] = function() + +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Quantize = __include("codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +type Header = { name: string, width: number, height: number, offsets: { number } } +type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } +type DecodeOptions = { + palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own + goldsrc: boolean?, -- read the palette stored after mip 3 + mip: number?, -- 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: names starting with '{' + maxPixels: number?, -- default 2^24 +} + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) + if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b: buffer, at: number, size: number, hd: Header): buffer? + local w, h = hd.width, hd.height + local p = hd.offsets[4] + (w // 8) * (h // 8) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = hd.width // (2 ^ mip), hd.height // (2 ^ mip) + if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 1, 1) == "{" + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local w2, h2 = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) + local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + local colors: { { number } } + if palette then + colors = Pixels.colorList(palette) + elseif goldsrc then + colors = Quantize.palette(img.pixels, w, h, 256) + else + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local levels: { buffer } = {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil }) + if keyed then + for k = 0, lw * lh - 1 do + if readu8(px, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + levels[m + 1] = idx + end + local total = 40 + for _, l in levels do + total += buffer.len(l) + end + local palAt = total + if goldsrc then + total += 2 + 768 + 2 + end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in levels do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o += buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) + if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out: { Lump } = {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps: { Lump }, name: string): Lump? + local want = string.lower(name) + local best: Lump? = nil + for _, l in lumps do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +return Miptex +end __FILES["codecs/image/Pixels"] = function() --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -69956,6 +70209,61 @@ function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boole return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +function Pixels.grey(): buffer + local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and +-- '{' textures) +function Pixels.keyed(pal: buffer, index: number): buffer + local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu32(out, index * 4, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +function Pixels.colorList(pal: buffer, n: number?): { { number } } + local out: { { number } } = {} + for i = 0, math.clamp(n or 256, 0, buffer.len(pal) // 4) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? + local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +function Pixels.paletteBytes(pal: buffer, n: number?): buffer + local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels end __FILES["codecs/image/Quantize"] = function() @@ -76522,6 +76830,795 @@ end return Yuv end +__FILES["codecs/model/Brush"] = function() + + + +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = __include("Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) +type Face = { + plane: Plane, + texture: string?, + vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) + bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths + [string]: any, +} +type Polygon = { + brush: number, + face: number, + points: { number }, -- x, y, z per corner, counter-clockwise seen from the front + normal: { number }, +} +type Options = { + epsilon: number?, -- plane side tolerance, default 1e-3 + size: number?, -- half size of the starting winding, default 2^17 + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + hull: boolean?, -- drop face parts inside / touching other brushes, default false + maxPolygons: number?, -- default 2^20 +} +type Built = { texture: string, primitive: Types.Primitive } + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +local function snap(x: number): number + local r = floor(x + 0.5) + return if abs(x - r) < 1e-6 then r else x +end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +function Brush.baseAxis(n: { number }): number + local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } + local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 + local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 3 + for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } + local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +function Brush.axisBase(normal: { number }): ({ number }, { number }) + local nx, ny, nz = normal[1], normal[2], normal[3] + nx = if abs(nx) < 1e-6 then 0 else nx + ny = if abs(ny) < 1e-6 then 0 else ny + nz = if abs(nz) < 1e-6 then 0 else nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) + local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +function Brush.baseWinding(p: Plane, size: number): { number } + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) + local n = #pts // 3 + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = table.create(n, 0) :: { number } + local side = table.create(n, 0) :: { number } + local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front += 1 + elseif v < -eps then + side[i + 1] = -1 + back += 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f: { number }, b: { number } = {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +local function clean(pts: { number }, eps: number): { number }? + local out: { number } = {} + local n = #pts // 3 + for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = #out // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return if #out >= 9 then out else nil +end + +local function samePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +local function oppositePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } + local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out: { { number }? } = {} + for i, p in planes do + local w: { number }? = Brush.baseWinding(p, size) + for j, q in planes do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = if on then nil else back + end + end + end + out[i] = if w then clean(w, eps) else nil + end + return out +end + +local function bounds(polys: { Polygon }): { number } + local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in polys do + local pts = p.points + for k = 0, #pts // 3 - 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } + local kept: { { number } } = {} + local inside: { number }? = pts + for _, q in planes do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +local function faceKey(f: Face): string + local parts = { f.texture or "" } + for _, m in { f.vecs, f.bp } do + if m then + for _, row in m do + for _, v in row do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +local function convex(pts: { number }, n: { number }, eps: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? + local n1, n2 = #f1 // 3, #f2 // 3 + for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out: { number } = {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } + local groups: { [string]: { Polygon } } = {} + local order: { string } = {} + for _, p in polys do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out: { Polygon } = {} + for _, key in order do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in g do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) + local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per: { { Polygon } } = {} + local planesOf: { { Plane } } = {} + local count = 0 + for bi, faces in brushes do + local planes: { Plane } = {} + for fi, f in faces do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list: { Polygon } = {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count += #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all: { Polygon } = {} + if opts and opts.hull then + local boxes: { { number } } = {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in per[bi] do + local frags: { { number } } = { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags: { { number } } = {} + for _, fr in frags do + for _, kept in outside(fr, own, bi, bj, planesOf[bj], eps) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in frags do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in per[bi] do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +function Brush.area(pts: { number }): number + local n = #pts // 3 + local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax += uy * vz - uz * vy + ay += uz * vx - ux * vz + az += ux * vy - uy * vx + end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } + type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + local byTex: { [string]: Acc } = {} + local order: { Acc } = {} + local sizes: { [string]: { number } } = {} + for _, p in polys do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a: Acc = acc + local pts = p.points + local n = #pts // 3 + local base = #a.pos // 3 + for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out: { Built } = {} + for _, a in order do + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" :: "triangles", + }, + }) + end + return out +end + +return Brush +end +__FILES["codecs/model/Displacement"] = function() + +-- codecs/model/Displacement: Source engine displacement surfaces (VBSP ddispinfo_t / Hammer dispinfo), as +-- CCoreDispInfo::GenerateDispSurf of the Source SDK 2013 (no code taken): corner 0 is the base face corner nearest the +-- start position, rows run along corner 0 -> 1, columns along 0 -> 3 (the face's own, clockwise, winding), each vertex +-- moved by its offset; the 2^power quads split along alternating diagonals. Normals come from the grid. +local Types = __include("Types") + +local Displacement = {} + +local sqrt = math.sqrt + +type Surface = { + n: number, -- vertices per row: 2^power + 1 + flat: { number }, -- x, y, z on the base face (texture coordinates are projected from these) + pos: { number }, -- x, y, z displaced + nrm: { number }, -- unit normals on the face normal's side + idx: { number }, -- 0-based triangles, counter-clockwise seen from the face normal's side +} + +local function cross(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number, number) + return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx +end + +-- corners: the 4 face corners (12 numbers) in the face's clockwise winding; offsets: n * n * 3 numbers (row major, +-- row = i along corner 0 -> 1) added to the flat grid; normal: the face's outward normal +function Displacement.surface(corners: { number }, start: { number }, power: number, offsets: { number }, normal: { number }): (Surface?, string?) + if #corners ~= 12 then + return nil, "a displacement needs a 4-sided face" + end + if power < 1 or power > 4 or power % 1 ~= 0 then + return nil, "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + if #offsets < n * n * 3 then + return nil, "displacement offsets truncated" + end + local best, bestD = 0, math.huge + for k = 0, 3 do + local dx, dy, dz = corners[k * 3 + 1] - start[1], corners[k * 3 + 2] - start[2], corners[k * 3 + 3] - start[3] + local d = dx * dx + dy * dy + dz * dz + if d < bestD then + best, bestD = k, d + end + end + local c: { number } = table.create(12) :: any + for k = 0, 3 do + local s = ((best + k) % 4) * 3 + c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = corners[s + 1], corners[s + 2], corners[s + 3] + end + local flat: { number } = table.create(n * n * 3) :: any + local pos: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local t = i / (n - 1) + local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t + local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t + for j = 0, n - 1 do + local s = j / (n - 1) + local k = (i * n + j) * 3 + local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s + flat[k + 1], flat[k + 2], flat[k + 3] = x, y, z + pos[k + 1], pos[k + 2], pos[k + 3] = x + offsets[k + 1], y + offsets[k + 2], z + offsets[k + 3] + end + end + local nx, ny, nz = normal[1], normal[2], normal[3] + local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3]) + local sign = if ux * nx + uy * ny + uz * nz >= 0 then 1 else -1 + local nrm: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1) + for j = 0, n - 1 do + local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1) + local a, b = (i1 * n + j) * 3, (i0 * n + j) * 3 + local e, f = (i * n + j1) * 3, (i * n + j0) * 3 + local x, y, z = cross(pos[a + 1] - pos[b + 1], pos[a + 2] - pos[b + 2], pos[a + 3] - pos[b + 3], pos[e + 1] - pos[f + 1], pos[e + 2] - pos[f + 2], pos[e + 3] - pos[f + 3]) + local l = sqrt(x * x + y * y + z * z) + local k = (i * n + j) * 3 + if l < 1e-12 then + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + else + nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l + end + end + end + -- triangle (i, j), (i + 1, j), (i, j + 1) turns about rows x columns: flipped when that faces away + local idx: { number } = table.create((n - 1) * (n - 1) * 6) :: any + local flip = sign < 0 + for i = 0, n - 2 do + for j = 0, n - 2 do + local a = i * n + j + local b, cc, d = a + n, a + n + 1, a + 1 + local t1, t2, t3, t4, t5, t6 + if (i + j) % 2 == 0 then + t1, t2, t3, t4, t5, t6 = a, b, d, b, cc, d + else + t1, t2, t3, t4, t5, t6 = a, b, cc, a, cc, d + end + if flip then + t2, t3, t5, t6 = t3, t2, t6, t5 + end + local q = #idx + idx[q + 1], idx[q + 2], idx[q + 3], idx[q + 4], idx[q + 5], idx[q + 6] = t1, t2, t3, t4, t5, t6 + end + end + return { n = n, flat = flat, pos = pos, nrm = nrm, idx = idx }, nil +end + +type Arrays = { + pos: { number }, + nrm: { number }, + uv: { number }, + idx: { number }, -- 0-based + blend: { number }?, -- per vertex 0..1: the _BLEND attribute (displacement alpha) +} + +-- flat arrays -> an indexed triangle primitive (POSITION, NORMAL, TEXCOORD_0, _BLEND) +function Displacement.primitive(a: Arrays): Types.Primitive + local writef32, writeu32 = buffer.writef32, buffer.writeu32 + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + local attrs: { [string]: Types.Accessor } = { + POSITION = S.accessor(pb, "f32", 3, nv), + NORMAL = S.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = S.accessor(ub, "f32", 2, nv), + } + local blend = a.blend + if blend then + local bb = buffer.create(nv * 4) + for k = 1, nv do + writef32(bb, (k - 1) * 4, blend[k] or 0) + end + attrs._BLEND = S.accessor(bb, "f32", 1, nv) + end + return { attributes = attrs, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" } +end + +return Displacement +end __FILES["codecs/model/Draco"] = function() -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). @@ -82187,6 +83284,130 @@ end return Packed end +__FILES["codecs/model/Patch"] = function() + + + +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +function Patch.valid(w: number, h: number, n: number): boolean + return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) + local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = (w - 1) // 2, (h - 1) // 2 + local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = table.create(gw * gh * comps, 0) :: { number } + for gy = 0, gh - 1 do + local sy = math.min(gy // lv, py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(gx // lu, px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 + local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) + local c = row + i * comps + for k = 1, comps do + out[o + k] += ctrl[c + k] * wgt + end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +function Patch.triangles(gw: number, gh: number): { number } + local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } + for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +function Patch.normalize(pts: { number }, comps: number, at: number) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } + local out = table.create(gw * gh * 3, 0) :: { number } + local function at(x: number, y: number, k: number): number + return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, i // gw + for _, d in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } } do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch +end __FILES["codecs/model/Polygon"] = function() -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. @@ -88150,7 +89371,7 @@ local KeyValues = {} type Pair = Binary.Pair type Block = Binary.Block type ParseOptions = { - escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true + escapes: (boolean | "quotes")?, -- \n \t \\ \" ... in quoted strings, default true; "quotes": only \" -- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the -- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with -- its cond @@ -88159,8 +89380,11 @@ type ParseOptions = { maxDepth: number?, -- default 256 } type WriteOptions = { - escapes: boolean?, -- default true + escapes: (boolean | "quotes")?, -- default true; "quotes": only " is escaped indent: string?, -- default "\t" + separator: string?, -- between a key and its value, default "\t" (Hammer: " ") + bareBlocks: boolean?, -- block names unquoted when they are plain words (Hammer), default false + flatBlocks: { [string]: boolean }?, -- blocks whose pairs keep the block's own indent (Hammer's dispinfo rows) } type ObjectOptions = { duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array @@ -88170,7 +89394,7 @@ local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true } local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' } -type Lexer = { s: string, i: number, n: number, escapes: boolean } +type Lexer = { s: string, i: number, n: number, escapes: boolean, quotesOnly: boolean?, quoted: boolean? } -- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string local function token(lx: Lexer): (string?, string?, number, string?) @@ -88199,6 +89423,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) lx.i = i + 1 return c, nil, i - 1, nil elseif c == '"' then + lx.quoted = true local start = i i += 1 if not lx.escapes then @@ -88223,7 +89448,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "s", table.concat(parts), start - 1, nil end local x = string.sub(s, e + 1, e + 1) - local r = ESCAPE[x] + local r = if lx.quotesOnly and x ~= '"' then nil else ESCAPE[x] if r then table.insert(parts, r) i = e + 2 @@ -88240,6 +89465,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "[", string.sub(s, i + 1, e - 1), i - 1, nil end end + lx.quoted = false local e = string.find(s, '[ \t\r\n\f\v"{}]', i) local stop = if e then e - 1 else n lx.i = stop + 1 @@ -88284,7 +89510,7 @@ end local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?) local o: ParseOptions = opts or {} - local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false } + local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false, quotesOnly = o.escapes == "quotes" } if string.sub(text, 1, 3) == "\239\187\191" then lx.i = 4 end @@ -88324,6 +89550,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at) else local key = v :: string + local keyQuoted = lx.quoted local k2, v2, at2, terr2 = token(lx) if terr2 then return nil, Err.new(Err.TRUNCATED, terr2, at2) @@ -88347,7 +89574,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl if not pass then skipping += 1 else - local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond } + local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond, bare = not keyQuoted } local last = cur[#cur] if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then cur[#cur] = pair @@ -88450,7 +89677,7 @@ function KeyValues.copy(b: Block): Block local out: Block = table.create(#b) :: any for i, p in b do local v: any = p.value - out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type } + out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type, bare = p.bare } end return out end @@ -88493,18 +89720,23 @@ function KeyValues.all(b: Block, key: string): { Pair } return out end -local function quote(s: string, escapes: boolean): string - if escapes then +local function quote(s: string, escapes: boolean | string): string + if escapes == "quotes" then + s = string.gsub(s, '"', '\\"') + elseif escapes then s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) end return '"' .. s .. '"' end -local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string? - if depth > 256 then +type WriteState = { indent: string, escapes: boolean | string, sep: string, bare: boolean, flat: { [string]: boolean } } + +local function writeBlock(b: Block, out: { string }, w: WriteState, level: number, depth: number?): string? + local dp = depth or 0 + if dp > 256 then return "nesting deeper than 256" end - local pad = string.rep(indent, level) + local pad = string.rep(w.indent, level) for _, p in b do if type(p) ~= "table" or type(p.key) ~= "string" then return "a pair needs a string key" @@ -88512,15 +89744,16 @@ local function writeBlock(b: Block, out: { string }, indent: string, level: numb local v: any = p.value local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else "" if type(v) == "table" then - table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n") - local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1) + local name = if w.bare and (p.bare or (p.bare == nil and string.match(p.key, "^[%w_]+$"))) then p.key else quote(p.key, w.escapes) + table.insert(out, pad .. name .. cond .. "\n" .. pad .. "{\n") + local err = writeBlock(v, out, w, if w.flat[p.key] then level else level + 1, dp + 1) if err then return err end table.insert(out, pad .. "}\n") elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v) - table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n") + table.insert(out, pad .. quote(p.key, w.escapes) .. w.sep .. quote(s, w.escapes) .. cond .. "\n") else return "unwritable value for key " .. p.key end @@ -88533,7 +89766,8 @@ function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?) return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list") end local out: { string } = {} - local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0) + local o: WriteOptions = opts or {} + local err = writeBlock(b, out, { indent = o.indent or "\t", escapes = if o.escapes == nil then true else o.escapes, sep = o.separator or "\t", bare = o.bareBlocks == true, flat = o.flatBlocks or {} }, 0) if err then return nil, Err.new(Err.ARG, err) end @@ -88707,6 +89941,7 @@ type Pair = { key: string, value: any, -- string | number | Block cond: string?, -- text: the [$CONDITION] kept when not evaluated + bare: boolean?, -- text: a block whose name was unquoted (written back so with bareBlocks) type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block) } type Block = { Pair } @@ -146199,7 +147434,7 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, } @@ -146331,6 +147566,7 @@ __FILES["model/bsp/Brush"] = function() -- size. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") local Brush = {} @@ -146363,34 +147599,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil + if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil - end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -146605,8 +147825,10 @@ end __FILES["model/bsp/Quake3"] = function() -- 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. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = __include("Types") +local Patch = __include("codecs/model/Patch") local Quake3 = {} @@ -146686,52 +147908,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: counts[if kind == 1 then "polygons" else "meshes"] += 1 elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches += 1 - local L = level - for py = 0, (h - 1) // 2 - 1 do - for px = 0, (w - 1) // 2 - 1 do - local ctrl: { { number } } = {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid: { number } = {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k] += cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - 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] - -- Quake's control grids are clockwise-front - for _, v in { a, d, c2, c2, d, e } do - table.insert(tris, v) - end - end - end - end + local ctrl = table.create(n * 14, 0) :: { number } + for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = table.create(gw * gh) :: { number } + for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number }) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(tris, ids[v + 1]) end else counts.skipped += 1 @@ -158137,6 +159330,1097 @@ end return Parse end +__FILES["model/map"] = function() + +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Miptex = __include("codecs/image/Miptex") +local Brush = __include("codecs/model/Brush") +local Parse = __include("model/map/Parse") +local Write = __include("model/map/Write") +local Build = __include("model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + epsilon: number?, -- default 1e-3 + patchLevel: number?, -- patchDef2 segments per sub-patch, default 4 + skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...) + textureSizes: { [string]: { number } }?, -- name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes + maxBrushes: number?, -- default 2^20 + maxPolygons: number?, -- default 2^20 +} +type EncodeOptions = { + variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Map.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c :: number) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return if game and string.match(s, "^%s*{") then 0.6 else 0 + end + return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m: Parse.Map): string + local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in m.entities do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in e.brushes do + if b.type ~= "brush" then + q3 = true + end + for _, f in b.faces or {} do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return if q2 then "quake2" else "quake" +end + +local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil + local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } } + local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in string.gmatch(spec, "[^;]+") do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w: number, h: number = 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] :: number, given[2] :: number + elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads :: any), 1, -1 do + local wd = (wads :: any)[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in { ".tga", ".jpg", ".png" } do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage :: any, b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw: number, fh: number = w :: number, h :: number + local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, if known then 1 else 0 } + return fw, fh, known + end +end + +function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f: Parse.Face): Parse.Face + if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x: number): string + return Write.num(x) +end + +function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents: { any } = {} + for _, node in scene.nodes do + local ex: any = node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {} + if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv: { Parse.Brush } = {} + for _, b in brushes do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in b.faces do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src: any = scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents :: { Parse.Entity }, + game = if fromMap then src.game else nil, + mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil, + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?) + local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil + if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m: Parse.Map): (string?, Err.Err?) + if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f: Parse.Face): Brush.Face? + return Build.face(f) +end + +return Map +end +__FILES["model/map/Build"] = function() + +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = __include("Types") +local Brush = __include("codecs/model/Brush") +local Patch = __include("codecs/model/Patch") +local Parse = __include("model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { + variant: string, -- "quake" | "valve220" | "quake2" | "quake3" + size: (name: string) -> (number, number, boolean), -- width, height, known + hull: boolean?, + merge: boolean?, + epsilon: number?, + patchLevel: number?, + skip: { string }?, + maxPolygons: number?, +} + +function Build.face(f: Parse.Face): Brush.Face? + local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out: Brush.Face = { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + +local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean + local size, pts = b.size :: { number }, b.points :: { number } + local w: number, h: number = size[1] :: number, size[2] :: number + if not Patch.valid(w, h, #pts // 5) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = table.create(w * h * 5, 0) :: { number } + for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params: { number } = b.params or {} + local explicit = b.type == "patchDef3" + local lu: number = if explicit then math.max(1, params[1] or 1) else level + local lv: number = if explicit then math.max(1, params[2] or 1) else level + local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = #acc.pos // 3 + for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a: Acc): Types.Primitive + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s: string?): { number }? + if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?) + local scene = Scene.new() + scene.meta.up = "z" + local skip: { [string]: boolean } = {} + for _, n in o.skip or {} do + skip[string.lower(n)] = true + end + local matOf: { [string]: number } = {} + local function material(name: string): number + local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities: { { [string]: string } } = {} + local polyTotal = 0 + for ei, ent in map.entities do + local keys = ent.keys + table.insert(entities, keys) + local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes: { { Brush.Face } } = {} + local patchAcc: { [string]: Acc } = {} + local patchOrder: { string } = {} + for _, b in ent.brushes do + if b.faces then + counts.brushes += 1 + local faces: { Brush.Face } = {} + for _, f in b.faces do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces += 1 + end + end + table.insert(brushes, faces) + else + counts.patches += 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then + skipped.patches += 1 + end + end + end + end + local prims: { Types.Primitive } = {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal += #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept: { Brush.Polygon } = {} + for _, p in polys do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name: string): (number, number) + local m = scene.materials[material(name)] + local e = (m.extras :: any).map + return e.width, e.height + end) + for _, bt in built do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in patchOrder do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build +end +__FILES["model/map/Parse"] = function() + +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = __include("Types") + +local Parse = {} + +type Face = { + points: { number }, -- 3 points: x, y, z each + texture: string, + offset: { number }?, -- Quake standard: x, y offset + rotation: number?, -- standard / Valve 220 (degrees) + scale: { number }?, -- standard / Valve 220 + u: { number }?, -- Valve 220: axis x, y, z, offset + v: { number }?, + matrix: { { number } }?, -- Quake III brush primitives: 2 x 3 + flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light) +} +type Brush = { + type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3" + faces: { Face }?, + texture: string?, -- patches + size: { number }?, -- patches: width, height (columns, points per column as written) + params: { number }?, -- patches: the header numbers after width, height + points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column) +} +type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object) +type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } } + +type St = { s: string, pos: number, n: number, comments: { string } } + +local function skip(st: St) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st: St): string + skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st: St, c: string): string? + if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos += 1 + return nil +end + +local function word(st: St): string? + skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b :: number) + 1 + return string.sub(st.s, a, b) +end + +local function number(st: St): number? + skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b :: number) + 1 + end + return v +end + +local function quoted(st: St): string? + if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st: St, n: number, out: { number }): string? + for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?) + local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st: St): { number }? + local out: { number } = {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return if #out > 0 then out else nil +end + +local function plane(st: St): ({ number }?, string?) + local pts: { number } = {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st: St, bp: boolean): (Face?, string?) + local pts, e = plane(st) + if not pts then + return nil, e + end + local f: Face = { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?) + local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = if kind == "patchDef3" then 7 else 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts: { number } = {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st: St, maxPoints: number): (Brush?, string?) + local c = peek(st) + if c == "(" then + local faces: { Face } = {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos += 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out: any, err: string? + if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces: { Face } = {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?) + local st: St = { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents: { Entity } = {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys: { [string]: string } = {} + local order: { string } = {} + local brushes: { Brush } = {} + while true do + local c = peek(st) + if c == "}" then + st.pos += 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos += 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count += 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes }) + end + local game, fmt + for _, c in st.comments do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse +end +__FILES["model/map/Write"] = function() + +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = __include("Types") +local Parse = __include("model/map/Parse") + +local Write = {} + +function Write.num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t: { number }, a: number, b: number): string + local out = table.create(b - a + 1) :: { string } + for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f: Parse.Face, bp: boolean): (string?, string?) + local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b: Parse.Brush, out: { string }): string? + local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = if b.type == "patchDef3" then 5 else 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map: Parse.Map): (string?, string?) + local out: { string } = {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in map.entities do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in Types.keys(ent.keys) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in ent.brushes or {} do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in b.faces or {} do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end __FILES["model/mca"] = function() -- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, @@ -174896,6 +177180,1517 @@ end return Write end +__FILES["model/vbsp"] = function() + +-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read, +-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and +-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by +-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a +-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360 +-- (big-endian) and Titanfall / Apex rBSP, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local KeyValues = __include("codecs/text/KeyValues") +local Mat4 = __include("codecs/model/Mat4") +local Zip = __include("containers/Zip") +local Archive = __include("containers/Archive") +local Faces = __include("model/vbsp/Faces") +local Props = __include("model/vbsp/Props") + +-- ------------------------------------------------------------------------------------------------ contract +local Vbsp = { + name = "vbsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + tools: boolean?, -- keep nodraw / skip / hint / sky faces, default false + pak: boolean?, -- meta.pak and textures from it, default true + maxBytes: number?, -- per decompressed lump, default 2^28 + maxVertices: number?, -- default 2^24 + maxProps: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ constants +local L = { + ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13, + MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43, + TEXDATA_STRING_TABLE = 44, FACES_HDR = 58, +} +local HEADER = 8 + 64 * 16 + 4 +local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vbsp.sniff(r: Bytes.Reader): number + if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return if v >= 19 and v <= 21 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Lump = Faces.Lump + +local function angles(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +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] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end + +local function vec3(s: any): { number }? + if type(s) ~= "string" then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream +local function unlzma(b: buffer, at: number, size: number, maxBytes: number): (buffer?, string?) + if size < 17 then + return nil, "truncated LZMA lump header" + end + local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8) + if actual > maxBytes then + return nil, "limit: LZMA lump of " .. actual .. " bytes" + end + if packed > size - 17 then + return nil, "LZMA lump runs past the end" + end + local props = buffer.create(5) + buffer.copy(props, 0, b, at + 12, 5) + local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes }) + if not out then + return nil, "LZMA lump: " .. tostring(if type(err) == "table" then err.message else err) + end + return out, nil +end + +local function isLzma(b: buffer, at: number, size: number): boolean + return size >= 17 and buffer.readstring(b, at, 4) == "LZMA" +end + +local function pakArchive(src: buffer, maxBytes: number): (any, Err.Err?) + local zc, err = Zip.open(src) + if not zc then + return nil, err + end + local a = Archive.new("zip") + for _, e in zc:list() do + local entry: any = { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = if e.method == 0 then "stored" elseif e.method == 8 then "deflate" elseif e.method == 14 then "lzma" else tostring(e.method), + mtime = e.mtime, + dir = e.isDir, + } + entry.load = function(): (buffer?, Err.Err?) + if e.method ~= 14 then + return zc:read(e) + end + -- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks) + local zb = zc.buf + for _, s in Zip._starts(zb, e) do + if s + 9 <= buffer.len(zb) then + local psize = buffer.readu16(zb, s + 2) + local start = s + 4 + psize + local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start) + if psize >= 5 and n > 0 and e.size <= maxBytes then + local props = buffer.create(5) + buffer.copy(props, 0, zb, s + 4, 5) + local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes }) + if out then + return out, nil + end + end + end + end + return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry") + end + Archive.put(a, entry) + end + a.meta.source = { format = "zip", lump = "pakfile" } + return a, nil +end + +local function light(scene: Types.Scene, e: any, class: string): (number?, { number }?) + local l = vec3(e._light) + local rgb: { number } = { 1, 1, 1 } + local intensity = 1 + if l then + rgb = { l[1] / 255, l[2] / 255, l[3] / 255 } + local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)") + intensity = (m and tonumber(m)) or 200 + end + local lt: Types.Light = nil :: any + if class == "light" then + lt = { name = nil :: string?, type = "point", color = rgb, intensity = intensity } + elseif class == "light_spot" then + local outer = tonumber(e._cone) or 45 + local inner = tonumber(e._inner_cone) or math.min(30, outer) + lt = { name = nil :: string?, type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) } + else + lt = { name = nil :: string?, type = "directional", color = rgb, intensity = intensity } + end + lt.name = if type(e.targetname) == "string" then e.targetname else class + table.insert(scene.lights, lt :: any) + local ang = vec3(e.angles) or { 0, 0, 0 } + if type(e.pitch) == "string" and tonumber(e.pitch) then + ang[1] = -(tonumber(e.pitch) :: number) -- the FGD's angle_negative_pitch + end + -- the light shines along the entity's forward (+x); a glTF light along -z + return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90)) +end + +function Vbsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base = r.buf, r.base + local size = r.limit - r.base + if size < HEADER then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VBSP" then + return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0) + end + local version = buffer.readi32(b, base + 4) + if version < 19 or version > 21 then + return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4) + end + local maxBytes = o.maxBytes or 2 ^ 28 + -- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036 + local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER + local dir: { { at: number, size: number, version: number, fourcc: number } } = {} + for i = 0, 63 do + local p = base + 8 + i * 16 + local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12) + local at, n, v = a, c, d + if l4d2 then + v, at, n = a, c, d + end + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base) + end + dir[i] = { at = at, size = n, version = v, fourcc = f } + end + local cache: { [number]: Lump } = {} + local compressed = false + local function lump(i: number): (Lump?, string?) + local c = cache[i] + if c then + return c, nil + end + local d = dir[i] + local out: Lump + if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then + local u, err = unlzma(b, base + d.at, d.size, maxBytes) + if not u then + return nil, "lump " .. i .. ": " .. tostring(err) + end + compressed = true + out = { buf = u, at = 0, size = buffer.len(u) } + else + out = { buf = b, at = base + d.at, size = d.size } + end + cache[i] = out + return out, nil + end + local need: { [string]: Lump } = {} + for name, idx in { planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES } :: { [string]: number } do + local lp, err = lump(idx) + if not lp then + return nil, Err.from(err) + end + need[name] = lp + end + if need.faces.size == 0 then + local hdr, err = lump(L.FACES_HDR) + if not hdr then + return nil, Err.from(err) + end + need.faces = hdr + end + local groups, ferr, skipped = Faces.build({ + planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges, + faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models, + dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true, + maxVertices = o.maxVertices or 2 ^ 24, + }) + if not groups then + return nil, Err.from(ferr, skipped and skipped - base) + end + + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + + local pak: any = nil + local pd = dir[L.PAKFILE] + if o.pak ~= false and pd.size > 0 then + local src = buffer.create(pd.size) + buffer.copy(src, 0, b, base + pd.at, pd.size) + pak = pakArchive(src, maxBytes) + scene.meta.pak = pak + end + + -- texdata -> material + texture (materials/.vtf, from the pak when it is there) + local TD, ST, SS = need.texdata, need.table, need.strings + local nTD = TD.size // 32 + local matOf: { [number]: number } = {} + local function material(td: number): number? + if td < 0 or td >= nTD then + return nil + end + local m = matOf[td] + if m then + return m + end + local to = TD.at + td * 32 + local si = buffer.readi32(TD.buf, to + 12) + local name = "texdata" .. td + if si >= 0 and (si + 1) * 4 <= ST.size then + local off = buffer.readi32(ST.buf, ST.at + si * 4) + if off >= 0 and off < SS.size then + name = string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") :: string + end + end + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + local tex: Types.Texture = { name = name, uri = path .. ".vtf" } + if pak then + local zc = pak :: any + local ok, data = pcall(zc.read, zc, path .. ".vtf") + if ok and type(data) == "buffer" then + tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil + end + end + table.insert(scene.textures, tex) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { + vbsp = { + vmt = path .. ".vmt", + width = buffer.readi32(TD.buf, to + 16), + height = buffer.readi32(TD.buf, to + 20), + reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) }, + }, + } + table.insert(scene.materials, mat) + matOf[td] = #scene.materials + return #scene.materials + end + + local root: Types.Node = { name = "vbsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelNode: { [number]: number } = {} + for _, g in groups do + local node = modelNode[g.model] + if not node then + local name = if g.model == 0 then "world" else "*" .. g.model + table.insert(scene.meshes, { name = name, primitives = {} }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } }) + node = #scene.nodes + modelNode[g.model] = node + table.insert(root.children, node) + end + local mesh = scene.meshes[scene.nodes[node].mesh :: number] + table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata))) + end + + -- entities + local E = need.entities + local text = string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") :: string + local blocks, eerr = KeyValues.entities(text) + if not blocks then + return nil, Err.new((eerr :: Err.Err).code, "entity lump: " .. (eerr :: Err.Err).message, dir[L.ENTITIES].at) + end + local ents: { any } = table.create(#blocks) + for i, blk in blocks do + local e = KeyValues.toObject(blk) + ents[i] = e + local class = if type(e.classname) == "string" then e.classname else "" + local mdl = if type(e.model) == "string" then string.match(e.model, "^%*(%d+)$") else nil + local mi = mdl and tonumber(mdl) + if mi and mi > 0 and modelNode[mi] then + local node = scene.nodes[modelNode[mi]] + node.name = if type(e.targetname) == "string" then e.targetname else class + local org = vec3(e.origin) + if org then + node.translation = org + end + local ang = vec3(e.angles) + if ang then + node.rotation = angles(ang[1], ang[2], ang[3]) + end + local x: any = node.extras + x.vbsp.entity = i + elseif class == "light" or class == "light_spot" or class == "light_environment" then + local li, rot = light(scene, e, class) + table.insert(scene.nodes, { name = scene.lights[li :: number].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.entities = ents + + -- game lumps + local spVersion: number? = nil + local G = dir[L.GAME_LUMP] + if G.size >= 4 then + local ga = base + G.at + local count = buffer.readi32(b, ga) + if count < 0 or 4 + count * 16 > G.size then + return nil, Err.new(Err.CORRUPT, "game lump directory", G.at) + end + for k = 0, count - 1 do + local eo = ga + 4 + k * 16 + local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6) + local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12) + if id == SPRP then + if off < 0 or len < 0 or off > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local pb, pat, plen = b, base + off, len + if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then + if off + 17 > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local u, err = unlzma(b, base + off, size - off, maxBytes) + if not u then + return nil, Err.from(err, off) + end + pb, pat, plen = u, 0, buffer.len(u) + compressed = true + elseif off + len > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local props, perr = Props.read(pb, pat, plen :: number, ver, o.maxProps or 2 ^ 20) + if not props then + return nil, Err.from(perr, off) + end + spVersion = ver + for pi, p in props do + local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model + table.insert(scene.nodes, { + name = nm, + children = {}, + translation = p.origin, + rotation = angles(p.angles[1], p.angles[2], p.angles[3]), + scale = if p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 then p.scale else nil, + extras = { + model = p.model, + vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin }, + }, + }) + table.insert(root.children, #scene.nodes) + end + end + end + end + + scene.meta.skippedFaces = skipped + scene.meta.source = { + format = "vbsp", + version = version, + variant = if l4d2 then "l4d2" else "v" .. version, + mapRevision = buffer.readi32(b, base + HEADER - 4), + compressed = compressed, + staticPropVersion = spVersion, + entities = text, + } + return scene, nil +end + +return Vbsp +end +__FILES["model/vbsp/Faces"] = function() + +-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013 +-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert); displacements through codecs/model/Displacement. +local Types = __include("Types") +local Displacement = __include("codecs/model/Displacement") + +local Faces = {} + +local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8 + +type Lump = { buf: buffer, at: number, size: number } +type Input = { + planes: Lump, + vertices: Lump, + edges: Lump, + surfedges: Lump, + faces: Lump, + texinfo: Lump, + texdata: Lump, + models: Lump, + dispinfo: Lump, + dispverts: Lump, + tools: boolean, -- keep nodraw / skip / hint / sky faces + maxVertices: number, +} +type Group = { model: number, texdata: number, pos: { number }, nrm: { number }, uv: { number }, blend: { number }?, idx: { number } } + +-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP +local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200 + +local function emit(g: Group, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number + local pos, nrm, uv = g.pos, g.nrm, g.uv + local k = #pos + pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + local q = #uv + uv[q + 1], uv[q + 2] = u, v + return k // 3 +end + +local function displacement(I: Input, g: Group, d: number, poly: { number }, nx: number, ny: number, nz: number, tex: { number }): string? + local di = I.dispinfo + if (d + 1) * 176 > di.size then + return "dispinfo index out of range" + end + local o = di.at + d * 176 + local b = di.buf + local vstart, power = readi32(b, o + 12), readi32(b, o + 20) + if #poly ~= 12 then + return nil -- not a quad: the base face is kept + end + if power < 1 or power > 4 then + return "displacement power " .. power + end + local n = 2 ^ power + 1 + local dv = I.dispverts + if vstart < 0 or (vstart + n * n) * 20 > dv.size then + return "displacement vertices out of range" + end + -- CDispVert: vector * dist, then alpha (0 .. 255) + local offsets: { number } = table.create(n * n * 3) :: any + for k = 0, n * n - 1 do + local vo = dv.at + (vstart + k) * 20 + local dist = readf32(dv.buf, vo + 12) + offsets[k * 3 + 1] = readf32(dv.buf, vo) * dist + offsets[k * 3 + 2] = readf32(dv.buf, vo + 4) * dist + offsets[k * 3 + 3] = readf32(dv.buf, vo + 8) * dist + end + local surf, err = Displacement.surface(poly, { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, power, offsets, { nx, ny, nz }) + if not surf then + return err + end + local base = #g.pos // 3 + local blend = g.blend or {} + g.blend = blend + local flat, pos, nrm = surf.flat, surf.pos, surf.nrm + for k = 0, n * n - 1 do + local x, y, z = flat[k * 3 + 1], flat[k * 3 + 2], flat[k * 3 + 3] + emit(g, pos[k * 3 + 1], pos[k * 3 + 2], pos[k * 3 + 3], nrm[k * 3 + 1], nrm[k * 3 + 2], nrm[k * 3 + 3], + (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9], (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10]) + blend[base + k + 1] = math.clamp(readf32(dv.buf, dv.at + (vstart + k) * 20 + 16) / 255, 0, 1) + end + local idx = g.idx + for _, v in surf.idx do + idx[#idx + 1] = base + v + end + return nil +end + +function Faces.build(I: Input): ({ Group }?, string?, number?) + local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, F.size // 56 + local nTI, nTD, nP = TI.size // 72, TD.size // 32, P.size // 20 + local faceModel: { [number]: number } = {} + local M = I.models + for m = 0, M.size // 48 - 1 do + local o = M.at + m * 48 + local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44) + if first >= 0 and count > 0 and first + count <= nF then + for f = first, first + count - 1 do + if faceModel[f] == nil then + faceModel[f] = m + end + end + end + end + local groups: { Group } = {} + local byKey: { [number]: Group } = {} + local skipped, verts = 0, 0 + local poly: { number } = {} + for f = 0, nF - 1 do + local fo = F.at + f * 56 + local fb = F.buf + local plane, side = readu16(fb, fo), readu8(fb, fo + 2) + local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8) + local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12) + local model = faceModel[f] or 0 + if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then + skipped += 1 + continue + end + local to = TI.at + ti * 72 + local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68) + if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then + continue + end + local w, h = 1, 1 + if td >= 0 and td < nTD then + w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1) + h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1) + else + td = -1 + end + table.clear(poly) + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local vi = readu16(E.buf, E.at + e * 4 + (if se >= 0 then 0 else 2)) + if vi >= nV then + ok = false + break + end + local vo = V.at + vi * 12 + poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8) + end + if not ok then + skipped += 1 + continue + end + local po = P.at + plane * 20 + local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + local key = model * 65536 + td + 1 + local grp: Group = byKey[key] + if not grp then + grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil :: { number }?, idx = {} } + byKey[key] = grp + table.insert(groups, grp) + end + local tex = { + readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12), + readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h, + } + local before = #grp.pos + local done = false + if disp >= 0 then + local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex) + if derr then + return nil, derr, fo + end + done = #grp.pos > before + end + if not done then + local n = numEdges + -- Newell's normal against the plane: the stored winding is clockwise from the front + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local a, b = k * 3, ((k + 1) % n) * 3 + ax += (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3]) + ay += (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1]) + az += (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2]) + end + local flip = ax * nx + ay * ny + az * nz < 0 + local first = -1 + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h) + if first < 0 then + first = id + end + end + local idx = grp.idx + for k = 1, n - 2 do + local b, c = first + k, first + k + 1 + if flip then + b, c = c, b + end + idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c + end + end + verts += (#grp.pos - before) // 3 + if verts > I.maxVertices then + return nil, "limit: over maxVertices", fo + end + end + return groups, nil, skipped +end + +function Faces.primitive(g: Group, material: number?): Types.Primitive + local prim = Displacement.primitive(g) + prim.material = material + return prim +end + +return Faces +end +__FILES["model/vbsp/Props"] = function() + +-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and +-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the +-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale +-- (v13: last 3 f32), u32 leaf indices (v12+). +local Props = {} + +local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32 + +type Prop = { + model: string, + origin: { number }, + angles: { number }, -- pitch, yaw, roll (degrees) + scale: { number }, + skin: number, + solid: number, + flags: number, + fadeMin: number, + fadeMax: number, + fadeScale: number?, + lightingOrigin: { number }, +} + +function Props.read(b: buffer, at: number, size: number, version: number, maxProps: number): ({ Prop }?, string?) + local e = at + size + local p = at + if p + 4 > e then + return {}, nil + end + local nd = readi32(b, p) + p += 4 + if nd < 0 or p + nd * 128 > e then + return nil, "static prop model names past the end" + end + local names: { string } = table.create(nd) :: any + for i = 0, nd - 1 do + names[i + 1] = string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") :: string + end + p += nd * 128 + if p + 4 > e then + return nil, "static prop leaves truncated" + end + local nl = readi32(b, p) + p += 4 + local leafSize = if version >= 12 then 4 else 2 + if nl < 0 or p + nl * leafSize + 4 > e then + return nil, "static prop leaves past the end" + end + p += nl * leafSize + local np = readi32(b, p) + p += 4 + if np < 0 or np > maxProps then + return nil, "limit: " .. np .. " static props" + end + local out: { Prop } = table.create(np) :: any + if np == 0 then + return out, nil + end + local rec = (e - p) // np + if rec < 56 then + return nil, "static prop records shorter than 56 bytes" + end + for i = 0, np - 1 do + local o = p + i * rec + local mi = readu16(b, o + 24) + local scale = { 1, 1, 1 } + if version == 13 and rec >= 88 then + scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) } + elseif (version == 11 or version == 12) and rec >= 80 then + local s = readf32(b, o + rec - 4) + scale = { s, s, s } + end + out[i + 1] = { + model = names[mi + 1] or "", + origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, + angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) }, + scale = scale, + solid = readu8(b, o + 30), + flags = readu8(b, o + 31), + skin = readi32(b, o + 32), + fadeMin = readf32(b, o + 36), + fadeMax = readf32(b, o + 40), + lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) }, + fadeScale = if version >= 5 and rec >= 60 then readf32(b, o + 56) else nil, + } + end + return out, nil +end + +return Props +end +__FILES["model/vmf"] = function() + +-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush +-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement, +-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in +-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from +-- opts.textureSizes, materials/.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances +-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Build = __include("model/vmf/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Vmf = { + name = "vmf", + category = "model", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + tools: boolean?, -- keep tools/* materials (nodraw, clip, trigger, skybox, ...), default false + textureSizes: { [string]: { number } }?, -- material name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> any)?, + maxPolygons: number?, -- default 2^20 +} +type EncodeOptions = {} +type SideSpec = { + points: { { number } }, -- three points, clockwise seen from outside (Hammer) + material: string?, + uaxis: { number }?, -- x, y, z, shift, scale; default from the face's dominant axis + vaxis: { number }?, + rotation: number?, + lightmapscale: number?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Vmf.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then + return 0.9 + end + if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function sizer(opts: DecodeOptions?): (string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h, known = 512, 512, false + local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)]) + if given and type(given[1]) == "number" and type(given[2]) == "number" then + w, h, known = given[1], given[2], true + elseif opts and opts.decodeImage then + local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf") + if data then + local ok, img = pcall(opts.decodeImage :: any, data) + if ok and type(img) == "table" and type(img.width) == "number" then + w, h, known = img.width, img.height, true + end + end + end + cache[name] = { w, h, if known then 1 else 0 } + return w, h, known + end +end + +function Vmf.parse(src: buffer | string): (KeyValues.Block?, Err.Err?) + return KeyValues.parse(src, { escapes = "quotes", defines = false }) +end + +function Vmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, err + end + local scene, msg = Build.scene(doc, { + tools = opts ~= nil and opts.tools == true, + size = sizer(opts), + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(msg) + end + local vi = KeyValues.get(doc, "versioninfo") + local info: any = if type(vi) == "table" then KeyValues.toObject(vi) else {} + scene.meta.vmf = doc + scene.meta.source = { + format = "vmf", + editorVersion = tonumber(info.editorversion), + editorBuild = tonumber(info.editorbuild), + mapVersion = tonumber(info.mapversion), + formatVersion = tonumber(info.formatversion), + prefab = info.prefab == "1", + } + return scene, nil +end + +-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world) +function Vmf.brushes(doc: KeyValues.Block): ({ { id: number?, entity: number, faces: { any }, materials: { string } } }?, Err.Err?) + local out = {} + local entity = 0 + local function walk(b: KeyValues.Block): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: KeyValues.Block, entity) + if not s then + return err + end + local faces, mats = {}, {} + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(mats, sd.material) + end + end + table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats }) + elseif k == "hidden" then + local err = walk(p.value :: KeyValues.Block) + if err then + return err + end + end + end + end + return nil + end + for _, p in doc do + local k = string.lower(p.key) + if type(p.value) == "table" and (k == "world" or k == "entity") then + entity += 1 + local err = walk(p.value :: KeyValues.Block) + if err then + return nil, Err.new(Err.CORRUPT, err) + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Hammer writes dispinfo rows at their block's own indent +local FLAT: { [string]: boolean } = {} +for _, k in { "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" } do + FLAT[k] = true +end + +function Vmf.encode(value: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local doc = value + if type(value) == "table" and value.kind == "scene" then + doc = value.meta and value.meta.vmf + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written") + end + end + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document") + end + local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function fmt(x: number): string + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + return (string.gsub(string.format("%.6f", x), "%.?0+$", "")) +end + +local function kv(k: string, v: string): KeyValues.Pair + return { key = k, value = v } +end + +-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls) +local function defaultAxes(points: { { number } }): ({ number }, { number }) + local a, b, c = points[1], points[2], points[3] + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx) + if nz >= nx and nz >= ny then + return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 } + elseif nx >= ny then + return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } + end + return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } +end + +local function id(given: number?, default: number): string + return fmt(given or default) +end + +function Vmf.side(s: SideSpec, sideId: number?): KeyValues.Pair + local p = s.points + local du, dv = defaultAxes(p) + local u, v = s.uaxis or du, s.vaxis or dv + local function axis(x: { number }): string + return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25) + end + local function pt(x: { number }): string + return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")" + end + return { key = "side", value = { + kv("id", id(sideId, 1)), + kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])), + kv("material", s.material or "TOOLS/TOOLSNODRAW"), + kv("uaxis", axis(u)), + kv("vaxis", axis(v)), + kv("rotation", fmt(s.rotation or 0)), + kv("lightmapscale", fmt(s.lightmapscale or 16)), + kv("smoothing_groups", "0"), + } } +end + +function Vmf.solid(sides: { SideSpec }, solidId: number?): KeyValues.Pair + local blk: KeyValues.Block = { kv("id", id(solidId, 1)) } + for i, s in sides do + table.insert(blk, Vmf.side(s, i)) + end + table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } }) + return { key = "solid", value = blk } +end + +-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north, +-- south) +function Vmf.box(lo: { number }, hi: { number }, material: string | { string }, solidId: number?): KeyValues.Pair + local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] + local function m(i: number): string + return if type(material) == "table" then material[i] or material[1] else material + end + return Vmf.solid({ + { points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) }, + { points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) }, + { points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) }, + { points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) }, + { points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) }, + { points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) }, + }, solidId) +end + +-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons +function Vmf.document(worldKeys: { [string]: string }?): KeyValues.Block + local world: KeyValues.Block = { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") } + if worldKeys then + local keys = {} + for k in worldKeys do + table.insert(keys, k) + end + table.sort(keys) + for _, k in keys do + table.insert(world, kv(k, worldKeys[k])) + end + end + return { + { key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } }, + { key = "visgroups", value = {} }, + { key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } }, + { key = "world", value = world }, + { key = "cameras", value = { kv("activecamera", "-1") } }, + { key = "cordons", value = { kv("active", "0") } }, + } +end + +-- an entity block (keys in the given order, then its solids) appended to doc before cameras +function Vmf.entity(doc: KeyValues.Block, keys: { { string } }, solids: { KeyValues.Pair }?): KeyValues.Pair + local count = 1 + for _, p in doc do + if string.lower(p.key) == "entity" then + count += 1 + end + end + local blk: KeyValues.Block = { kv("id", id(nil, count + 1)) } + for _, k in keys do + table.insert(blk, kv(k[1], k[2])) + end + for _, s in solids or {} do + table.insert(blk, s) + end + local pair = { key = "entity", value = blk } + local at = #doc + 1 + for i, p in doc do + if string.lower(p.key) == "cameras" then + at = i + break + end + end + table.insert(doc, at, pair) + return pair +end + +-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...))) +function Vmf.world(doc: KeyValues.Block): KeyValues.Block? + local w = KeyValues.get(doc, "world") + return if type(w) == "table" then w else nil +end + +return Vmf +end +__FILES["model/vmf/Build"] = function() + +-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes +-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one +-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras. +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Brush = __include("codecs/model/Brush") +local Displacement = __include("codecs/model/Displacement") +local Mat4 = __include("codecs/model/Mat4") + +local Build = {} + +type Block = KeyValues.Block + +type Side = { + id: number?, + points: { number }, -- 9: the plane's three points + material: string, + uaxis: { number }, -- x, y, z, shift, scale + vaxis: { number }, + disp: Block?, +} +type Solid = { id: number?, sides: { Side }, editor: any, entity: number } +type Options = { + tools: boolean, + size: (name: string) -> (number, number, boolean), + maxPolygons: number?, +} + +local function nums(s: any): { number } + local out: { number } = {} + if type(s) ~= "string" then + return out + end + for w in string.gmatch(s, "[^%s%(%)%[%]]+") do + local n = tonumber(w) + if n then + table.insert(out, n) + end + end + return out +end +Build.nums = nums + +local function get(b: Block, key: string): any + return KeyValues.get(b, key) +end + +local function editor(b: Block): any + local e = KeyValues.find(b, "editor") + return if e and type(e.value) == "table" then KeyValues.toObject(e.value) else nil +end + +function Build.solid(b: Block, entity: number): (Solid?, string?) + local sides: { Side } = {} + for _, p in KeyValues.all(b, "side") do + if type(p.value) == "table" then + local sb = p.value :: Block + local pts = nums(get(sb, "plane")) + if #pts ~= 9 then + return nil, "side without a 3-point plane" + end + local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis")) + local d = KeyValues.find(sb, "dispinfo") + table.insert(sides, { + id = tonumber(get(sb, "id")), + points = pts, + material = tostring(get(sb, "material") or ""), + uaxis = if #u >= 5 then u else { 1, 0, 0, 0, 1 }, + vaxis = if #v >= 5 then v else { 0, -1, 0, 0, 1 }, + disp = if d and type(d.value) == "table" then d.value :: Block else nil, + }) + end + end + return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil +end + +function Build.face(s: Side): Brush.Face? + local p = s.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) } +end + +local function rows(d: Block, name: string, per: number, n: number): { number }? + local blk = KeyValues.get(d, name) + if type(blk) ~= "table" then + return nil + end + local out: { number } = table.create(n * n * per, 0) :: any + for i = 0, n - 1 do + local r = nums(KeyValues.get(blk, "row" .. i)) + for k = 1, math.min(#r, n * per) do + out[i * n * per + k] = r[k] + end + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number }, blend: { number } } + +-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp) +local function displace(s: Side, face: Brush.Face, poly: Brush.Polygon, acc: Acc, w: number, h: number): string? + local d = s.disp :: Block + local power = tonumber(KeyValues.get(d, "power")) or 0 + if power < 1 or power > 4 or power % 1 ~= 0 then + return "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + local start = nums(KeyValues.get(d, "startposition")) + if #start < 3 then + return "displacement without a start position" + end + local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n) + local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n) + local elev = tonumber(KeyValues.get(d, "elevation")) or 0 + local pn = face.plane + local offsets: { number } = table.create(n * n * 3, 0) :: any + for k = 0, n * n - 1 do + for c = 1, 3 do + local v = elev * pn[c] + if normals and dists then + v += normals[k * 3 + c] * dists[k + 1] + end + if offs then + v += offs[k * 3 + c] + end + offsets[k * 3 + c] = v + end + end + -- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise + local pts = poly.points + local cw: { number } = {} + for k = #pts // 3 - 1, 0, -1 do + table.insert(cw, pts[k * 3 + 1]) + table.insert(cw, pts[k * 3 + 2]) + table.insert(cw, pts[k * 3 + 3]) + end + local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] }) + if not surf then + return err + end + local base = #acc.pos // 3 + for k = 0, n * n - 1 do + local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3] + for c = 1, 3 do + table.insert(acc.pos, surf.pos[k * 3 + c]) + table.insert(acc.nrm, surf.nrm[k * 3 + c]) + end + local u, v = Brush.uv(face, x, y, z, w, h) + table.insert(acc.uv, u) + table.insert(acc.uv, v) + table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1)) + end + for _, i in surf.idx do + table.insert(acc.idx, base + i) + end + return nil +end + +local function isTool(name: string): boolean + return string.sub(string.lower(name), 1, 6) == "tools/" +end + +-- the solids of one entity -> its primitives (material indices by name through matOf) +function Build.mesh(solids: { Solid }, o: Options, matOf: (string) -> number, name: string): (Types.Mesh?, string?) + local brushes: { { Brush.Face } } = {} + local sideOf: { { Side } } = {} + local hasDisp: { boolean } = {} + for _, s in solids do + local faces: { Brush.Face } = {} + local sides: { Side } = {} + local disp = false + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(sides, sd) + disp = disp or sd.disp ~= nil + end + end + if #faces >= 4 then + table.insert(brushes, faces) + table.insert(sideOf, sides) + table.insert(hasDisp, disp) + end + end + local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons }) + if not polys then + return nil, perr + end + local keep: { Brush.Polygon } = {} + local disps: { [string]: Acc } = {} + local dispOrder: { string } = {} + for _, p in polys do + local sd = sideOf[p.brush][p.face] + if o.tools or not isTool(sd.material) then + if sd.disp then + local acc = disps[sd.material] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} } + disps[sd.material] = acc + table.insert(dispOrder, sd.material) + end + local w, h = o.size(sd.material) + local err = displace(sd, brushes[p.brush][p.face], p, acc :: Acc, w, h) + if err then + return nil, err + end + elseif not hasDisp[p.brush] then + table.insert(keep, p) + end + end + end + local mesh: Types.Mesh = { name = name, primitives = {} } + local function size(n: string): (number, number) + local w, h = o.size(n) + return w, h + end + for _, b in Brush.primitives(keep, brushes, size) do + b.primitive.material = matOf(b.texture) + table.insert(mesh.primitives, b.primitive) + end + for _, m in dispOrder do + local prim = Displacement.primitive(disps[m] :: any) + prim.material = matOf(m) + table.insert(mesh.primitives, prim) + end + return mesh, nil +end + +local function quat(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +-- a camera at position looking at look, z up: glTF cameras look along -z with +y up +local function lookAt(pos: { number }, look: { number }): { number } + local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3] + local l = math.sqrt(fx * fx + fy * fy + fz * fz) + if l < 1e-9 then + return { 0, 0, 0, 1 } + end + fx, fy, fz = fx / l, fy / l, fz / l + local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1) + local rl = math.sqrt(rx * rx + ry * ry) + if rl < 1e-9 then + rx, ry, rl = 1, 0, 1 + end + rx, ry = rx / rl, ry / rl + local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f + return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +local function visgroups(b: Block): { any } + local out = {} + for _, p in KeyValues.all(b, "visgroup") do + if type(p.value) == "table" then + local v = p.value :: Block + table.insert(out, { + name = KeyValues.get(v, "name"), + id = tonumber(KeyValues.get(v, "visgroupid")), + color = KeyValues.get(v, "color"), + children = visgroups(v), + }) + end + end + return out +end + +-- solids of a block, including those inside its hidden { } blocks +local function solidsOf(b: Block, entity: number, out: { Solid }): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: Block, entity) + if not s then + return err + end + table.insert(out, s) + elseif k == "hidden" then + local err = solidsOf(p.value :: Block, entity, out) + if err then + return err + end + end + end + end + return nil +end + +function Build.scene(doc: Block, o: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + local mats: { [string]: number } = {} + local function matOf(name: string): number + local m = mats[name] + if m then + return m + end + local w, h, known = o.size(name) + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + table.insert(scene.textures, { name = name, uri = path .. ".vtf" }) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + mats[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "vmf", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local ents: { any } = {} + local solidsMeta: { any } = {} + local groups: { any } = {} + -- world and entities, hidden ones included + local blocks: { { key: string, block: Block } } = {} + for _, p in doc do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "world" or k == "entity" then + table.insert(blocks, { key = k, block = p.value :: Block }) + elseif k == "hidden" then + for _, q in KeyValues.all(p.value :: Block, "entity") do + if type(q.value) == "table" then + table.insert(blocks, { key = "entity", block = q.value :: Block }) + end + end + end + end + end + for _, item in blocks do + local b = item.block + local keys: Block = {} + local conns: any = nil + for _, p in b do + if type(p.value) == "string" then + table.insert(keys, p) + elseif string.lower(p.key) == "connections" then + conns = KeyValues.toObject(p.value :: Block) + elseif item.key == "world" and string.lower(p.key) == "group" then + local g = p.value :: Block + table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) }) + end + end + local e = KeyValues.toObject(keys) + if conns then + e.connections = conns + end + table.insert(ents, e) + local ei = #ents + local solids: { Solid } = {} + local serr = solidsOf(b, ei, solids) + if serr then + return nil, serr + end + local class = if type(e.classname) == "string" then e.classname else item.key + local name = if item.key == "world" then "world" elseif type(e.targetname) == "string" then e.targetname else class + local node: Types.Node = { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } } + if #solids > 0 then + local mesh, merr = Build.mesh(solids, o, matOf, name) + if not mesh then + return nil, merr + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + for _, s in solids do + table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor }) + end + else + local org = nums(e.origin) + if #org >= 3 then + node.translation = { org[1], org[2], org[3] } + end + local ang = nums(e.angles) + if #ang >= 3 then + node.rotation = quat(ang[1], ang[2], ang[3]) + end + if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then + (node.extras :: any).model = e.model + end + end + if node.mesh or item.key ~= "world" then + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + end + -- cameras + local cams = KeyValues.get(doc, "cameras") + local camMeta: any = nil + if type(cams) == "table" then + camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} } + for _, p in KeyValues.all(cams, "camera") do + if type(p.value) == "table" then + local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look")) + if #pos >= 3 and #look >= 3 then + local cam: Types.Camera = { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 } + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) }) + table.insert(root.children, #scene.nodes) + table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } }) + end + end + end + end + local vg = KeyValues.get(doc, "visgroups") + scene.meta.entities = ents + scene.meta.solids = solidsMeta + scene.meta.groups = groups + scene.meta.visgroups = if type(vg) == "table" then visgroups(vg) else {} + scene.meta.cameras = camMeta + return scene, nil +end + +return Build +end __FILES["model/vox"] = function() -- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index dba217d..ed0ce49 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,553 +1,566 @@ [ [29, "src/Rosetta/init.luau"], [873, "src/Rosetta/Registry.luau"], -[3030, "src/Rosetta/Types.luau"], -[4113, "src/Rosetta/archive/7z/init.luau"], -[4498, "src/Rosetta/archive/7z/Header.luau"], -[5025, "src/Rosetta/archive/adf/init.luau"], -[5307, "src/Rosetta/archive/applesingle/init.luau"], -[5493, "src/Rosetta/archive/ar/init.luau"], -[5896, "src/Rosetta/archive/arj/init.luau"], -[6106, "src/Rosetta/archive/binhex/init.luau"], -[6355, "src/Rosetta/archive/br/init.luau"], -[6430, "src/Rosetta/archive/bz2/init.luau"], -[6494, "src/Rosetta/archive/cab/init.luau"], -[6907, "src/Rosetta/archive/cab/Sum.luau"], -[6948, "src/Rosetta/archive/cpio/init.luau"], -[7116, "src/Rosetta/archive/d64/init.luau"], -[7530, "src/Rosetta/archive/fat/init.luau"], -[7652, "src/Rosetta/archive/grp/init.luau"], -[7766, "src/Rosetta/archive/gzip/init.luau"], -[7951, "src/Rosetta/archive/iso/init.luau"], -[8023, "src/Rosetta/archive/lha/init.luau"], -[8448, "src/Rosetta/archive/lz4/init.luau"], -[8792, "src/Rosetta/archive/macbinary/init.luau"], -[8990, "src/Rosetta/archive/mpq/init.luau"], -[9396, "src/Rosetta/archive/mpq/Crypt.luau"], -[9461, "src/Rosetta/archive/pak/init.luau"], -[9595, "src/Rosetta/archive/rpm/init.luau"], -[9919, "src/Rosetta/archive/tar/init.luau"], -[10037, "src/Rosetta/archive/uu/init.luau"], -[10307, "src/Rosetta/archive/vpk/init.luau"], -[10618, "src/Rosetta/archive/wad/init.luau"], -[11068, "src/Rosetta/archive/wad/Map.luau"], -[11498, "src/Rosetta/archive/wad/Picture.luau"], -[11600, "src/Rosetta/archive/xz/init.luau"], -[11700, "src/Rosetta/archive/yenc/init.luau"], -[11972, "src/Rosetta/archive/z/init.luau"], -[12068, "src/Rosetta/archive/zip/init.luau"], -[12287, "src/Rosetta/archive/zoo/init.luau"], -[12483, "src/Rosetta/archive/zst/init.luau"], -[12547, "src/Rosetta/audio/aac/init.luau"], -[12753, "src/Rosetta/audio/ac3/init.luau"], -[12899, "src/Rosetta/audio/adpcm/init.luau"], -[13044, "src/Rosetta/audio/adx/init.luau"], -[13275, "src/Rosetta/audio/aiff/init.luau"], -[13666, "src/Rosetta/audio/ape/init.luau"], -[13794, "src/Rosetta/audio/au/init.luau"], -[13955, "src/Rosetta/audio/brstm/init.luau"], -[14246, "src/Rosetta/audio/caf/init.luau"], -[14908, "src/Rosetta/audio/flac/init.luau"], -[15056, "src/Rosetta/audio/flac/Meta.luau"], -[15278, "src/Rosetta/audio/flac/Stream.luau"], -[15648, "src/Rosetta/audio/m4a/init.luau"], -[15982, "src/Rosetta/audio/mp3/init.luau"], -[16242, "src/Rosetta/audio/mp3/Index.luau"], -[16433, "src/Rosetta/audio/mp3/Stream.luau"], -[16660, "src/Rosetta/audio/mp3/Tags.luau"], -[16972, "src/Rosetta/audio/mpc/init.luau"], -[17066, "src/Rosetta/audio/opus/init.luau"], -[17444, "src/Rosetta/audio/opus/Encode.luau"], -[17555, "src/Rosetta/audio/qoa/init.luau"], -[17735, "src/Rosetta/audio/tta/init.luau"], -[17853, "src/Rosetta/audio/vag/init.luau"], -[18076, "src/Rosetta/audio/voc/init.luau"], -[18351, "src/Rosetta/audio/vorbis/init.luau"], -[18805, "src/Rosetta/audio/vorbis/Encode.luau"], -[19618, "src/Rosetta/audio/wav/init.luau"], -[20239, "src/Rosetta/audio/wav/Codecs.luau"], -[20405, "src/Rosetta/audio/wavpack/init.luau"], -[20612, "src/Rosetta/cad/step/init.luau"], -[20994, "src/Rosetta/cad/step/Brep.luau"], -[21229, "src/Rosetta/cad/step/Parse.luau"], -[21786, "src/Rosetta/cad/step/Write.luau"], -[22034, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22353, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23236, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[23571, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[23730, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[24615, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[24716, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[25470, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[25772, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26006, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26425, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[26837, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27052, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[27813, "src/Rosetta/codecs/audio/ApeTag.luau"], -[27910, "src/Rosetta/codecs/audio/Flac/init.luau"], -[27921, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[28870, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[29467, "src/Rosetta/codecs/audio/Hively/init.luau"], -[29663, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[29912, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[30870, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31089, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31273, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[31482, "src/Rosetta/codecs/audio/MidiRender.luau"], -[31828, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[31842, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[31901, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[33504, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[33796, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34181, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[34822, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[34963, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35189, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[35534, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36428, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[36806, "src/Rosetta/codecs/audio/Opus/init.luau"], -[36820, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[38667, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[39732, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[39792, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40252, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[40589, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[40822, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[42858, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43232, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[43495, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[43792, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44074, "src/Rosetta/codecs/audio/Resample/init.luau"], -[44433, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[44487, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[44630, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45143, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[45924, "src/Rosetta/codecs/audio/Stream.luau"], -[46085, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[46567, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[46845, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47014, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47142, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49130, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49246, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49363, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[49615, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[49628, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50012, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[50578, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[50999, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51038, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51090, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51312, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[52767, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[52830, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[52917, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[53886, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[54754, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[54802, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55318, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[55644, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56064, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[56499, "src/Rosetta/codecs/compress/Explode.luau"], -[56695, "src/Rosetta/codecs/compress/Lz4.luau"], -[56964, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[57568, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58108, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58146, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[58619, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[58795, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59063, "src/Rosetta/codecs/compress/Lzx.luau"], -[59497, "src/Rosetta/codecs/compress/PackBits.luau"], -[59587, "src/Rosetta/codecs/compress/Quantum.luau"], -[59824, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60128, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60197, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60254, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61212, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61364, "src/Rosetta/codecs/entropy/Huffman.luau"], -[61646, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[61657, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[61871, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62115, "src/Rosetta/codecs/font/Bitmap.luau"], -[62316, "src/Rosetta/codecs/font/Cff/init.luau"], -[62957, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63107, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63421, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[63813, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64315, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64422, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[64911, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65340, "src/Rosetta/codecs/image/Blend.luau"], -[65719, "src/Rosetta/codecs/image/Dct/init.luau"], -[66100, "src/Rosetta/codecs/image/Etc.luau"], -[66398, "src/Rosetta/codecs/image/Half.luau"], -[66467, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[66821, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67229, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[67466, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68226, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69107, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[69553, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[69631, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[69698, "src/Rosetta/codecs/image/Pixels.luau"], -[69962, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70421, "src/Rosetta/codecs/image/Raster.luau"], -[71118, "src/Rosetta/codecs/image/Texel.luau"], -[71491, "src/Rosetta/codecs/image/Texture.luau"], -[71636, "src/Rosetta/codecs/image/Vp8/init.luau"], -[71766, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[73722, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[73981, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74230, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74349, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[74453, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75306, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76258, "src/Rosetta/codecs/image/Yuv.luau"], -[76526, "src/Rosetta/codecs/model/Draco/init.luau"], -[76858, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77327, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[78516, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[78665, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79024, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[79986, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[80460, "src/Rosetta/codecs/model/Mat4.luau"], -[80719, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81247, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[81799, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[81878, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[81985, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82191, "src/Rosetta/codecs/model/Polygon.luau"], -[82425, "src/Rosetta/codecs/model/Rbx/init.luau"], -[82662, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83416, "src/Rosetta/codecs/model/Rig.luau"], -[83659, "src/Rosetta/codecs/model/Sampler.luau"], -[83819, "src/Rosetta/codecs/model/SourceAnim.luau"], -[84040, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84188, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[84762, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[84925, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[85674, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86196, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[86923, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87155, "src/Rosetta/codecs/text/Json/init.luau"], -[87424, "src/Rosetta/codecs/text/Json/Decode.luau"], -[87838, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88140, "src/Rosetta/codecs/text/KeyValues/init.luau"], -[88697, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], -[89002, "src/Rosetta/codecs/text/Nbt/init.luau"], -[89355, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[90047, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90687, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90925, "src/Rosetta/codecs/text/Text/init.luau"], -[91016, "src/Rosetta/codecs/text/Url/init.luau"], -[91221, "src/Rosetta/codecs/text/Xml/init.luau"], -[91624, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[92364, "src/Rosetta/codecs/video/Dsp.luau"], -[93087, "src/Rosetta/codecs/video/H263/init.luau"], -[93243, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[94101, "src/Rosetta/codecs/video/H263/Tables.luau"], -[94304, "src/Rosetta/codecs/video/H264/init.luau"], -[94677, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94952, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[96083, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[96851, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[97109, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[98118, "src/Rosetta/codecs/video/H264/Inter.luau"], -[98372, "src/Rosetta/codecs/video/H264/Intra.luau"], -[98779, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99685, "src/Rosetta/codecs/video/H264/Params.luau"], -[100132, "src/Rosetta/codecs/video/H264/Slice.luau"], -[100383, "src/Rosetta/codecs/video/H264/Tables.luau"], -[100424, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100589, "src/Rosetta/codecs/video/Legacy/init.luau"], -[100787, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[101084, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[101451, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101569, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101677, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101950, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[102345, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102522, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102534, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102901, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[104408, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104547, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104685, "src/Rosetta/codecs/video/Theora/init.luau"], -[104948, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[106212, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106575, "src/Rosetta/codecs/video/Video/init.luau"], -[107132, "src/Rosetta/codecs/video/Video/Source.luau"], -[107417, "src/Rosetta/containers/Archive.luau"], -[107684, "src/Rosetta/containers/AudioWrap.luau"], -[108187, "src/Rosetta/containers/Avi/init.luau"], -[108739, "src/Rosetta/containers/Chunks.luau"], -[108874, "src/Rosetta/containers/Cpio.luau"], -[109302, "src/Rosetta/containers/Demux.luau"], -[109577, "src/Rosetta/containers/Ebml/init.luau"], -[109890, "src/Rosetta/containers/Fat.luau"], -[110578, "src/Rosetta/containers/Iso9660.luau"], -[111083, "src/Rosetta/containers/IsoBmff/init.luau"], -[111253, "src/Rosetta/containers/IsoBmff/Box.luau"], -[111441, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[112286, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[112807, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[113323, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[113440, "src/Rosetta/containers/MacFile.luau"], -[113589, "src/Rosetta/containers/MpegEs.luau"], -[113755, "src/Rosetta/containers/MpegPs/init.luau"], -[113975, "src/Rosetta/containers/MpegTs/init.luau"], -[114767, "src/Rosetta/containers/Ogg/init.luau"], -[115192, "src/Rosetta/containers/Ogg/Mux.luau"], -[115387, "src/Rosetta/containers/Ogg/Page.luau"], -[115556, "src/Rosetta/containers/Riff/init.luau"], -[115873, "src/Rosetta/containers/Tar.luau"], -[116287, "src/Rosetta/containers/Zip/init.luau"], -[116919, "src/Rosetta/core/Adler32.luau"], -[116965, "src/Rosetta/core/Base64.luau"], -[117124, "src/Rosetta/core/Bits.luau"], -[117417, "src/Rosetta/core/Bytes.luau"], -[117944, "src/Rosetta/core/Crc16.luau"], -[117996, "src/Rosetta/core/Crc32.luau"], -[118108, "src/Rosetta/core/Err.luau"], -[118190, "src/Rosetta/core/Input.luau"], -[118266, "src/Rosetta/core/Md5.luau"], -[118425, "src/Rosetta/core/Sniff.luau"], -[118454, "src/Rosetta/data/cbor/init.luau"], -[118553, "src/Rosetta/data/cbor/Codec.luau"], -[119122, "src/Rosetta/data/csv/init.luau"], -[119434, "src/Rosetta/data/ini/init.luau"], -[119680, "src/Rosetta/data/json/init.luau"], -[119772, "src/Rosetta/data/msgpack/init.luau"], -[119861, "src/Rosetta/data/msgpack/Codec.luau"], -[120303, "src/Rosetta/data/nbt/init.luau"], -[120362, "src/Rosetta/data/plist/init.luau"], -[120668, "src/Rosetta/data/plist/Binary.luau"], -[120935, "src/Rosetta/data/snbt/init.luau"], -[120998, "src/Rosetta/data/toml/init.luau"], -[121065, "src/Rosetta/data/toml/Decode.luau"], -[121693, "src/Rosetta/data/toml/Encode.luau"], -[121902, "src/Rosetta/data/vdf/init.luau"], -[122003, "src/Rosetta/data/xml/init.luau"], -[122059, "src/Rosetta/data/yaml/init.luau"], -[122132, "src/Rosetta/data/yaml/Emit.luau"], -[122422, "src/Rosetta/data/yaml/Parse.luau"], -[123715, "src/Rosetta/font/bdf/init.luau"], -[124004, "src/Rosetta/font/bmfont/init.luau"], -[124431, "src/Rosetta/font/bmfont/Parse.luau"], -[124884, "src/Rosetta/font/eot/init.luau"], -[125116, "src/Rosetta/font/fon/init.luau"], -[125399, "src/Rosetta/font/hershey/init.luau"], -[125594, "src/Rosetta/font/pcf/init.luau"], -[125874, "src/Rosetta/font/psf/init.luau"], -[126194, "src/Rosetta/font/ttf/init.luau"], -[126245, "src/Rosetta/font/type1/init.luau"], -[126604, "src/Rosetta/font/type1/Charstring.luau"], -[126882, "src/Rosetta/font/woff/init.luau"], -[127014, "src/Rosetta/font/woff2/init.luau"], -[127071, "src/Rosetta/font/woff2/Rebuild.luau"], -[127611, "src/Rosetta/host/init.luau"], -[127656, "src/Rosetta/host/Love.luau"], -[127799, "src/Rosetta/host/LuaJIT.luau"], -[127849, "src/Rosetta/host/Luau.luau"], -[127872, "src/Rosetta/host/Roblox.luau"], -[128231, "src/Rosetta/image/ani/init.luau"], -[128411, "src/Rosetta/image/art/init.luau"], -[128899, "src/Rosetta/image/blp/init.luau"], -[129157, "src/Rosetta/image/bmp/init.luau"], -[129572, "src/Rosetta/image/dds/init.luau"], -[130055, "src/Rosetta/image/exr/init.luau"], -[130815, "src/Rosetta/image/exr/Codec.luau"], -[130926, "src/Rosetta/image/exr/Piz.luau"], -[131283, "src/Rosetta/image/gif/init.luau"], -[131799, "src/Rosetta/image/gif/Decode.luau"], -[131862, "src/Rosetta/image/hdr/init.luau"], -[132091, "src/Rosetta/image/hdr/Codec.luau"], -[132302, "src/Rosetta/image/icns/init.luau"], -[132633, "src/Rosetta/image/ico/init.luau"], -[132910, "src/Rosetta/image/ico/Dib.luau"], -[133005, "src/Rosetta/image/ilbm/init.luau"], -[133324, "src/Rosetta/image/jpeg/init.luau"], -[133460, "src/Rosetta/image/ktx/init.luau"], -[134120, "src/Rosetta/image/pcx/init.luau"], -[134384, "src/Rosetta/image/png/init.luau"], -[134964, "src/Rosetta/image/png/Apng.luau"], -[135044, "src/Rosetta/image/png/Decode.luau"], -[135284, "src/Rosetta/image/png/Encode.luau"], -[135439, "src/Rosetta/image/pnm/init.luau"], -[135817, "src/Rosetta/image/pnm/Codec.luau"], -[136094, "src/Rosetta/image/qoi/init.luau"], -[136216, "src/Rosetta/image/qoi/Codec.luau"], -[136366, "src/Rosetta/image/sgi/init.luau"], -[136651, "src/Rosetta/image/sunras/init.luau"], -[136897, "src/Rosetta/image/tga/init.luau"], -[137167, "src/Rosetta/image/tga/Codec.luau"], -[137319, "src/Rosetta/image/tiff/init.luau"], -[138146, "src/Rosetta/image/tiff/Pixels.luau"], -[138536, "src/Rosetta/image/tim/init.luau"], -[138778, "src/Rosetta/image/vtf/init.luau"], -[139013, "src/Rosetta/image/webp/init.luau"], -[139623, "src/Rosetta/image/webp/Alpha.luau"], -[139699, "src/Rosetta/image/webp/Anim.luau"], -[139854, "src/Rosetta/image/xbm/init.luau"], -[140015, "src/Rosetta/image/xpm/init.luau"], -[140283, "src/Rosetta/image/xpm/Names.luau"], -[140339, "src/Rosetta/layered/aseprite/init.luau"], -[141077, "src/Rosetta/layered/ora/init.luau"], -[141364, "src/Rosetta/layered/psd/init.luau"], -[142099, "src/Rosetta/layered/psd/Channels.luau"], -[142451, "src/Rosetta/model/3ds/init.luau"], -[142534, "src/Rosetta/model/3ds/Build.luau"], -[143181, "src/Rosetta/model/3ds/Read.luau"], -[143677, "src/Rosetta/model/3ds/Write.luau"], -[144482, "src/Rosetta/model/3mf/init.luau"], -[144564, "src/Rosetta/model/3mf/Read.luau"], -[145152, "src/Rosetta/model/3mf/Write.luau"], -[145557, "src/Rosetta/model/b3d/init.luau"], -[145612, "src/Rosetta/model/b3d/Read.luau"], -[146183, "src/Rosetta/model/bsp/init.luau"], -[146328, "src/Rosetta/model/bsp/Brush.luau"], -[146606, "src/Rosetta/model/bsp/Quake3.luau"], -[146861, "src/Rosetta/model/buildmap/init.luau"], -[147133, "src/Rosetta/model/buildmap/Geometry.luau"], -[147536, "src/Rosetta/model/dae/init.luau"], -[147725, "src/Rosetta/model/dae/Math.luau"], -[147772, "src/Rosetta/model/dae/Read.luau"], -[149622, "src/Rosetta/model/dae/Write.luau"], -[149991, "src/Rosetta/model/fbx/init.luau"], -[150139, "src/Rosetta/model/fbx/Ascii.luau"], -[150409, "src/Rosetta/model/fbx/Binary.luau"], -[150864, "src/Rosetta/model/fbx/Read.luau"], -[152226, "src/Rosetta/model/fbx/Write.luau"], -[153211, "src/Rosetta/model/fbx/Xform.luau"], -[153252, "src/Rosetta/model/gltf/init.luau"], -[153489, "src/Rosetta/model/gltf/Pack.luau"], -[153558, "src/Rosetta/model/gltf/Read.luau"], -[154289, "src/Rosetta/model/gltf/Write.luau"], -[154969, "src/Rosetta/model/iqm/init.luau"], -[155045, "src/Rosetta/model/iqm/Read.luau"], -[155400, "src/Rosetta/model/iqm/Write.luau"], -[156087, "src/Rosetta/model/ldraw/init.luau"], -[156165, "src/Rosetta/model/ldraw/Colors.luau"], -[156483, "src/Rosetta/model/ldraw/Read.luau"], -[157060, "src/Rosetta/model/lwo/init.luau"], -[157136, "src/Rosetta/model/lwo/Build.luau"], -[157598, "src/Rosetta/model/lwo/Parse.luau"], -[158141, "src/Rosetta/model/mca/init.luau"], -[158483, "src/Rosetta/model/mca/Chunk.luau"], -[158616, "src/Rosetta/model/mca/Lz4Block.luau"], -[158686, "src/Rosetta/model/md2/init.luau"], -[158885, "src/Rosetta/model/md3/init.luau"], -[159113, "src/Rosetta/model/md5/init.luau"], -[159194, "src/Rosetta/model/md5/Read.luau"], -[159627, "src/Rosetta/model/mdl/init.luau"], -[159709, "src/Rosetta/model/mdl/HalfLife.luau"], -[160013, "src/Rosetta/model/mdl/Quake.luau"], -[160231, "src/Rosetta/model/ms3d/init.luau"], -[160303, "src/Rosetta/model/ms3d/Read.luau"], -[160749, "src/Rosetta/model/ms3d/Write.luau"], -[161218, "src/Rosetta/model/obj/init.luau"], -[161960, "src/Rosetta/model/obj/Mtl.luau"], -[162247, "src/Rosetta/model/off/init.luau"], -[162709, "src/Rosetta/model/ply/init.luau"], -[163814, "src/Rosetta/model/ply/Binary.luau"], -[164015, "src/Rosetta/model/pmx/init.luau"], -[164084, "src/Rosetta/model/pmx/Build.luau"], -[164380, "src/Rosetta/model/pmx/Pmd.luau"], -[164715, "src/Rosetta/model/pmx/Read.luau"], -[165119, "src/Rosetta/model/qb/init.luau"], -[165512, "src/Rosetta/model/rbxm/init.luau"], -[166104, "src/Rosetta/model/rbxmx/init.luau"], -[166757, "src/Rosetta/model/robloxmesh/init.luau"], -[167416, "src/Rosetta/model/robloxmesh/Parse.luau"], -[167873, "src/Rosetta/model/robloxmesh/Write.luau"], -[167982, "src/Rosetta/model/schematic/init.luau"], -[168303, "src/Rosetta/model/schematic/Common.luau"], -[168423, "src/Rosetta/model/schematic/Litematic.luau"], -[168634, "src/Rosetta/model/schematic/Mcedit.luau"], -[168878, "src/Rosetta/model/schematic/Sponge.luau"], -[169007, "src/Rosetta/model/smd/init.luau"], -[169074, "src/Rosetta/model/smd/Read.luau"], -[169343, "src/Rosetta/model/smd/Write.luau"], -[169586, "src/Rosetta/model/sourcemdl/init.luau"], -[169757, "src/Rosetta/model/sourcemdl/Build.luau"], -[170187, "src/Rosetta/model/sourcemdl/Material.luau"], -[170348, "src/Rosetta/model/sourcemdl/Mdl.luau"], -[170875, "src/Rosetta/model/sourcemdl/Phy.luau"], -[170998, "src/Rosetta/model/sourcemdl/Vtx.luau"], -[171180, "src/Rosetta/model/sourcemdl/Vvd.luau"], -[171274, "src/Rosetta/model/stl/init.luau"], -[171724, "src/Rosetta/model/stl/Decode.luau"], -[171798, "src/Rosetta/model/usda/init.luau"], -[172007, "src/Rosetta/model/usda/Build.luau"], -[173285, "src/Rosetta/model/usda/Parse.luau"], -[174083, "src/Rosetta/model/usda/Write.luau"], -[174900, "src/Rosetta/model/vox/init.luau"], -[175786, "src/Rosetta/model/vox/Grid.luau"], -[175843, "src/Rosetta/model/vrml/init.luau"], -[175909, "src/Rosetta/model/x/init.luau"], -[176039, "src/Rosetta/model/x/Build.luau"], -[176602, "src/Rosetta/model/x/Parse.luau"], -[176899, "src/Rosetta/model/x3d/init.luau"], -[176977, "src/Rosetta/music/669/init.luau"], -[177183, "src/Rosetta/music/ahx/init.luau"], -[177234, "src/Rosetta/music/far/init.luau"], -[177463, "src/Rosetta/music/hmp/init.luau"], -[177727, "src/Rosetta/music/hvl/init.luau"], -[177778, "src/Rosetta/music/it/init.luau"], -[178196, "src/Rosetta/music/it/Itsex.luau"], -[178312, "src/Rosetta/music/med/init.luau"], -[178959, "src/Rosetta/music/midi/init.luau"], -[179102, "src/Rosetta/music/midi/Smf.luau"], -[179513, "src/Rosetta/music/mod/init.luau"], -[179866, "src/Rosetta/music/mtm/init.luau"], -[180088, "src/Rosetta/music/mus/init.luau"], -[180245, "src/Rosetta/music/okt/init.luau"], -[180526, "src/Rosetta/music/ptm/init.luau"], -[180748, "src/Rosetta/music/s3m/init.luau"], -[180984, "src/Rosetta/music/sf2/init.luau"], -[181027, "src/Rosetta/music/stm/init.luau"], -[181258, "src/Rosetta/music/ult/init.luau"], -[181562, "src/Rosetta/music/umx/init.luau"], -[181778, "src/Rosetta/music/xm/init.luau"], -[182339, "src/Rosetta/music/xmi/init.luau"], -[182547, "src/Rosetta/ops/AudioOps.luau"], -[182996, "src/Rosetta/ops/ImageOps/init.luau"], -[183640, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[184150, "src/Rosetta/ops/LayerOps.luau"], -[184243, "src/Rosetta/ops/MeshOps/init.luau"], -[185279, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[185446, "src/Rosetta/ops/MusicOps.luau"], -[185794, "src/Rosetta/playlist/m3u/init.luau"], -[186147, "src/Rosetta/playlist/pls/init.luau"], -[186325, "src/Rosetta/playlist/xspf/init.luau"], -[186528, "src/Rosetta/subtitle/ass/init.luau"], -[186972, "src/Rosetta/subtitle/srt/init.luau"], -[187145, "src/Rosetta/subtitle/vtt/init.luau"], -[187348, "src/Rosetta/vector/svg/init.luau"], -[187434, "src/Rosetta/vector/svg/Parse.luau"], -[188180, "src/Rosetta/vector/svg/PathData.luau"], -[188548, "src/Rosetta/vector/svg/Render.luau"], -[188965, "src/Rosetta/vector/svg/Style.luau"], -[189337, "src/Rosetta/vector/svg/Write.luau"], -[189537, "src/Rosetta/vector/tiled/init.luau"], -[189717, "src/Rosetta/vector/tiled/Data.luau"], -[189868, "src/Rosetta/vector/tiled/Tmj.luau"], -[190499, "src/Rosetta/vector/tiled/Tmx.luau"], -[191111, "src/Rosetta/video/avi/init.luau"], -[191405, "src/Rosetta/video/fli/init.luau"], -[191556, "src/Rosetta/video/flv/init.luau"], -[191940, "src/Rosetta/video/flv/Amf.luau"], -[192098, "src/Rosetta/video/flv/Mux.luau"], -[192379, "src/Rosetta/video/h264/init.luau"], -[192518, "src/Rosetta/video/mkv/init.luau"], -[192674, "src/Rosetta/video/mkv/Mux.luau"], -[192953, "src/Rosetta/video/mkv/Parse.luau"], -[193674, "src/Rosetta/video/mp4/init.luau"], -[194002, "src/Rosetta/video/mpegps/init.luau"], -[194189, "src/Rosetta/video/mpegts/init.luau"], -[194427, "src/Rosetta/video/ogv/init.luau"], -[194822, "src/Rosetta/video/smk/init.luau"], -[195131, "src/Rosetta/video/smk/Audio.luau"], -[195251, "src/Rosetta/video/y4m/init.luau"] +[3066, "src/Rosetta/Types.luau"], +[4149, "src/Rosetta/archive/7z/init.luau"], +[4534, "src/Rosetta/archive/7z/Header.luau"], +[5061, "src/Rosetta/archive/adf/init.luau"], +[5343, "src/Rosetta/archive/applesingle/init.luau"], +[5529, "src/Rosetta/archive/ar/init.luau"], +[5932, "src/Rosetta/archive/arj/init.luau"], +[6142, "src/Rosetta/archive/binhex/init.luau"], +[6391, "src/Rosetta/archive/br/init.luau"], +[6466, "src/Rosetta/archive/bz2/init.luau"], +[6530, "src/Rosetta/archive/cab/init.luau"], +[6943, "src/Rosetta/archive/cab/Sum.luau"], +[6984, "src/Rosetta/archive/cpio/init.luau"], +[7152, "src/Rosetta/archive/d64/init.luau"], +[7566, "src/Rosetta/archive/fat/init.luau"], +[7688, "src/Rosetta/archive/grp/init.luau"], +[7802, "src/Rosetta/archive/gzip/init.luau"], +[7987, "src/Rosetta/archive/iso/init.luau"], +[8059, "src/Rosetta/archive/lha/init.luau"], +[8484, "src/Rosetta/archive/lz4/init.luau"], +[8828, "src/Rosetta/archive/macbinary/init.luau"], +[9026, "src/Rosetta/archive/mpq/init.luau"], +[9432, "src/Rosetta/archive/mpq/Crypt.luau"], +[9497, "src/Rosetta/archive/pak/init.luau"], +[9631, "src/Rosetta/archive/rpm/init.luau"], +[9955, "src/Rosetta/archive/tar/init.luau"], +[10073, "src/Rosetta/archive/uu/init.luau"], +[10343, "src/Rosetta/archive/vpk/init.luau"], +[10654, "src/Rosetta/archive/wad/init.luau"], +[11104, "src/Rosetta/archive/wad/Map.luau"], +[11534, "src/Rosetta/archive/wad/Picture.luau"], +[11636, "src/Rosetta/archive/xz/init.luau"], +[11736, "src/Rosetta/archive/yenc/init.luau"], +[12008, "src/Rosetta/archive/z/init.luau"], +[12104, "src/Rosetta/archive/zip/init.luau"], +[12323, "src/Rosetta/archive/zoo/init.luau"], +[12519, "src/Rosetta/archive/zst/init.luau"], +[12583, "src/Rosetta/audio/aac/init.luau"], +[12789, "src/Rosetta/audio/ac3/init.luau"], +[12935, "src/Rosetta/audio/adpcm/init.luau"], +[13080, "src/Rosetta/audio/adx/init.luau"], +[13311, "src/Rosetta/audio/aiff/init.luau"], +[13702, "src/Rosetta/audio/ape/init.luau"], +[13830, "src/Rosetta/audio/au/init.luau"], +[13991, "src/Rosetta/audio/brstm/init.luau"], +[14282, "src/Rosetta/audio/caf/init.luau"], +[14944, "src/Rosetta/audio/flac/init.luau"], +[15092, "src/Rosetta/audio/flac/Meta.luau"], +[15314, "src/Rosetta/audio/flac/Stream.luau"], +[15684, "src/Rosetta/audio/m4a/init.luau"], +[16018, "src/Rosetta/audio/mp3/init.luau"], +[16278, "src/Rosetta/audio/mp3/Index.luau"], +[16469, "src/Rosetta/audio/mp3/Stream.luau"], +[16696, "src/Rosetta/audio/mp3/Tags.luau"], +[17008, "src/Rosetta/audio/mpc/init.luau"], +[17102, "src/Rosetta/audio/opus/init.luau"], +[17480, "src/Rosetta/audio/opus/Encode.luau"], +[17591, "src/Rosetta/audio/qoa/init.luau"], +[17771, "src/Rosetta/audio/tta/init.luau"], +[17889, "src/Rosetta/audio/vag/init.luau"], +[18112, "src/Rosetta/audio/voc/init.luau"], +[18387, "src/Rosetta/audio/vorbis/init.luau"], +[18841, "src/Rosetta/audio/vorbis/Encode.luau"], +[19654, "src/Rosetta/audio/wav/init.luau"], +[20275, "src/Rosetta/audio/wav/Codecs.luau"], +[20441, "src/Rosetta/audio/wavpack/init.luau"], +[20648, "src/Rosetta/cad/step/init.luau"], +[21030, "src/Rosetta/cad/step/Brep.luau"], +[21265, "src/Rosetta/cad/step/Parse.luau"], +[21822, "src/Rosetta/cad/step/Write.luau"], +[22070, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22389, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23272, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23607, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[23766, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24651, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[24752, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25506, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[25808, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26042, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26461, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[26873, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27088, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[27849, "src/Rosetta/codecs/audio/ApeTag.luau"], +[27946, "src/Rosetta/codecs/audio/Flac/init.luau"], +[27957, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[28906, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29503, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29699, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[29948, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[30906, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31125, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31309, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31518, "src/Rosetta/codecs/audio/MidiRender.luau"], +[31864, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[31878, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[31937, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33540, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[33832, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34217, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[34858, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[34999, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35225, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35570, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36464, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[36842, "src/Rosetta/codecs/audio/Opus/init.luau"], +[36856, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38703, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[39768, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[39828, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40288, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40625, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[40858, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[42894, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43268, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43531, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[43828, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44110, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44469, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44523, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44666, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45179, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[45960, "src/Rosetta/codecs/audio/Stream.luau"], +[46121, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46603, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[46881, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47050, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47178, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49166, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49282, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49399, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49651, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49664, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50048, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50614, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51035, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51074, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51126, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51348, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[52803, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[52866, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[52953, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[53922, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[54790, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[54838, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55354, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55680, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56100, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56535, "src/Rosetta/codecs/compress/Explode.luau"], +[56731, "src/Rosetta/codecs/compress/Lz4.luau"], +[57000, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57604, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58144, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58182, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58655, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[58831, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59099, "src/Rosetta/codecs/compress/Lzx.luau"], +[59533, "src/Rosetta/codecs/compress/PackBits.luau"], +[59623, "src/Rosetta/codecs/compress/Quantum.luau"], +[59860, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60164, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60233, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60290, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61248, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61400, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61682, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61693, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[61907, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62151, "src/Rosetta/codecs/font/Bitmap.luau"], +[62352, "src/Rosetta/codecs/font/Cff/init.luau"], +[62993, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63143, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63457, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[63849, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64351, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64458, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[64947, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65376, "src/Rosetta/codecs/image/Blend.luau"], +[65755, "src/Rosetta/codecs/image/Dct/init.luau"], +[66136, "src/Rosetta/codecs/image/Etc.luau"], +[66434, "src/Rosetta/codecs/image/Half.luau"], +[66503, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[66857, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67265, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67502, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68262, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69143, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69589, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69667, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69734, "src/Rosetta/codecs/image/Miptex.luau"], +[69950, "src/Rosetta/codecs/image/Pixels.luau"], +[70270, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70729, "src/Rosetta/codecs/image/Raster.luau"], +[71426, "src/Rosetta/codecs/image/Texel.luau"], +[71799, "src/Rosetta/codecs/image/Texture.luau"], +[71944, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72074, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74030, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74289, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74538, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74657, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[74761, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75614, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76566, "src/Rosetta/codecs/image/Yuv.luau"], +[76834, "src/Rosetta/codecs/model/Brush.luau"], +[77474, "src/Rosetta/codecs/model/Displacement.luau"], +[77623, "src/Rosetta/codecs/model/Draco/init.luau"], +[77955, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[78424, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79613, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79762, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80121, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81083, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81557, "src/Rosetta/codecs/model/Mat4.luau"], +[81816, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[82344, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[82896, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[82975, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83082, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[83288, "src/Rosetta/codecs/model/Patch.luau"], +[83412, "src/Rosetta/codecs/model/Polygon.luau"], +[83646, "src/Rosetta/codecs/model/Rbx/init.luau"], +[83883, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[84637, "src/Rosetta/codecs/model/Rig.luau"], +[84880, "src/Rosetta/codecs/model/Sampler.luau"], +[85040, "src/Rosetta/codecs/model/SourceAnim.luau"], +[85261, "src/Rosetta/codecs/model/Vrml/init.luau"], +[85409, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85983, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86146, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86895, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[87417, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88144, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[88376, "src/Rosetta/codecs/text/Json/init.luau"], +[88645, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89059, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89361, "src/Rosetta/codecs/text/KeyValues/init.luau"], +[89931, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], +[90237, "src/Rosetta/codecs/text/Nbt/init.luau"], +[90590, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[91282, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[91922, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[92160, "src/Rosetta/codecs/text/Text/init.luau"], +[92251, "src/Rosetta/codecs/text/Url/init.luau"], +[92456, "src/Rosetta/codecs/text/Xml/init.luau"], +[92859, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[93599, "src/Rosetta/codecs/video/Dsp.luau"], +[94322, "src/Rosetta/codecs/video/H263/init.luau"], +[94478, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[95336, "src/Rosetta/codecs/video/H263/Tables.luau"], +[95539, "src/Rosetta/codecs/video/H264/init.luau"], +[95912, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[96187, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[97318, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[98086, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[98344, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[99353, "src/Rosetta/codecs/video/H264/Inter.luau"], +[99607, "src/Rosetta/codecs/video/H264/Intra.luau"], +[100014, "src/Rosetta/codecs/video/H264/Mb.luau"], +[100920, "src/Rosetta/codecs/video/H264/Params.luau"], +[101367, "src/Rosetta/codecs/video/H264/Slice.luau"], +[101618, "src/Rosetta/codecs/video/H264/Tables.luau"], +[101659, "src/Rosetta/codecs/video/H264/Transform.luau"], +[101824, "src/Rosetta/codecs/video/Legacy/init.luau"], +[102022, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[102319, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[102686, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[102804, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[102912, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[103185, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[103580, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[103757, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[103769, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[104136, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[105643, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[105782, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[105920, "src/Rosetta/codecs/video/Theora/init.luau"], +[106183, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[107447, "src/Rosetta/codecs/video/Theora/Header.luau"], +[107810, "src/Rosetta/codecs/video/Video/init.luau"], +[108367, "src/Rosetta/codecs/video/Video/Source.luau"], +[108652, "src/Rosetta/containers/Archive.luau"], +[108919, "src/Rosetta/containers/AudioWrap.luau"], +[109422, "src/Rosetta/containers/Avi/init.luau"], +[109974, "src/Rosetta/containers/Chunks.luau"], +[110109, "src/Rosetta/containers/Cpio.luau"], +[110537, "src/Rosetta/containers/Demux.luau"], +[110812, "src/Rosetta/containers/Ebml/init.luau"], +[111125, "src/Rosetta/containers/Fat.luau"], +[111813, "src/Rosetta/containers/Iso9660.luau"], +[112318, "src/Rosetta/containers/IsoBmff/init.luau"], +[112488, "src/Rosetta/containers/IsoBmff/Box.luau"], +[112676, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[113521, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[114042, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[114558, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[114675, "src/Rosetta/containers/MacFile.luau"], +[114824, "src/Rosetta/containers/MpegEs.luau"], +[114990, "src/Rosetta/containers/MpegPs/init.luau"], +[115210, "src/Rosetta/containers/MpegTs/init.luau"], +[116002, "src/Rosetta/containers/Ogg/init.luau"], +[116427, "src/Rosetta/containers/Ogg/Mux.luau"], +[116622, "src/Rosetta/containers/Ogg/Page.luau"], +[116791, "src/Rosetta/containers/Riff/init.luau"], +[117108, "src/Rosetta/containers/Tar.luau"], +[117522, "src/Rosetta/containers/Zip/init.luau"], +[118154, "src/Rosetta/core/Adler32.luau"], +[118200, "src/Rosetta/core/Base64.luau"], +[118359, "src/Rosetta/core/Bits.luau"], +[118652, "src/Rosetta/core/Bytes.luau"], +[119179, "src/Rosetta/core/Crc16.luau"], +[119231, "src/Rosetta/core/Crc32.luau"], +[119343, "src/Rosetta/core/Err.luau"], +[119425, "src/Rosetta/core/Input.luau"], +[119501, "src/Rosetta/core/Md5.luau"], +[119660, "src/Rosetta/core/Sniff.luau"], +[119689, "src/Rosetta/data/cbor/init.luau"], +[119788, "src/Rosetta/data/cbor/Codec.luau"], +[120357, "src/Rosetta/data/csv/init.luau"], +[120669, "src/Rosetta/data/ini/init.luau"], +[120915, "src/Rosetta/data/json/init.luau"], +[121007, "src/Rosetta/data/msgpack/init.luau"], +[121096, "src/Rosetta/data/msgpack/Codec.luau"], +[121538, "src/Rosetta/data/nbt/init.luau"], +[121597, "src/Rosetta/data/plist/init.luau"], +[121903, "src/Rosetta/data/plist/Binary.luau"], +[122170, "src/Rosetta/data/snbt/init.luau"], +[122233, "src/Rosetta/data/toml/init.luau"], +[122300, "src/Rosetta/data/toml/Decode.luau"], +[122928, "src/Rosetta/data/toml/Encode.luau"], +[123137, "src/Rosetta/data/vdf/init.luau"], +[123238, "src/Rosetta/data/xml/init.luau"], +[123294, "src/Rosetta/data/yaml/init.luau"], +[123367, "src/Rosetta/data/yaml/Emit.luau"], +[123657, "src/Rosetta/data/yaml/Parse.luau"], +[124950, "src/Rosetta/font/bdf/init.luau"], +[125239, "src/Rosetta/font/bmfont/init.luau"], +[125666, "src/Rosetta/font/bmfont/Parse.luau"], +[126119, "src/Rosetta/font/eot/init.luau"], +[126351, "src/Rosetta/font/fon/init.luau"], +[126634, "src/Rosetta/font/hershey/init.luau"], +[126829, "src/Rosetta/font/pcf/init.luau"], +[127109, "src/Rosetta/font/psf/init.luau"], +[127429, "src/Rosetta/font/ttf/init.luau"], +[127480, "src/Rosetta/font/type1/init.luau"], +[127839, "src/Rosetta/font/type1/Charstring.luau"], +[128117, "src/Rosetta/font/woff/init.luau"], +[128249, "src/Rosetta/font/woff2/init.luau"], +[128306, "src/Rosetta/font/woff2/Rebuild.luau"], +[128846, "src/Rosetta/host/init.luau"], +[128891, "src/Rosetta/host/Love.luau"], +[129034, "src/Rosetta/host/LuaJIT.luau"], +[129084, "src/Rosetta/host/Luau.luau"], +[129107, "src/Rosetta/host/Roblox.luau"], +[129466, "src/Rosetta/image/ani/init.luau"], +[129646, "src/Rosetta/image/art/init.luau"], +[130134, "src/Rosetta/image/blp/init.luau"], +[130392, "src/Rosetta/image/bmp/init.luau"], +[130807, "src/Rosetta/image/dds/init.luau"], +[131290, "src/Rosetta/image/exr/init.luau"], +[132050, "src/Rosetta/image/exr/Codec.luau"], +[132161, "src/Rosetta/image/exr/Piz.luau"], +[132518, "src/Rosetta/image/gif/init.luau"], +[133034, "src/Rosetta/image/gif/Decode.luau"], +[133097, "src/Rosetta/image/hdr/init.luau"], +[133326, "src/Rosetta/image/hdr/Codec.luau"], +[133537, "src/Rosetta/image/icns/init.luau"], +[133868, "src/Rosetta/image/ico/init.luau"], +[134145, "src/Rosetta/image/ico/Dib.luau"], +[134240, "src/Rosetta/image/ilbm/init.luau"], +[134559, "src/Rosetta/image/jpeg/init.luau"], +[134695, "src/Rosetta/image/ktx/init.luau"], +[135355, "src/Rosetta/image/pcx/init.luau"], +[135619, "src/Rosetta/image/png/init.luau"], +[136199, "src/Rosetta/image/png/Apng.luau"], +[136279, "src/Rosetta/image/png/Decode.luau"], +[136519, "src/Rosetta/image/png/Encode.luau"], +[136674, "src/Rosetta/image/pnm/init.luau"], +[137052, "src/Rosetta/image/pnm/Codec.luau"], +[137329, "src/Rosetta/image/qoi/init.luau"], +[137451, "src/Rosetta/image/qoi/Codec.luau"], +[137601, "src/Rosetta/image/sgi/init.luau"], +[137886, "src/Rosetta/image/sunras/init.luau"], +[138132, "src/Rosetta/image/tga/init.luau"], +[138402, "src/Rosetta/image/tga/Codec.luau"], +[138554, "src/Rosetta/image/tiff/init.luau"], +[139381, "src/Rosetta/image/tiff/Pixels.luau"], +[139771, "src/Rosetta/image/tim/init.luau"], +[140013, "src/Rosetta/image/vtf/init.luau"], +[140248, "src/Rosetta/image/webp/init.luau"], +[140858, "src/Rosetta/image/webp/Alpha.luau"], +[140934, "src/Rosetta/image/webp/Anim.luau"], +[141089, "src/Rosetta/image/xbm/init.luau"], +[141250, "src/Rosetta/image/xpm/init.luau"], +[141518, "src/Rosetta/image/xpm/Names.luau"], +[141574, "src/Rosetta/layered/aseprite/init.luau"], +[142312, "src/Rosetta/layered/ora/init.luau"], +[142599, "src/Rosetta/layered/psd/init.luau"], +[143334, "src/Rosetta/layered/psd/Channels.luau"], +[143686, "src/Rosetta/model/3ds/init.luau"], +[143769, "src/Rosetta/model/3ds/Build.luau"], +[144416, "src/Rosetta/model/3ds/Read.luau"], +[144912, "src/Rosetta/model/3ds/Write.luau"], +[145717, "src/Rosetta/model/3mf/init.luau"], +[145799, "src/Rosetta/model/3mf/Read.luau"], +[146387, "src/Rosetta/model/3mf/Write.luau"], +[146792, "src/Rosetta/model/b3d/init.luau"], +[146847, "src/Rosetta/model/b3d/Read.luau"], +[147418, "src/Rosetta/model/bsp/init.luau"], +[147563, "src/Rosetta/model/bsp/Brush.luau"], +[147826, "src/Rosetta/model/bsp/Quake3.luau"], +[148054, "src/Rosetta/model/buildmap/init.luau"], +[148326, "src/Rosetta/model/buildmap/Geometry.luau"], +[148729, "src/Rosetta/model/dae/init.luau"], +[148918, "src/Rosetta/model/dae/Math.luau"], +[148965, "src/Rosetta/model/dae/Read.luau"], +[150815, "src/Rosetta/model/dae/Write.luau"], +[151184, "src/Rosetta/model/fbx/init.luau"], +[151332, "src/Rosetta/model/fbx/Ascii.luau"], +[151602, "src/Rosetta/model/fbx/Binary.luau"], +[152057, "src/Rosetta/model/fbx/Read.luau"], +[153419, "src/Rosetta/model/fbx/Write.luau"], +[154404, "src/Rosetta/model/fbx/Xform.luau"], +[154445, "src/Rosetta/model/gltf/init.luau"], +[154682, "src/Rosetta/model/gltf/Pack.luau"], +[154751, "src/Rosetta/model/gltf/Read.luau"], +[155482, "src/Rosetta/model/gltf/Write.luau"], +[156162, "src/Rosetta/model/iqm/init.luau"], +[156238, "src/Rosetta/model/iqm/Read.luau"], +[156593, "src/Rosetta/model/iqm/Write.luau"], +[157280, "src/Rosetta/model/ldraw/init.luau"], +[157358, "src/Rosetta/model/ldraw/Colors.luau"], +[157676, "src/Rosetta/model/ldraw/Read.luau"], +[158253, "src/Rosetta/model/lwo/init.luau"], +[158329, "src/Rosetta/model/lwo/Build.luau"], +[158791, "src/Rosetta/model/lwo/Parse.luau"], +[159334, "src/Rosetta/model/map/init.luau"], +[159651, "src/Rosetta/model/map/Build.luau"], +[159894, "src/Rosetta/model/map/Parse.luau"], +[160279, "src/Rosetta/model/map/Write.luau"], +[160425, "src/Rosetta/model/mca/init.luau"], +[160767, "src/Rosetta/model/mca/Chunk.luau"], +[160900, "src/Rosetta/model/mca/Lz4Block.luau"], +[160970, "src/Rosetta/model/md2/init.luau"], +[161169, "src/Rosetta/model/md3/init.luau"], +[161397, "src/Rosetta/model/md5/init.luau"], +[161478, "src/Rosetta/model/md5/Read.luau"], +[161911, "src/Rosetta/model/mdl/init.luau"], +[161993, "src/Rosetta/model/mdl/HalfLife.luau"], +[162297, "src/Rosetta/model/mdl/Quake.luau"], +[162515, "src/Rosetta/model/ms3d/init.luau"], +[162587, "src/Rosetta/model/ms3d/Read.luau"], +[163033, "src/Rosetta/model/ms3d/Write.luau"], +[163502, "src/Rosetta/model/obj/init.luau"], +[164244, "src/Rosetta/model/obj/Mtl.luau"], +[164531, "src/Rosetta/model/off/init.luau"], +[164993, "src/Rosetta/model/ply/init.luau"], +[166098, "src/Rosetta/model/ply/Binary.luau"], +[166299, "src/Rosetta/model/pmx/init.luau"], +[166368, "src/Rosetta/model/pmx/Build.luau"], +[166664, "src/Rosetta/model/pmx/Pmd.luau"], +[166999, "src/Rosetta/model/pmx/Read.luau"], +[167403, "src/Rosetta/model/qb/init.luau"], +[167796, "src/Rosetta/model/rbxm/init.luau"], +[168388, "src/Rosetta/model/rbxmx/init.luau"], +[169041, "src/Rosetta/model/robloxmesh/init.luau"], +[169700, "src/Rosetta/model/robloxmesh/Parse.luau"], +[170157, "src/Rosetta/model/robloxmesh/Write.luau"], +[170266, "src/Rosetta/model/schematic/init.luau"], +[170587, "src/Rosetta/model/schematic/Common.luau"], +[170707, "src/Rosetta/model/schematic/Litematic.luau"], +[170918, "src/Rosetta/model/schematic/Mcedit.luau"], +[171162, "src/Rosetta/model/schematic/Sponge.luau"], +[171291, "src/Rosetta/model/smd/init.luau"], +[171358, "src/Rosetta/model/smd/Read.luau"], +[171627, "src/Rosetta/model/smd/Write.luau"], +[171870, "src/Rosetta/model/sourcemdl/init.luau"], +[172041, "src/Rosetta/model/sourcemdl/Build.luau"], +[172471, "src/Rosetta/model/sourcemdl/Material.luau"], +[172632, "src/Rosetta/model/sourcemdl/Mdl.luau"], +[173159, "src/Rosetta/model/sourcemdl/Phy.luau"], +[173282, "src/Rosetta/model/sourcemdl/Vtx.luau"], +[173464, "src/Rosetta/model/sourcemdl/Vvd.luau"], +[173558, "src/Rosetta/model/stl/init.luau"], +[174008, "src/Rosetta/model/stl/Decode.luau"], +[174082, "src/Rosetta/model/usda/init.luau"], +[174291, "src/Rosetta/model/usda/Build.luau"], +[175569, "src/Rosetta/model/usda/Parse.luau"], +[176367, "src/Rosetta/model/usda/Write.luau"], +[177184, "src/Rosetta/model/vbsp/init.luau"], +[177630, "src/Rosetta/model/vbsp/Faces.luau"], +[177854, "src/Rosetta/model/vbsp/Props.luau"], +[177946, "src/Rosetta/model/vmf/init.luau"], +[178271, "src/Rosetta/model/vmf/Build.luau"], +[178695, "src/Rosetta/model/vox/init.luau"], +[179581, "src/Rosetta/model/vox/Grid.luau"], +[179638, "src/Rosetta/model/vrml/init.luau"], +[179704, "src/Rosetta/model/x/init.luau"], +[179834, "src/Rosetta/model/x/Build.luau"], +[180397, "src/Rosetta/model/x/Parse.luau"], +[180694, "src/Rosetta/model/x3d/init.luau"], +[180772, "src/Rosetta/music/669/init.luau"], +[180978, "src/Rosetta/music/ahx/init.luau"], +[181029, "src/Rosetta/music/far/init.luau"], +[181258, "src/Rosetta/music/hmp/init.luau"], +[181522, "src/Rosetta/music/hvl/init.luau"], +[181573, "src/Rosetta/music/it/init.luau"], +[181991, "src/Rosetta/music/it/Itsex.luau"], +[182107, "src/Rosetta/music/med/init.luau"], +[182754, "src/Rosetta/music/midi/init.luau"], +[182897, "src/Rosetta/music/midi/Smf.luau"], +[183308, "src/Rosetta/music/mod/init.luau"], +[183661, "src/Rosetta/music/mtm/init.luau"], +[183883, "src/Rosetta/music/mus/init.luau"], +[184040, "src/Rosetta/music/okt/init.luau"], +[184321, "src/Rosetta/music/ptm/init.luau"], +[184543, "src/Rosetta/music/s3m/init.luau"], +[184779, "src/Rosetta/music/sf2/init.luau"], +[184822, "src/Rosetta/music/stm/init.luau"], +[185053, "src/Rosetta/music/ult/init.luau"], +[185357, "src/Rosetta/music/umx/init.luau"], +[185573, "src/Rosetta/music/xm/init.luau"], +[186134, "src/Rosetta/music/xmi/init.luau"], +[186342, "src/Rosetta/ops/AudioOps.luau"], +[186791, "src/Rosetta/ops/ImageOps/init.luau"], +[187435, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[187945, "src/Rosetta/ops/LayerOps.luau"], +[188038, "src/Rosetta/ops/MeshOps/init.luau"], +[189074, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[189241, "src/Rosetta/ops/MusicOps.luau"], +[189589, "src/Rosetta/playlist/m3u/init.luau"], +[189942, "src/Rosetta/playlist/pls/init.luau"], +[190120, "src/Rosetta/playlist/xspf/init.luau"], +[190323, "src/Rosetta/subtitle/ass/init.luau"], +[190767, "src/Rosetta/subtitle/srt/init.luau"], +[190940, "src/Rosetta/subtitle/vtt/init.luau"], +[191143, "src/Rosetta/vector/svg/init.luau"], +[191229, "src/Rosetta/vector/svg/Parse.luau"], +[191975, "src/Rosetta/vector/svg/PathData.luau"], +[192343, "src/Rosetta/vector/svg/Render.luau"], +[192760, "src/Rosetta/vector/svg/Style.luau"], +[193132, "src/Rosetta/vector/svg/Write.luau"], +[193332, "src/Rosetta/vector/tiled/init.luau"], +[193512, "src/Rosetta/vector/tiled/Data.luau"], +[193663, "src/Rosetta/vector/tiled/Tmj.luau"], +[194294, "src/Rosetta/vector/tiled/Tmx.luau"], +[194906, "src/Rosetta/video/avi/init.luau"], +[195200, "src/Rosetta/video/fli/init.luau"], +[195351, "src/Rosetta/video/flv/init.luau"], +[195735, "src/Rosetta/video/flv/Amf.luau"], +[195893, "src/Rosetta/video/flv/Mux.luau"], +[196174, "src/Rosetta/video/h264/init.luau"], +[196313, "src/Rosetta/video/mkv/init.luau"], +[196469, "src/Rosetta/video/mkv/Mux.luau"], +[196748, "src/Rosetta/video/mkv/Parse.luau"], +[197469, "src/Rosetta/video/mp4/init.luau"], +[197797, "src/Rosetta/video/mpegps/init.luau"], +[197984, "src/Rosetta/video/mpegts/init.luau"], +[198222, "src/Rosetta/video/ogv/init.luau"], +[198617, "src/Rosetta/video/smk/init.luau"], +[198926, "src/Rosetta/video/smk/Audio.luau"], +[199046, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/Rosetta.rbxm b/build/Rosetta.rbxm index dfb6c20..d21bbe7 100644 Binary files a/build/Rosetta.rbxm and b/build/Rosetta.rbxm differ diff --git a/build/Rosetta.rbxm.linemap.json b/build/Rosetta.rbxm.linemap.json index 603ea9a..17d3aa1 100644 --- a/build/Rosetta.rbxm.linemap.json +++ b/build/Rosetta.rbxm.linemap.json @@ -1,5 +1,5 @@ { -"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3009, "src/Rosetta/Types.luau"], [4092, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4846, "src/Rosetta/codecs/image/Yuv.luau"], [5114, "src/Rosetta/codecs/model/Rbx/init.luau"], [5351, "src/Rosetta/codecs/video/Video/init.luau"], [5908, "src/Rosetta/containers/AudioWrap.luau"], [6411, "src/Rosetta/containers/Ogg/Mux.luau"], [6606, "src/Rosetta/containers/Ogg/Page.luau"], [6775, "src/Rosetta/core/Bytes.luau"], [7302, "src/Rosetta/core/Crc32.luau"], [7414, "src/Rosetta/core/Err.luau"], [7496, "src/Rosetta/core/Input.luau"], [7572, "src/Rosetta/host/init.luau"]], +"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3045, "src/Rosetta/Types.luau"], [4128, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4882, "src/Rosetta/codecs/image/Yuv.luau"], [5150, "src/Rosetta/codecs/model/Rbx/init.luau"], [5387, "src/Rosetta/codecs/video/Video/init.luau"], [5944, "src/Rosetta/containers/AudioWrap.luau"], [6447, "src/Rosetta/containers/Ogg/Mux.luau"], [6642, "src/Rosetta/containers/Ogg/Page.luau"], [6811, "src/Rosetta/core/Bytes.luau"], [7338, "src/Rosetta/core/Crc32.luau"], [7450, "src/Rosetta/core/Err.luau"], [7532, "src/Rosetta/core/Input.luau"], [7608, "src/Rosetta/host/init.luau"]], "Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]], "Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]], "H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]], @@ -35,9 +35,9 @@ "codecs_compress": [[8, "src/Rosetta/codecs/compress/Bzip2/init.luau"], [56, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], [572, "src/Rosetta/codecs/compress/Explode.luau"], [768, "src/Rosetta/codecs/compress/Lz4.luau"], [1037, "src/Rosetta/codecs/compress/Lzh/init.luau"], [1641, "src/Rosetta/codecs/compress/Lzw/init.luau"], [1909, "src/Rosetta/codecs/compress/Lzx.luau"], [2343, "src/Rosetta/codecs/compress/PackBits.luau"], [2433, "src/Rosetta/codecs/compress/Quantum.luau"], [2670, "src/Rosetta/codecs/compress/UnixCompress.luau"], [2974, "src/Rosetta/codecs/compress/Xxh32.luau"]], "codecs_entropy": [[8, "src/Rosetta/codecs/entropy/Huffman.luau"], [290, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], [301, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], [515, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"]], "codecs_font": [[8, "src/Rosetta/codecs/font/Bitmap.luau"], [209, "src/Rosetta/codecs/font/Cff/init.luau"], [850, "src/Rosetta/codecs/font/GlyphNames.luau"], [1000, "src/Rosetta/codecs/font/TrueType/init.luau"], [1314, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], [1706, "src/Rosetta/codecs/font/TrueType/Tables.luau"]], -"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Pixels.luau"], [1018, "src/Rosetta/codecs/image/Quantize/init.luau"], [1477, "src/Rosetta/codecs/image/Raster.luau"], [2174, "src/Rosetta/codecs/image/Texel.luau"], [2547, "src/Rosetta/codecs/image/Texture.luau"]], -"codecs_model": [[8, "src/Rosetta/codecs/model/Mat4.luau"], [267, "src/Rosetta/codecs/model/MeshFlatten.luau"], [795, "src/Rosetta/codecs/model/Minecraft/init.luau"], [1347, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [1426, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [1533, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [1739, "src/Rosetta/codecs/model/Polygon.luau"], [1973, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [2727, "src/Rosetta/codecs/model/Rig.luau"], [2970, "src/Rosetta/codecs/model/Sampler.luau"], [3130, "src/Rosetta/codecs/model/SourceAnim.luau"], [3351, "src/Rosetta/codecs/model/Vrml/init.luau"], [3499, "src/Rosetta/codecs/model/Vrml/Build.luau"], [4073, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [4236, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [4985, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [5507, "src/Rosetta/codecs/model/Vrml/Write.luau"], [6234, "src/Rosetta/codecs/model/Vrml/Xml.luau"]], -"codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/KeyValues/init.luau"], [1550, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1855, "src/Rosetta/codecs/text/Nbt/init.luau"], [2208, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [2900, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3540, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3778, "src/Rosetta/codecs/text/Text/init.luau"], [3869, "src/Rosetta/codecs/text/Url/init.luau"], [4074, "src/Rosetta/codecs/text/Xml/init.luau"], [4477, "src/Rosetta/codecs/text/Xml/Parse.luau"]], +"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Miptex.luau"], [970, "src/Rosetta/codecs/image/Pixels.luau"], [1290, "src/Rosetta/codecs/image/Quantize/init.luau"], [1749, "src/Rosetta/codecs/image/Raster.luau"], [2446, "src/Rosetta/codecs/image/Texel.luau"], [2819, "src/Rosetta/codecs/image/Texture.luau"]], +"codecs_model": [[8, "src/Rosetta/codecs/model/Brush.luau"], [648, "src/Rosetta/codecs/model/Displacement.luau"], [797, "src/Rosetta/codecs/model/Mat4.luau"], [1056, "src/Rosetta/codecs/model/MeshFlatten.luau"], [1584, "src/Rosetta/codecs/model/Minecraft/init.luau"], [2136, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [2215, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [2322, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [2528, "src/Rosetta/codecs/model/Patch.luau"], [2652, "src/Rosetta/codecs/model/Polygon.luau"], [2886, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [3640, "src/Rosetta/codecs/model/Rig.luau"], [3883, "src/Rosetta/codecs/model/Sampler.luau"], [4043, "src/Rosetta/codecs/model/SourceAnim.luau"], [4264, "src/Rosetta/codecs/model/Vrml/init.luau"], [4412, "src/Rosetta/codecs/model/Vrml/Build.luau"], [4986, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [5149, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [5898, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [6420, "src/Rosetta/codecs/model/Vrml/Write.luau"], [7147, "src/Rosetta/codecs/model/Vrml/Xml.luau"]], +"codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/KeyValues/init.luau"], [1563, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1869, "src/Rosetta/codecs/text/Nbt/init.luau"], [2222, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [2914, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3554, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3792, "src/Rosetta/codecs/text/Text/init.luau"], [3883, "src/Rosetta/codecs/text/Url/init.luau"], [4088, "src/Rosetta/codecs/text/Xml/init.luau"], [4491, "src/Rosetta/codecs/text/Xml/Parse.luau"]], "codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]], "containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Chunks.luau"], [962, "src/Rosetta/containers/Cpio.luau"], [1390, "src/Rosetta/containers/Demux.luau"], [1665, "src/Rosetta/containers/Ebml/init.luau"], [1978, "src/Rosetta/containers/Fat.luau"], [2666, "src/Rosetta/containers/Iso9660.luau"], [3171, "src/Rosetta/containers/IsoBmff/init.luau"], [3341, "src/Rosetta/containers/IsoBmff/Box.luau"], [3529, "src/Rosetta/containers/IsoBmff/Demux.luau"], [4374, "src/Rosetta/containers/IsoBmff/Meta.luau"], [4895, "src/Rosetta/containers/IsoBmff/Mux.luau"], [5411, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [5528, "src/Rosetta/containers/MacFile.luau"], [5677, "src/Rosetta/containers/Ogg/init.luau"], [6102, "src/Rosetta/containers/Riff/init.luau"], [6419, "src/Rosetta/containers/Tar.luau"], [6833, "src/Rosetta/containers/Zip/init.luau"]], "core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]], @@ -47,11 +47,11 @@ "image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/pcx/init.luau"], [6161, "src/Rosetta/image/pnm/init.luau"], [6539, "src/Rosetta/image/pnm/Codec.luau"], [6816, "src/Rosetta/image/qoi/init.luau"], [6938, "src/Rosetta/image/qoi/Codec.luau"], [7088, "src/Rosetta/image/sgi/init.luau"], [7373, "src/Rosetta/image/sunras/init.luau"], [7619, "src/Rosetta/image/tga/init.luau"]], "image_2": [[8, "src/Rosetta/image/tga/Codec.luau"], [160, "src/Rosetta/image/tiff/init.luau"], [987, "src/Rosetta/image/tiff/Pixels.luau"], [1377, "src/Rosetta/image/tim/init.luau"], [1619, "src/Rosetta/image/vtf/init.luau"], [1854, "src/Rosetta/image/webp/init.luau"], [2464, "src/Rosetta/image/webp/Alpha.luau"], [2540, "src/Rosetta/image/webp/Anim.luau"], [2695, "src/Rosetta/image/xbm/init.luau"], [2856, "src/Rosetta/image/xpm/init.luau"], [3124, "src/Rosetta/image/xpm/Names.luau"]], "layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]], -"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4163, "src/Rosetta/model/bsp/Quake3.luau"], [4418, "src/Rosetta/model/buildmap/init.luau"], [4690, "src/Rosetta/model/buildmap/Geometry.luau"], [5093, "src/Rosetta/model/dae/init.luau"], [5282, "src/Rosetta/model/dae/Math.luau"], [5329, "src/Rosetta/model/dae/Read.luau"], [7179, "src/Rosetta/model/dae/Write.luau"], [7548, "src/Rosetta/model/fbx/init.luau"]], +"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4148, "src/Rosetta/model/bsp/Quake3.luau"], [4376, "src/Rosetta/model/buildmap/init.luau"], [4648, "src/Rosetta/model/buildmap/Geometry.luau"], [5051, "src/Rosetta/model/dae/init.luau"], [5240, "src/Rosetta/model/dae/Math.luau"], [5287, "src/Rosetta/model/dae/Read.luau"], [7137, "src/Rosetta/model/dae/Write.luau"], [7506, "src/Rosetta/model/fbx/init.luau"]], "model_2": [[8, "src/Rosetta/model/fbx/Ascii.luau"], [278, "src/Rosetta/model/fbx/Binary.luau"], [733, "src/Rosetta/model/fbx/Read.luau"], [2095, "src/Rosetta/model/fbx/Write.luau"], [3080, "src/Rosetta/model/fbx/Xform.luau"], [3121, "src/Rosetta/model/gltf/init.luau"], [3358, "src/Rosetta/model/gltf/Pack.luau"], [3427, "src/Rosetta/model/gltf/Read.luau"], [4158, "src/Rosetta/model/gltf/Write.luau"], [4838, "src/Rosetta/model/iqm/init.luau"], [4914, "src/Rosetta/model/iqm/Read.luau"], [5269, "src/Rosetta/model/iqm/Write.luau"], [5956, "src/Rosetta/model/ldraw/init.luau"], [6034, "src/Rosetta/model/ldraw/Colors.luau"], [6352, "src/Rosetta/model/ldraw/Read.luau"], [6929, "src/Rosetta/model/lwo/init.luau"], [7005, "src/Rosetta/model/lwo/Build.luau"]], -"model_3": [[8, "src/Rosetta/model/lwo/Parse.luau"], [551, "src/Rosetta/model/mca/init.luau"], [893, "src/Rosetta/model/mca/Chunk.luau"], [1026, "src/Rosetta/model/mca/Lz4Block.luau"], [1096, "src/Rosetta/model/md2/init.luau"], [1295, "src/Rosetta/model/md3/init.luau"], [1523, "src/Rosetta/model/md5/init.luau"], [1604, "src/Rosetta/model/md5/Read.luau"], [2037, "src/Rosetta/model/mdl/init.luau"], [2119, "src/Rosetta/model/mdl/HalfLife.luau"], [2423, "src/Rosetta/model/mdl/Quake.luau"], [2641, "src/Rosetta/model/ms3d/init.luau"], [2713, "src/Rosetta/model/ms3d/Read.luau"], [3159, "src/Rosetta/model/ms3d/Write.luau"], [3628, "src/Rosetta/model/obj/init.luau"], [4370, "src/Rosetta/model/obj/Mtl.luau"], [4657, "src/Rosetta/model/off/init.luau"], [5119, "src/Rosetta/model/ply/init.luau"], [6224, "src/Rosetta/model/ply/Binary.luau"], [6425, "src/Rosetta/model/pmx/init.luau"], [6494, "src/Rosetta/model/pmx/Build.luau"], [6790, "src/Rosetta/model/pmx/Pmd.luau"], [7125, "src/Rosetta/model/pmx/Read.luau"], [7529, "src/Rosetta/model/qb/init.luau"]], -"model_4": [[8, "src/Rosetta/model/rbxm/init.luau"], [600, "src/Rosetta/model/rbxmx/init.luau"], [1253, "src/Rosetta/model/robloxmesh/init.luau"], [1912, "src/Rosetta/model/robloxmesh/Parse.luau"], [2369, "src/Rosetta/model/robloxmesh/Write.luau"], [2478, "src/Rosetta/model/schematic/init.luau"], [2799, "src/Rosetta/model/schematic/Common.luau"], [2919, "src/Rosetta/model/schematic/Litematic.luau"], [3130, "src/Rosetta/model/schematic/Mcedit.luau"], [3374, "src/Rosetta/model/schematic/Sponge.luau"], [3503, "src/Rosetta/model/smd/init.luau"], [3570, "src/Rosetta/model/smd/Read.luau"], [3839, "src/Rosetta/model/smd/Write.luau"], [4082, "src/Rosetta/model/sourcemdl/init.luau"], [4253, "src/Rosetta/model/sourcemdl/Build.luau"], [4683, "src/Rosetta/model/sourcemdl/Material.luau"], [4844, "src/Rosetta/model/sourcemdl/Mdl.luau"], [5371, "src/Rosetta/model/sourcemdl/Phy.luau"], [5494, "src/Rosetta/model/sourcemdl/Vtx.luau"], [5676, "src/Rosetta/model/sourcemdl/Vvd.luau"], [5770, "src/Rosetta/model/stl/init.luau"], [6220, "src/Rosetta/model/stl/Decode.luau"], [6294, "src/Rosetta/model/usda/init.luau"], [6503, "src/Rosetta/model/usda/Build.luau"]], -"model_5": [[8, "src/Rosetta/model/usda/Parse.luau"], [806, "src/Rosetta/model/usda/Write.luau"], [1623, "src/Rosetta/model/vox/init.luau"], [2509, "src/Rosetta/model/vox/Grid.luau"], [2566, "src/Rosetta/model/vrml/init.luau"], [2632, "src/Rosetta/model/x/init.luau"], [2762, "src/Rosetta/model/x/Build.luau"], [3325, "src/Rosetta/model/x/Parse.luau"], [3622, "src/Rosetta/model/x3d/init.luau"]], +"model_3": [[8, "src/Rosetta/model/lwo/Parse.luau"], [551, "src/Rosetta/model/map/init.luau"], [868, "src/Rosetta/model/map/Build.luau"], [1111, "src/Rosetta/model/map/Parse.luau"], [1496, "src/Rosetta/model/map/Write.luau"], [1642, "src/Rosetta/model/mca/init.luau"], [1984, "src/Rosetta/model/mca/Chunk.luau"], [2117, "src/Rosetta/model/mca/Lz4Block.luau"], [2187, "src/Rosetta/model/md2/init.luau"], [2386, "src/Rosetta/model/md3/init.luau"], [2614, "src/Rosetta/model/md5/init.luau"], [2695, "src/Rosetta/model/md5/Read.luau"], [3128, "src/Rosetta/model/mdl/init.luau"], [3210, "src/Rosetta/model/mdl/HalfLife.luau"], [3514, "src/Rosetta/model/mdl/Quake.luau"], [3732, "src/Rosetta/model/ms3d/init.luau"], [3804, "src/Rosetta/model/ms3d/Read.luau"], [4250, "src/Rosetta/model/ms3d/Write.luau"], [4719, "src/Rosetta/model/obj/init.luau"], [5461, "src/Rosetta/model/obj/Mtl.luau"], [5748, "src/Rosetta/model/off/init.luau"], [6210, "src/Rosetta/model/ply/init.luau"], [7315, "src/Rosetta/model/ply/Binary.luau"], [7516, "src/Rosetta/model/pmx/init.luau"], [7585, "src/Rosetta/model/pmx/Build.luau"]], +"model_4": [[8, "src/Rosetta/model/pmx/Pmd.luau"], [343, "src/Rosetta/model/pmx/Read.luau"], [747, "src/Rosetta/model/qb/init.luau"], [1140, "src/Rosetta/model/rbxm/init.luau"], [1732, "src/Rosetta/model/rbxmx/init.luau"], [2385, "src/Rosetta/model/robloxmesh/init.luau"], [3044, "src/Rosetta/model/robloxmesh/Parse.luau"], [3501, "src/Rosetta/model/robloxmesh/Write.luau"], [3610, "src/Rosetta/model/schematic/init.luau"], [3931, "src/Rosetta/model/schematic/Common.luau"], [4051, "src/Rosetta/model/schematic/Litematic.luau"], [4262, "src/Rosetta/model/schematic/Mcedit.luau"], [4506, "src/Rosetta/model/schematic/Sponge.luau"], [4635, "src/Rosetta/model/smd/init.luau"], [4702, "src/Rosetta/model/smd/Read.luau"], [4971, "src/Rosetta/model/smd/Write.luau"], [5214, "src/Rosetta/model/sourcemdl/init.luau"], [5385, "src/Rosetta/model/sourcemdl/Build.luau"], [5815, "src/Rosetta/model/sourcemdl/Material.luau"], [5976, "src/Rosetta/model/sourcemdl/Mdl.luau"], [6503, "src/Rosetta/model/sourcemdl/Phy.luau"], [6626, "src/Rosetta/model/sourcemdl/Vtx.luau"], [6808, "src/Rosetta/model/sourcemdl/Vvd.luau"], [6902, "src/Rosetta/model/stl/init.luau"], [7352, "src/Rosetta/model/stl/Decode.luau"], [7426, "src/Rosetta/model/usda/init.luau"]], +"model_5": [[8, "src/Rosetta/model/usda/Build.luau"], [1286, "src/Rosetta/model/usda/Parse.luau"], [2084, "src/Rosetta/model/usda/Write.luau"], [2901, "src/Rosetta/model/vbsp/init.luau"], [3347, "src/Rosetta/model/vbsp/Faces.luau"], [3571, "src/Rosetta/model/vbsp/Props.luau"], [3663, "src/Rosetta/model/vmf/init.luau"], [3988, "src/Rosetta/model/vmf/Build.luau"], [4412, "src/Rosetta/model/vox/init.luau"], [5298, "src/Rosetta/model/vox/Grid.luau"], [5355, "src/Rosetta/model/vrml/init.luau"], [5421, "src/Rosetta/model/x/init.luau"], [5551, "src/Rosetta/model/x/Build.luau"], [6114, "src/Rosetta/model/x/Parse.luau"], [6411, "src/Rosetta/model/x3d/init.luau"]], "music": [[8, "src/Rosetta/music/669/init.luau"], [214, "src/Rosetta/music/ahx/init.luau"], [265, "src/Rosetta/music/far/init.luau"], [494, "src/Rosetta/music/hmp/init.luau"], [758, "src/Rosetta/music/hvl/init.luau"], [809, "src/Rosetta/music/it/init.luau"], [1227, "src/Rosetta/music/it/Itsex.luau"], [1343, "src/Rosetta/music/med/init.luau"], [1990, "src/Rosetta/music/midi/init.luau"], [2133, "src/Rosetta/music/midi/Smf.luau"], [2544, "src/Rosetta/music/mod/init.luau"], [2897, "src/Rosetta/music/mtm/init.luau"], [3119, "src/Rosetta/music/mus/init.luau"], [3276, "src/Rosetta/music/okt/init.luau"], [3557, "src/Rosetta/music/ptm/init.luau"], [3779, "src/Rosetta/music/s3m/init.luau"], [4015, "src/Rosetta/music/sf2/init.luau"], [4058, "src/Rosetta/music/stm/init.luau"], [4289, "src/Rosetta/music/ult/init.luau"], [4593, "src/Rosetta/music/umx/init.luau"], [4809, "src/Rosetta/music/xm/init.luau"], [5370, "src/Rosetta/music/xmi/init.luau"]], "ops": [[8, "src/Rosetta/ops/AudioOps.luau"], [457, "src/Rosetta/ops/LayerOps.luau"], [550, "src/Rosetta/ops/MeshOps/init.luau"], [1586, "src/Rosetta/ops/MeshOps/Greedy.luau"], [1753, "src/Rosetta/ops/MusicOps.luau"]], "playlist": [[8, "src/Rosetta/playlist/m3u/init.luau"], [361, "src/Rosetta/playlist/pls/init.luau"], [539, "src/Rosetta/playlist/xspf/init.luau"]], diff --git a/build/Rosetta.rbxmx b/build/Rosetta.rbxmx index f15201e..bd43279 100644 --- a/build/Rosetta.rbxmx +++ b/build/Rosetta.rbxmx @@ -268,17 +268,21 @@ local __CHUNK = { ["codecs/image/Blend"] = "codecs_image", ["codecs/image/Etc"] = "codecs_image", ["codecs/image/Half"] = "codecs_image", + ["codecs/image/Miptex"] = "codecs_image", ["codecs/image/Pixels"] = "codecs_image", ["codecs/image/Quantize"] = "codecs_image", ["codecs/image/Raster"] = "codecs_image", ["codecs/image/Texel"] = "codecs_image", ["codecs/image/Texture"] = "codecs_image", + ["codecs/model/Brush"] = "codecs_model", + ["codecs/model/Displacement"] = "codecs_model", ["codecs/model/Mat4"] = "codecs_model", ["codecs/model/MeshFlatten"] = "codecs_model", ["codecs/model/Minecraft"] = "codecs_model", ["codecs/model/Minecraft/Colors"] = "codecs_model", ["codecs/model/Minecraft/Legacy"] = "codecs_model", ["codecs/model/Minecraft/Packed"] = "codecs_model", + ["codecs/model/Patch"] = "codecs_model", ["codecs/model/Polygon"] = "codecs_model", ["codecs/model/Rbx/Binary"] = "codecs_model", ["codecs/model/Rig"] = "codecs_model", @@ -445,6 +449,10 @@ local __CHUNK = { ["model/lwo"] = "model_2", ["model/lwo/Build"] = "model_2", ["model/lwo/Parse"] = "model_3", + ["model/map"] = "model_3", + ["model/map/Build"] = "model_3", + ["model/map/Parse"] = "model_3", + ["model/map/Write"] = "model_3", ["model/mca"] = "model_3", ["model/mca/Chunk"] = "model_3", ["model/mca/Lz4Block"] = "model_3", @@ -465,9 +473,9 @@ local __CHUNK = { ["model/ply/Binary"] = "model_3", ["model/pmx"] = "model_3", ["model/pmx/Build"] = "model_3", - ["model/pmx/Pmd"] = "model_3", - ["model/pmx/Read"] = "model_3", - ["model/qb"] = "model_3", + ["model/pmx/Pmd"] = "model_4", + ["model/pmx/Read"] = "model_4", + ["model/qb"] = "model_4", ["model/rbxm"] = "model_4", ["model/rbxmx"] = "model_4", ["model/robloxmesh"] = "model_4", @@ -491,9 +499,14 @@ local __CHUNK = { ["model/stl"] = "model_4", ["model/stl/Decode"] = "model_4", ["model/usda"] = "model_4", - ["model/usda/Build"] = "model_4", + ["model/usda/Build"] = "model_5", ["model/usda/Parse"] = "model_5", ["model/usda/Write"] = "model_5", + ["model/vbsp"] = "model_5", + ["model/vbsp/Faces"] = "model_5", + ["model/vbsp/Props"] = "model_5", + ["model/vmf"] = "model_5", + ["model/vmf/Build"] = "model_5", ["model/vox"] = "model_5", ["model/vox/Grid"] = "model_5", ["model/vrml"] = "model_5", @@ -2217,7 +2230,7 @@ local list: { Entry } = { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, load = function() return __include("model/bsp") @@ -2307,6 +2320,18 @@ local list: { Entry } = { return __include("model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return __include("model/map") + end, + }, { name = "mca", category = "model", @@ -2535,6 +2560,30 @@ local list: { Entry } = { return __include("model/usda") end, }, + { + name = "vbsp", + category = "model", + path = "model/vbsp", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, + load = function() + return __include("model/vbsp") + end, + }, + { + name = "vmf", + category = "model", + path = "model/vmf", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, + load = function() + return __include("model/vmf") + end, + }, { name = "vox", category = "model", @@ -98931,7 +98980,7 @@ end --!optimize 2 --!nocheck -- rosetta chunk codecs_image (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 8 modules (7 native: @native); the Rosetta root requires it when one of them is first included. +-- 9 modules (7 native: @native); the Rosetta root requires it when one of them is first included. -- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). return function(__FILES, __include) __FILES["codecs/image/Blend"] = @native function() @@ -99680,12 +99729,229 @@ end return Half end +__FILES["codecs/image/Miptex"] = function() + +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Quantize = __include("codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +type Header = { name: string, width: number, height: number, offsets: { number } } +type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } +type DecodeOptions = { + palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own + goldsrc: boolean?, -- read the palette stored after mip 3 + mip: number?, -- 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: names starting with '{' + maxPixels: number?, -- default 2^24 +} + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) + if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b: buffer, at: number, size: number, hd: Header): buffer? + local w, h = hd.width, hd.height + local p = hd.offsets[4] + (w // 8) * (h // 8) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = hd.width // (2 ^ mip), hd.height // (2 ^ mip) + if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 1, 1) == "{" + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local w2, h2 = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) + local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + local colors: { { number } } + if palette then + colors = Pixels.colorList(palette) + elseif goldsrc then + colors = Quantize.palette(img.pixels, w, h, 256) + else + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local levels: { buffer } = {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil }) + if keyed then + for k = 0, lw * lh - 1 do + if readu8(px, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + levels[m + 1] = idx + end + local total = 40 + for _, l in levels do + total += buffer.len(l) + end + local palAt = total + if goldsrc then + total += 2 + 768 + 2 + end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in levels do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o += buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) + if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out: { Lump } = {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps: { Lump }, name: string): Lump? + local want = string.lower(name) + local best: Lump? = nil + for _, l in lumps do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +return Miptex +end __FILES["codecs/image/Pixels"] = @native function() --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -99942,6 +100208,61 @@ end return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +@native function Pixels.grey(): buffer + local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and +-- '{' textures) +@native function Pixels.keyed(pal: buffer, index: number): buffer + local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu32(out, index * 4, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +@native function Pixels.colorList(pal: buffer, n: number?): { { number } } + local out: { { number } } = {} + for i = 0, math.clamp(n or 256, 0, buffer.len(pal) // 4) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +@native function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? + local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +@native function Pixels.paletteBytes(pal: buffer, n: number?): buffer + local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels end __FILES["codecs/image/Quantize"] = @native function() @@ -101628,9 +101949,798 @@ end --!optimize 2 --!nocheck -- rosetta chunk codecs_model (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 18 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- 21 modules (5 native: @native); the Rosetta root requires it when one of them is first included. -- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). return function(__FILES, __include) +__FILES["codecs/model/Brush"] = @native function() + + + +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = __include("Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) +type Face = { + plane: Plane, + texture: string?, + vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) + bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths + [string]: any, +} +type Polygon = { + brush: number, + face: number, + points: { number }, -- x, y, z per corner, counter-clockwise seen from the front + normal: { number }, +} +type Options = { + epsilon: number?, -- plane side tolerance, default 1e-3 + size: number?, -- half size of the starting winding, default 2^17 + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + hull: boolean?, -- drop face parts inside / touching other brushes, default false + maxPolygons: number?, -- default 2^20 +} +type Built = { texture: string, primitive: Types.Primitive } + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +@native local function snap(x: number): number + local r = floor(x + 0.5) + return if abs(x - r) < 1e-6 then r else x +end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +@native function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +@native function Brush.baseAxis(n: { number }): number + local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +@native function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } + local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 + local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 3 + for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +@native function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } + local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +@native function Brush.axisBase(normal: { number }): ({ number }, { number }) + local nx, ny, nz = normal[1], normal[2], normal[3] + nx = if abs(nx) < 1e-6 then 0 else nx + ny = if abs(ny) < 1e-6 then 0 else ny + nz = if abs(nz) < 1e-6 then 0 else nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +@native function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +@native function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +@native function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) + local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +@native function Brush.baseWinding(p: Plane, size: number): { number } + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +@native function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) + local n = #pts // 3 + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = table.create(n, 0) :: { number } + local side = table.create(n, 0) :: { number } + local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front += 1 + elseif v < -eps then + side[i + 1] = -1 + back += 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f: { number }, b: { number } = {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +@native local function clean(pts: { number }, eps: number): { number }? + local out: { number } = {} + local n = #pts // 3 + for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = #out // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return if #out >= 9 then out else nil +end + +@native local function samePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +@native local function oppositePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +@native function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } + local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out: { { number }? } = {} + for i, p in planes do + local w: { number }? = Brush.baseWinding(p, size) + for j, q in planes do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = if on then nil else back + end + end + end + out[i] = if w then clean(w, eps) else nil + end + return out +end + +@native local function bounds(polys: { Polygon }): { number } + local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in polys do + local pts = p.points + for k = 0, #pts // 3 - 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +@native local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } + local kept: { { number } } = {} + local inside: { number }? = pts + for _, q in planes do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +@native local function faceKey(f: Face): string + local parts = { f.texture or "" } + for _, m in { f.vecs, f.bp } do + if m then + for _, row in m do + for _, v in row do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +@native local function convex(pts: { number }, n: { number }, eps: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +@native local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? + local n1, n2 = #f1 // 3, #f2 // 3 + for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out: { number } = {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +@native local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } + local groups: { [string]: { Polygon } } = {} + local order: { string } = {} + for _, p in polys do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out: { Polygon } = {} + for _, key in order do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in g do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +@native function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) + local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per: { { Polygon } } = {} + local planesOf: { { Plane } } = {} + local count = 0 + for bi, faces in brushes do + local planes: { Plane } = {} + for fi, f in faces do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list: { Polygon } = {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count += #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all: { Polygon } = {} + if opts and opts.hull then + local boxes: { { number } } = {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in per[bi] do + local frags: { { number } } = { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags: { { number } } = {} + for _, fr in frags do + for _, kept in outside(fr, own, bi, bj, planesOf[bj], eps) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in frags do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in per[bi] do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +@native function Brush.area(pts: { number }): number + local n = #pts // 3 + local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax += uy * vz - uz * vy + ay += uz * vx - ux * vz + az += ux * vy - uy * vx + end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +@native function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } + type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + local byTex: { [string]: Acc } = {} + local order: { Acc } = {} + local sizes: { [string]: { number } } = {} + for _, p in polys do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a: Acc = acc + local pts = p.points + local n = #pts // 3 + local base = #a.pos // 3 + for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out: { Built } = {} + for _, a in order do + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" :: "triangles", + }, + }) + end + return out +end + +return Brush +end +__FILES["codecs/model/Displacement"] = function() + +-- codecs/model/Displacement: Source engine displacement surfaces (VBSP ddispinfo_t / Hammer dispinfo), as +-- CCoreDispInfo::GenerateDispSurf of the Source SDK 2013 (no code taken): corner 0 is the base face corner nearest the +-- start position, rows run along corner 0 -> 1, columns along 0 -> 3 (the face's own, clockwise, winding), each vertex +-- moved by its offset; the 2^power quads split along alternating diagonals. Normals come from the grid. +local Types = __include("Types") + +local Displacement = {} + +local sqrt = math.sqrt + +type Surface = { + n: number, -- vertices per row: 2^power + 1 + flat: { number }, -- x, y, z on the base face (texture coordinates are projected from these) + pos: { number }, -- x, y, z displaced + nrm: { number }, -- unit normals on the face normal's side + idx: { number }, -- 0-based triangles, counter-clockwise seen from the face normal's side +} + +local function cross(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number, number) + return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx +end + +-- corners: the 4 face corners (12 numbers) in the face's clockwise winding; offsets: n * n * 3 numbers (row major, +-- row = i along corner 0 -> 1) added to the flat grid; normal: the face's outward normal +function Displacement.surface(corners: { number }, start: { number }, power: number, offsets: { number }, normal: { number }): (Surface?, string?) + if #corners ~= 12 then + return nil, "a displacement needs a 4-sided face" + end + if power < 1 or power > 4 or power % 1 ~= 0 then + return nil, "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + if #offsets < n * n * 3 then + return nil, "displacement offsets truncated" + end + local best, bestD = 0, math.huge + for k = 0, 3 do + local dx, dy, dz = corners[k * 3 + 1] - start[1], corners[k * 3 + 2] - start[2], corners[k * 3 + 3] - start[3] + local d = dx * dx + dy * dy + dz * dz + if d < bestD then + best, bestD = k, d + end + end + local c: { number } = table.create(12) :: any + for k = 0, 3 do + local s = ((best + k) % 4) * 3 + c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = corners[s + 1], corners[s + 2], corners[s + 3] + end + local flat: { number } = table.create(n * n * 3) :: any + local pos: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local t = i / (n - 1) + local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t + local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t + for j = 0, n - 1 do + local s = j / (n - 1) + local k = (i * n + j) * 3 + local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s + flat[k + 1], flat[k + 2], flat[k + 3] = x, y, z + pos[k + 1], pos[k + 2], pos[k + 3] = x + offsets[k + 1], y + offsets[k + 2], z + offsets[k + 3] + end + end + local nx, ny, nz = normal[1], normal[2], normal[3] + local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3]) + local sign = if ux * nx + uy * ny + uz * nz >= 0 then 1 else -1 + local nrm: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1) + for j = 0, n - 1 do + local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1) + local a, b = (i1 * n + j) * 3, (i0 * n + j) * 3 + local e, f = (i * n + j1) * 3, (i * n + j0) * 3 + local x, y, z = cross(pos[a + 1] - pos[b + 1], pos[a + 2] - pos[b + 2], pos[a + 3] - pos[b + 3], pos[e + 1] - pos[f + 1], pos[e + 2] - pos[f + 2], pos[e + 3] - pos[f + 3]) + local l = sqrt(x * x + y * y + z * z) + local k = (i * n + j) * 3 + if l < 1e-12 then + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + else + nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l + end + end + end + -- triangle (i, j), (i + 1, j), (i, j + 1) turns about rows x columns: flipped when that faces away + local idx: { number } = table.create((n - 1) * (n - 1) * 6) :: any + local flip = sign < 0 + for i = 0, n - 2 do + for j = 0, n - 2 do + local a = i * n + j + local b, cc, d = a + n, a + n + 1, a + 1 + local t1, t2, t3, t4, t5, t6 + if (i + j) % 2 == 0 then + t1, t2, t3, t4, t5, t6 = a, b, d, b, cc, d + else + t1, t2, t3, t4, t5, t6 = a, b, cc, a, cc, d + end + if flip then + t2, t3, t5, t6 = t3, t2, t6, t5 + end + local q = #idx + idx[q + 1], idx[q + 2], idx[q + 3], idx[q + 4], idx[q + 5], idx[q + 6] = t1, t2, t3, t4, t5, t6 + end + end + return { n = n, flat = flat, pos = pos, nrm = nrm, idx = idx }, nil +end + +type Arrays = { + pos: { number }, + nrm: { number }, + uv: { number }, + idx: { number }, -- 0-based + blend: { number }?, -- per vertex 0..1: the _BLEND attribute (displacement alpha) +} + +-- flat arrays -> an indexed triangle primitive (POSITION, NORMAL, TEXCOORD_0, _BLEND) +function Displacement.primitive(a: Arrays): Types.Primitive + local writef32, writeu32 = buffer.writef32, buffer.writeu32 + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + local attrs: { [string]: Types.Accessor } = { + POSITION = S.accessor(pb, "f32", 3, nv), + NORMAL = S.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = S.accessor(ub, "f32", 2, nv), + } + local blend = a.blend + if blend then + local bb = buffer.create(nv * 4) + for k = 1, nv do + writef32(bb, (k - 1) * 4, blend[k] or 0) + end + attrs._BLEND = S.accessor(bb, "f32", 1, nv) + end + return { attributes = attrs, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" } +end + +return Displacement +end __FILES["codecs/model/Mat4"] = function() -- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. @@ -103362,6 +104472,130 @@ end return Packed end +__FILES["codecs/model/Patch"] = @native function() + + + +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +@native function Patch.valid(w: number, h: number, n: number): boolean + return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +@native function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) + local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = (w - 1) // 2, (h - 1) // 2 + local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = table.create(gw * gh * comps, 0) :: { number } + for gy = 0, gh - 1 do + local sy = math.min(gy // lv, py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(gx // lu, px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 + local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) + local c = row + i * comps + for k = 1, comps do + out[o + k] += ctrl[c + k] * wgt + end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +@native function Patch.triangles(gw: number, gh: number): { number } + local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } + for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +@native function Patch.normalize(pts: { number }, comps: number, at: number) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +@native function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } + local out = table.create(gw * gh * 3, 0) :: { number } + @native local function at(x: number, y: number, k: number): number + return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, i // gw + for _, d in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } } do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch +end __FILES["codecs/model/Polygon"] = function() -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. @@ -109101,7 +110335,7 @@ local KeyValues = {} type Pair = Binary.Pair type Block = Binary.Block type ParseOptions = { - escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true + escapes: (boolean | "quotes")?, -- \n \t \\ \" ... in quoted strings, default true; "quotes": only \" -- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the -- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with -- its cond @@ -109110,8 +110344,11 @@ type ParseOptions = { maxDepth: number?, -- default 256 } type WriteOptions = { - escapes: boolean?, -- default true + escapes: (boolean | "quotes")?, -- default true; "quotes": only " is escaped indent: string?, -- default "\t" + separator: string?, -- between a key and its value, default "\t" (Hammer: " ") + bareBlocks: boolean?, -- block names unquoted when they are plain words (Hammer), default false + flatBlocks: { [string]: boolean }?, -- blocks whose pairs keep the block's own indent (Hammer's dispinfo rows) } type ObjectOptions = { duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array @@ -109121,7 +110358,7 @@ local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true } local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' } -type Lexer = { s: string, i: number, n: number, escapes: boolean } +type Lexer = { s: string, i: number, n: number, escapes: boolean, quotesOnly: boolean?, quoted: boolean? } -- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string local function token(lx: Lexer): (string?, string?, number, string?) @@ -109150,6 +110387,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) lx.i = i + 1 return c, nil, i - 1, nil elseif c == '"' then + lx.quoted = true local start = i i += 1 if not lx.escapes then @@ -109174,7 +110412,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "s", table.concat(parts), start - 1, nil end local x = string.sub(s, e + 1, e + 1) - local r = ESCAPE[x] + local r = if lx.quotesOnly and x ~= '"' then nil else ESCAPE[x] if r then table.insert(parts, r) i = e + 2 @@ -109191,6 +110429,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "[", string.sub(s, i + 1, e - 1), i - 1, nil end end + lx.quoted = false local e = string.find(s, '[ \t\r\n\f\v"{}]', i) local stop = if e then e - 1 else n lx.i = stop + 1 @@ -109235,7 +110474,7 @@ end local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?) local o: ParseOptions = opts or {} - local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false } + local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false, quotesOnly = o.escapes == "quotes" } if string.sub(text, 1, 3) == "\239\187\191" then lx.i = 4 end @@ -109275,6 +110514,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at) else local key = v :: string + local keyQuoted = lx.quoted local k2, v2, at2, terr2 = token(lx) if terr2 then return nil, Err.new(Err.TRUNCATED, terr2, at2) @@ -109298,7 +110538,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl if not pass then skipping += 1 else - local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond } + local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond, bare = not keyQuoted } local last = cur[#cur] if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then cur[#cur] = pair @@ -109401,7 +110641,7 @@ function KeyValues.copy(b: Block): Block local out: Block = table.create(#b) :: any for i, p in b do local v: any = p.value - out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type } + out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type, bare = p.bare } end return out end @@ -109444,18 +110684,23 @@ function KeyValues.all(b: Block, key: string): { Pair } return out end -local function quote(s: string, escapes: boolean): string - if escapes then +local function quote(s: string, escapes: boolean | string): string + if escapes == "quotes" then + s = string.gsub(s, '"', '\\"') + elseif escapes then s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) end return '"' .. s .. '"' end -local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string? - if depth > 256 then +type WriteState = { indent: string, escapes: boolean | string, sep: string, bare: boolean, flat: { [string]: boolean } } + +local function writeBlock(b: Block, out: { string }, w: WriteState, level: number, depth: number?): string? + local dp = depth or 0 + if dp > 256 then return "nesting deeper than 256" end - local pad = string.rep(indent, level) + local pad = string.rep(w.indent, level) for _, p in b do if type(p) ~= "table" or type(p.key) ~= "string" then return "a pair needs a string key" @@ -109463,15 +110708,16 @@ local function writeBlock(b: Block, out: { string }, indent: string, level: numb local v: any = p.value local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else "" if type(v) == "table" then - table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n") - local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1) + local name = if w.bare and (p.bare or (p.bare == nil and string.match(p.key, "^[%w_]+$"))) then p.key else quote(p.key, w.escapes) + table.insert(out, pad .. name .. cond .. "\n" .. pad .. "{\n") + local err = writeBlock(v, out, w, if w.flat[p.key] then level else level + 1, dp + 1) if err then return err end table.insert(out, pad .. "}\n") elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v) - table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n") + table.insert(out, pad .. quote(p.key, w.escapes) .. w.sep .. quote(s, w.escapes) .. cond .. "\n") else return "unwritable value for key " .. p.key end @@ -109484,7 +110730,8 @@ function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?) return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list") end local out: { string } = {} - local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0) + local o: WriteOptions = opts or {} + local err = writeBlock(b, out, { indent = o.indent or "\t", escapes = if o.escapes == nil then true else o.escapes, sep = o.separator or "\t", bare = o.bareBlocks == true, flat = o.flatBlocks or {} }, 0) if err then return nil, Err.new(Err.ARG, err) end @@ -109658,6 +110905,7 @@ type Pair = { key: string, value: any, -- string | number | Block cond: string?, -- text: the [$CONDITION] kept when not evaluated + bare: boolean?, -- text: a block whose name was unquoted (written back so with bareBlocks) type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block) } type Block = { Pair } @@ -148570,7 +149818,7 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, } @@ -148702,6 +149950,7 @@ __FILES["model/bsp/Brush"] = function() -- size. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") local Brush = {} @@ -148734,34 +149983,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil + if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil - end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -148976,8 +150209,10 @@ end __FILES["model/bsp/Quake3"] = function() -- 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. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = __include("Types") +local Patch = __include("codecs/model/Patch") local Quake3 = {} @@ -149057,52 +150292,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: counts[if kind == 1 then "polygons" else "meshes"] += 1 elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches += 1 - local L = level - for py = 0, (h - 1) // 2 - 1 do - for px = 0, (w - 1) // 2 - 1 do - local ctrl: { { number } } = {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid: { number } = {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k] += cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - 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] - -- Quake's control grids are clockwise-front - for _, v in { a, d, c2, c2, d, e } do - table.insert(tris, v) - end - end - end - end + local ctrl = table.create(n * 14, 0) :: { number } + for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = table.create(gw * gh) :: { number } + for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number }) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(tris, ids[v + 1]) end else counts.skipped += 1 @@ -159988,7 +161194,7 @@ end --!optimize 2 --!nocheck -- rosetta chunk model_3 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 24 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- 25 modules (1 native: @native); the Rosetta root requires it when one of them is first included. -- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). return function(__FILES, __include) __FILES["model/lwo/Parse"] = function() @@ -160534,6 +161740,1097 @@ end return Parse end +__FILES["model/map"] = function() + +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Miptex = __include("codecs/image/Miptex") +local Brush = __include("codecs/model/Brush") +local Parse = __include("model/map/Parse") +local Write = __include("model/map/Write") +local Build = __include("model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + epsilon: number?, -- default 1e-3 + patchLevel: number?, -- patchDef2 segments per sub-patch, default 4 + skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...) + textureSizes: { [string]: { number } }?, -- name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes + maxBrushes: number?, -- default 2^20 + maxPolygons: number?, -- default 2^20 +} +type EncodeOptions = { + variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Map.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c :: number) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return if game and string.match(s, "^%s*{") then 0.6 else 0 + end + return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m: Parse.Map): string + local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in m.entities do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in e.brushes do + if b.type ~= "brush" then + q3 = true + end + for _, f in b.faces or {} do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return if q2 then "quake2" else "quake" +end + +local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil + local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } } + local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in string.gmatch(spec, "[^;]+") do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w: number, h: number = 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] :: number, given[2] :: number + elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads :: any), 1, -1 do + local wd = (wads :: any)[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in { ".tga", ".jpg", ".png" } do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage :: any, b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw: number, fh: number = w :: number, h :: number + local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, if known then 1 else 0 } + return fw, fh, known + end +end + +function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f: Parse.Face): Parse.Face + if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x: number): string + return Write.num(x) +end + +function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents: { any } = {} + for _, node in scene.nodes do + local ex: any = node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {} + if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv: { Parse.Brush } = {} + for _, b in brushes do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in b.faces do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src: any = scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents :: { Parse.Entity }, + game = if fromMap then src.game else nil, + mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil, + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?) + local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil + if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m: Parse.Map): (string?, Err.Err?) + if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f: Parse.Face): Brush.Face? + return Build.face(f) +end + +return Map +end +__FILES["model/map/Build"] = function() + +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = __include("Types") +local Brush = __include("codecs/model/Brush") +local Patch = __include("codecs/model/Patch") +local Parse = __include("model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { + variant: string, -- "quake" | "valve220" | "quake2" | "quake3" + size: (name: string) -> (number, number, boolean), -- width, height, known + hull: boolean?, + merge: boolean?, + epsilon: number?, + patchLevel: number?, + skip: { string }?, + maxPolygons: number?, +} + +function Build.face(f: Parse.Face): Brush.Face? + local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out: Brush.Face = { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + +local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean + local size, pts = b.size :: { number }, b.points :: { number } + local w: number, h: number = size[1] :: number, size[2] :: number + if not Patch.valid(w, h, #pts // 5) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = table.create(w * h * 5, 0) :: { number } + for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params: { number } = b.params or {} + local explicit = b.type == "patchDef3" + local lu: number = if explicit then math.max(1, params[1] or 1) else level + local lv: number = if explicit then math.max(1, params[2] or 1) else level + local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = #acc.pos // 3 + for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a: Acc): Types.Primitive + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s: string?): { number }? + if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?) + local scene = Scene.new() + scene.meta.up = "z" + local skip: { [string]: boolean } = {} + for _, n in o.skip or {} do + skip[string.lower(n)] = true + end + local matOf: { [string]: number } = {} + local function material(name: string): number + local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities: { { [string]: string } } = {} + local polyTotal = 0 + for ei, ent in map.entities do + local keys = ent.keys + table.insert(entities, keys) + local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes: { { Brush.Face } } = {} + local patchAcc: { [string]: Acc } = {} + local patchOrder: { string } = {} + for _, b in ent.brushes do + if b.faces then + counts.brushes += 1 + local faces: { Brush.Face } = {} + for _, f in b.faces do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces += 1 + end + end + table.insert(brushes, faces) + else + counts.patches += 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then + skipped.patches += 1 + end + end + end + end + local prims: { Types.Primitive } = {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal += #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept: { Brush.Polygon } = {} + for _, p in polys do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name: string): (number, number) + local m = scene.materials[material(name)] + local e = (m.extras :: any).map + return e.width, e.height + end) + for _, bt in built do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in patchOrder do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build +end +__FILES["model/map/Parse"] = function() + +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = __include("Types") + +local Parse = {} + +type Face = { + points: { number }, -- 3 points: x, y, z each + texture: string, + offset: { number }?, -- Quake standard: x, y offset + rotation: number?, -- standard / Valve 220 (degrees) + scale: { number }?, -- standard / Valve 220 + u: { number }?, -- Valve 220: axis x, y, z, offset + v: { number }?, + matrix: { { number } }?, -- Quake III brush primitives: 2 x 3 + flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light) +} +type Brush = { + type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3" + faces: { Face }?, + texture: string?, -- patches + size: { number }?, -- patches: width, height (columns, points per column as written) + params: { number }?, -- patches: the header numbers after width, height + points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column) +} +type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object) +type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } } + +type St = { s: string, pos: number, n: number, comments: { string } } + +local function skip(st: St) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st: St): string + skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st: St, c: string): string? + if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos += 1 + return nil +end + +local function word(st: St): string? + skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b :: number) + 1 + return string.sub(st.s, a, b) +end + +local function number(st: St): number? + skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b :: number) + 1 + end + return v +end + +local function quoted(st: St): string? + if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st: St, n: number, out: { number }): string? + for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?) + local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st: St): { number }? + local out: { number } = {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return if #out > 0 then out else nil +end + +local function plane(st: St): ({ number }?, string?) + local pts: { number } = {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st: St, bp: boolean): (Face?, string?) + local pts, e = plane(st) + if not pts then + return nil, e + end + local f: Face = { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?) + local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = if kind == "patchDef3" then 7 else 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts: { number } = {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st: St, maxPoints: number): (Brush?, string?) + local c = peek(st) + if c == "(" then + local faces: { Face } = {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos += 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out: any, err: string? + if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces: { Face } = {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?) + local st: St = { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents: { Entity } = {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys: { [string]: string } = {} + local order: { string } = {} + local brushes: { Brush } = {} + while true do + local c = peek(st) + if c == "}" then + st.pos += 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos += 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count += 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes }) + end + local game, fmt + for _, c in st.comments do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse +end +__FILES["model/map/Write"] = function() + +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = __include("Types") +local Parse = __include("model/map/Parse") + +local Write = {} + +function Write.num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t: { number }, a: number, b: number): string + local out = table.create(b - a + 1) :: { string } + for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f: Parse.Face, bp: boolean): (string?, string?) + local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b: Parse.Brush, out: { string }): string? + local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = if b.type == "patchDef3" then 5 else 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map: Parse.Map): (string?, string?) + local out: { string } = {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in map.entities do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in Types.keys(ent.keys) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in ent.brushes or {} do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in b.faces or {} do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end __FILES["model/mca"] = function() -- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, @@ -166773,6 +169070,19 @@ end return Build end +end + + + + + + model_4 + --!optimize 2 +--!nocheck +-- rosetta chunk model_4 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 26 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/pmx/Pmd"] = function() -- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are @@ -167905,19 +170215,6 @@ end return Qb end -end - - - - - - model_4 - --!optimize 2 ---!nocheck --- rosetta chunk model_4 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 24 modules (3 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/rbxm"] = function() -- model/rbxm: Roblox binary model / place (.rbxm / .rbxl, "<roblox!") to and from a codecs/model/Rbx RbxTree, from the @@ -174413,6 +176710,19 @@ end return Usda end +end + + + + + + model_5 + --!optimize 2 +--!nocheck +-- rosetta chunk model_5 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 15 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/usda/Build"] = function() -- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other @@ -175691,19 +178001,6 @@ end return Build end -end - - - - - - model_5 - --!optimize 2 ---!nocheck --- rosetta chunk model_5 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 9 modules (1 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/usda/Parse"] = function() -- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads @@ -177319,6 +179616,1517 @@ end return Write end +__FILES["model/vbsp"] = function() + +-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read, +-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and +-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by +-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a +-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360 +-- (big-endian) and Titanfall / Apex rBSP, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local KeyValues = __include("codecs/text/KeyValues") +local Mat4 = __include("codecs/model/Mat4") +local Zip = __include("containers/Zip") +local Archive = __include("containers/Archive") +local Faces = __include("model/vbsp/Faces") +local Props = __include("model/vbsp/Props") + +-- ------------------------------------------------------------------------------------------------ contract +local Vbsp = { + name = "vbsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + tools: boolean?, -- keep nodraw / skip / hint / sky faces, default false + pak: boolean?, -- meta.pak and textures from it, default true + maxBytes: number?, -- per decompressed lump, default 2^28 + maxVertices: number?, -- default 2^24 + maxProps: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ constants +local L = { + ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13, + MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43, + TEXDATA_STRING_TABLE = 44, FACES_HDR = 58, +} +local HEADER = 8 + 64 * 16 + 4 +local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vbsp.sniff(r: Bytes.Reader): number + if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return if v >= 19 and v <= 21 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Lump = Faces.Lump + +local function angles(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +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] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end + +local function vec3(s: any): { number }? + if type(s) ~= "string" then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream +local function unlzma(b: buffer, at: number, size: number, maxBytes: number): (buffer?, string?) + if size < 17 then + return nil, "truncated LZMA lump header" + end + local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8) + if actual > maxBytes then + return nil, "limit: LZMA lump of " .. actual .. " bytes" + end + if packed > size - 17 then + return nil, "LZMA lump runs past the end" + end + local props = buffer.create(5) + buffer.copy(props, 0, b, at + 12, 5) + local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes }) + if not out then + return nil, "LZMA lump: " .. tostring(if type(err) == "table" then err.message else err) + end + return out, nil +end + +local function isLzma(b: buffer, at: number, size: number): boolean + return size >= 17 and buffer.readstring(b, at, 4) == "LZMA" +end + +local function pakArchive(src: buffer, maxBytes: number): (any, Err.Err?) + local zc, err = Zip.open(src) + if not zc then + return nil, err + end + local a = Archive.new("zip") + for _, e in zc:list() do + local entry: any = { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = if e.method == 0 then "stored" elseif e.method == 8 then "deflate" elseif e.method == 14 then "lzma" else tostring(e.method), + mtime = e.mtime, + dir = e.isDir, + } + entry.load = function(): (buffer?, Err.Err?) + if e.method ~= 14 then + return zc:read(e) + end + -- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks) + local zb = zc.buf + for _, s in Zip._starts(zb, e) do + if s + 9 <= buffer.len(zb) then + local psize = buffer.readu16(zb, s + 2) + local start = s + 4 + psize + local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start) + if psize >= 5 and n > 0 and e.size <= maxBytes then + local props = buffer.create(5) + buffer.copy(props, 0, zb, s + 4, 5) + local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes }) + if out then + return out, nil + end + end + end + end + return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry") + end + Archive.put(a, entry) + end + a.meta.source = { format = "zip", lump = "pakfile" } + return a, nil +end + +local function light(scene: Types.Scene, e: any, class: string): (number?, { number }?) + local l = vec3(e._light) + local rgb: { number } = { 1, 1, 1 } + local intensity = 1 + if l then + rgb = { l[1] / 255, l[2] / 255, l[3] / 255 } + local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)") + intensity = (m and tonumber(m)) or 200 + end + local lt: Types.Light = nil :: any + if class == "light" then + lt = { name = nil :: string?, type = "point", color = rgb, intensity = intensity } + elseif class == "light_spot" then + local outer = tonumber(e._cone) or 45 + local inner = tonumber(e._inner_cone) or math.min(30, outer) + lt = { name = nil :: string?, type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) } + else + lt = { name = nil :: string?, type = "directional", color = rgb, intensity = intensity } + end + lt.name = if type(e.targetname) == "string" then e.targetname else class + table.insert(scene.lights, lt :: any) + local ang = vec3(e.angles) or { 0, 0, 0 } + if type(e.pitch) == "string" and tonumber(e.pitch) then + ang[1] = -(tonumber(e.pitch) :: number) -- the FGD's angle_negative_pitch + end + -- the light shines along the entity's forward (+x); a glTF light along -z + return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90)) +end + +function Vbsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base = r.buf, r.base + local size = r.limit - r.base + if size < HEADER then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VBSP" then + return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0) + end + local version = buffer.readi32(b, base + 4) + if version < 19 or version > 21 then + return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4) + end + local maxBytes = o.maxBytes or 2 ^ 28 + -- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036 + local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER + local dir: { { at: number, size: number, version: number, fourcc: number } } = {} + for i = 0, 63 do + local p = base + 8 + i * 16 + local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12) + local at, n, v = a, c, d + if l4d2 then + v, at, n = a, c, d + end + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base) + end + dir[i] = { at = at, size = n, version = v, fourcc = f } + end + local cache: { [number]: Lump } = {} + local compressed = false + local function lump(i: number): (Lump?, string?) + local c = cache[i] + if c then + return c, nil + end + local d = dir[i] + local out: Lump + if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then + local u, err = unlzma(b, base + d.at, d.size, maxBytes) + if not u then + return nil, "lump " .. i .. ": " .. tostring(err) + end + compressed = true + out = { buf = u, at = 0, size = buffer.len(u) } + else + out = { buf = b, at = base + d.at, size = d.size } + end + cache[i] = out + return out, nil + end + local need: { [string]: Lump } = {} + for name, idx in { planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES } :: { [string]: number } do + local lp, err = lump(idx) + if not lp then + return nil, Err.from(err) + end + need[name] = lp + end + if need.faces.size == 0 then + local hdr, err = lump(L.FACES_HDR) + if not hdr then + return nil, Err.from(err) + end + need.faces = hdr + end + local groups, ferr, skipped = Faces.build({ + planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges, + faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models, + dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true, + maxVertices = o.maxVertices or 2 ^ 24, + }) + if not groups then + return nil, Err.from(ferr, skipped and skipped - base) + end + + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + + local pak: any = nil + local pd = dir[L.PAKFILE] + if o.pak ~= false and pd.size > 0 then + local src = buffer.create(pd.size) + buffer.copy(src, 0, b, base + pd.at, pd.size) + pak = pakArchive(src, maxBytes) + scene.meta.pak = pak + end + + -- texdata -> material + texture (materials/<name>.vtf, from the pak when it is there) + local TD, ST, SS = need.texdata, need.table, need.strings + local nTD = TD.size // 32 + local matOf: { [number]: number } = {} + local function material(td: number): number? + if td < 0 or td >= nTD then + return nil + end + local m = matOf[td] + if m then + return m + end + local to = TD.at + td * 32 + local si = buffer.readi32(TD.buf, to + 12) + local name = "texdata" .. td + if si >= 0 and (si + 1) * 4 <= ST.size then + local off = buffer.readi32(ST.buf, ST.at + si * 4) + if off >= 0 and off < SS.size then + name = string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") :: string + end + end + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + local tex: Types.Texture = { name = name, uri = path .. ".vtf" } + if pak then + local zc = pak :: any + local ok, data = pcall(zc.read, zc, path .. ".vtf") + if ok and type(data) == "buffer" then + tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil + end + end + table.insert(scene.textures, tex) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { + vbsp = { + vmt = path .. ".vmt", + width = buffer.readi32(TD.buf, to + 16), + height = buffer.readi32(TD.buf, to + 20), + reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) }, + }, + } + table.insert(scene.materials, mat) + matOf[td] = #scene.materials + return #scene.materials + end + + local root: Types.Node = { name = "vbsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelNode: { [number]: number } = {} + for _, g in groups do + local node = modelNode[g.model] + if not node then + local name = if g.model == 0 then "world" else "*" .. g.model + table.insert(scene.meshes, { name = name, primitives = {} }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } }) + node = #scene.nodes + modelNode[g.model] = node + table.insert(root.children, node) + end + local mesh = scene.meshes[scene.nodes[node].mesh :: number] + table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata))) + end + + -- entities + local E = need.entities + local text = string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") :: string + local blocks, eerr = KeyValues.entities(text) + if not blocks then + return nil, Err.new((eerr :: Err.Err).code, "entity lump: " .. (eerr :: Err.Err).message, dir[L.ENTITIES].at) + end + local ents: { any } = table.create(#blocks) + for i, blk in blocks do + local e = KeyValues.toObject(blk) + ents[i] = e + local class = if type(e.classname) == "string" then e.classname else "" + local mdl = if type(e.model) == "string" then string.match(e.model, "^%*(%d+)$") else nil + local mi = mdl and tonumber(mdl) + if mi and mi > 0 and modelNode[mi] then + local node = scene.nodes[modelNode[mi]] + node.name = if type(e.targetname) == "string" then e.targetname else class + local org = vec3(e.origin) + if org then + node.translation = org + end + local ang = vec3(e.angles) + if ang then + node.rotation = angles(ang[1], ang[2], ang[3]) + end + local x: any = node.extras + x.vbsp.entity = i + elseif class == "light" or class == "light_spot" or class == "light_environment" then + local li, rot = light(scene, e, class) + table.insert(scene.nodes, { name = scene.lights[li :: number].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.entities = ents + + -- game lumps + local spVersion: number? = nil + local G = dir[L.GAME_LUMP] + if G.size >= 4 then + local ga = base + G.at + local count = buffer.readi32(b, ga) + if count < 0 or 4 + count * 16 > G.size then + return nil, Err.new(Err.CORRUPT, "game lump directory", G.at) + end + for k = 0, count - 1 do + local eo = ga + 4 + k * 16 + local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6) + local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12) + if id == SPRP then + if off < 0 or len < 0 or off > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local pb, pat, plen = b, base + off, len + if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then + if off + 17 > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local u, err = unlzma(b, base + off, size - off, maxBytes) + if not u then + return nil, Err.from(err, off) + end + pb, pat, plen = u, 0, buffer.len(u) + compressed = true + elseif off + len > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local props, perr = Props.read(pb, pat, plen :: number, ver, o.maxProps or 2 ^ 20) + if not props then + return nil, Err.from(perr, off) + end + spVersion = ver + for pi, p in props do + local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model + table.insert(scene.nodes, { + name = nm, + children = {}, + translation = p.origin, + rotation = angles(p.angles[1], p.angles[2], p.angles[3]), + scale = if p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 then p.scale else nil, + extras = { + model = p.model, + vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin }, + }, + }) + table.insert(root.children, #scene.nodes) + end + end + end + end + + scene.meta.skippedFaces = skipped + scene.meta.source = { + format = "vbsp", + version = version, + variant = if l4d2 then "l4d2" else "v" .. version, + mapRevision = buffer.readi32(b, base + HEADER - 4), + compressed = compressed, + staticPropVersion = spVersion, + entities = text, + } + return scene, nil +end + +return Vbsp +end +__FILES["model/vbsp/Faces"] = function() + +-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013 +-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert); displacements through codecs/model/Displacement. +local Types = __include("Types") +local Displacement = __include("codecs/model/Displacement") + +local Faces = {} + +local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8 + +type Lump = { buf: buffer, at: number, size: number } +type Input = { + planes: Lump, + vertices: Lump, + edges: Lump, + surfedges: Lump, + faces: Lump, + texinfo: Lump, + texdata: Lump, + models: Lump, + dispinfo: Lump, + dispverts: Lump, + tools: boolean, -- keep nodraw / skip / hint / sky faces + maxVertices: number, +} +type Group = { model: number, texdata: number, pos: { number }, nrm: { number }, uv: { number }, blend: { number }?, idx: { number } } + +-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP +local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200 + +local function emit(g: Group, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number + local pos, nrm, uv = g.pos, g.nrm, g.uv + local k = #pos + pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + local q = #uv + uv[q + 1], uv[q + 2] = u, v + return k // 3 +end + +local function displacement(I: Input, g: Group, d: number, poly: { number }, nx: number, ny: number, nz: number, tex: { number }): string? + local di = I.dispinfo + if (d + 1) * 176 > di.size then + return "dispinfo index out of range" + end + local o = di.at + d * 176 + local b = di.buf + local vstart, power = readi32(b, o + 12), readi32(b, o + 20) + if #poly ~= 12 then + return nil -- not a quad: the base face is kept + end + if power < 1 or power > 4 then + return "displacement power " .. power + end + local n = 2 ^ power + 1 + local dv = I.dispverts + if vstart < 0 or (vstart + n * n) * 20 > dv.size then + return "displacement vertices out of range" + end + -- CDispVert: vector * dist, then alpha (0 .. 255) + local offsets: { number } = table.create(n * n * 3) :: any + for k = 0, n * n - 1 do + local vo = dv.at + (vstart + k) * 20 + local dist = readf32(dv.buf, vo + 12) + offsets[k * 3 + 1] = readf32(dv.buf, vo) * dist + offsets[k * 3 + 2] = readf32(dv.buf, vo + 4) * dist + offsets[k * 3 + 3] = readf32(dv.buf, vo + 8) * dist + end + local surf, err = Displacement.surface(poly, { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, power, offsets, { nx, ny, nz }) + if not surf then + return err + end + local base = #g.pos // 3 + local blend = g.blend or {} + g.blend = blend + local flat, pos, nrm = surf.flat, surf.pos, surf.nrm + for k = 0, n * n - 1 do + local x, y, z = flat[k * 3 + 1], flat[k * 3 + 2], flat[k * 3 + 3] + emit(g, pos[k * 3 + 1], pos[k * 3 + 2], pos[k * 3 + 3], nrm[k * 3 + 1], nrm[k * 3 + 2], nrm[k * 3 + 3], + (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9], (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10]) + blend[base + k + 1] = math.clamp(readf32(dv.buf, dv.at + (vstart + k) * 20 + 16) / 255, 0, 1) + end + local idx = g.idx + for _, v in surf.idx do + idx[#idx + 1] = base + v + end + return nil +end + +function Faces.build(I: Input): ({ Group }?, string?, number?) + local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, F.size // 56 + local nTI, nTD, nP = TI.size // 72, TD.size // 32, P.size // 20 + local faceModel: { [number]: number } = {} + local M = I.models + for m = 0, M.size // 48 - 1 do + local o = M.at + m * 48 + local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44) + if first >= 0 and count > 0 and first + count <= nF then + for f = first, first + count - 1 do + if faceModel[f] == nil then + faceModel[f] = m + end + end + end + end + local groups: { Group } = {} + local byKey: { [number]: Group } = {} + local skipped, verts = 0, 0 + local poly: { number } = {} + for f = 0, nF - 1 do + local fo = F.at + f * 56 + local fb = F.buf + local plane, side = readu16(fb, fo), readu8(fb, fo + 2) + local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8) + local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12) + local model = faceModel[f] or 0 + if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then + skipped += 1 + continue + end + local to = TI.at + ti * 72 + local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68) + if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then + continue + end + local w, h = 1, 1 + if td >= 0 and td < nTD then + w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1) + h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1) + else + td = -1 + end + table.clear(poly) + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local vi = readu16(E.buf, E.at + e * 4 + (if se >= 0 then 0 else 2)) + if vi >= nV then + ok = false + break + end + local vo = V.at + vi * 12 + poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8) + end + if not ok then + skipped += 1 + continue + end + local po = P.at + plane * 20 + local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + local key = model * 65536 + td + 1 + local grp: Group = byKey[key] + if not grp then + grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil :: { number }?, idx = {} } + byKey[key] = grp + table.insert(groups, grp) + end + local tex = { + readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12), + readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h, + } + local before = #grp.pos + local done = false + if disp >= 0 then + local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex) + if derr then + return nil, derr, fo + end + done = #grp.pos > before + end + if not done then + local n = numEdges + -- Newell's normal against the plane: the stored winding is clockwise from the front + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local a, b = k * 3, ((k + 1) % n) * 3 + ax += (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3]) + ay += (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1]) + az += (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2]) + end + local flip = ax * nx + ay * ny + az * nz < 0 + local first = -1 + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h) + if first < 0 then + first = id + end + end + local idx = grp.idx + for k = 1, n - 2 do + local b, c = first + k, first + k + 1 + if flip then + b, c = c, b + end + idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c + end + end + verts += (#grp.pos - before) // 3 + if verts > I.maxVertices then + return nil, "limit: over maxVertices", fo + end + end + return groups, nil, skipped +end + +function Faces.primitive(g: Group, material: number?): Types.Primitive + local prim = Displacement.primitive(g) + prim.material = material + return prim +end + +return Faces +end +__FILES["model/vbsp/Props"] = function() + +-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and +-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the +-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale +-- (v13: last 3 f32), u32 leaf indices (v12+). +local Props = {} + +local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32 + +type Prop = { + model: string, + origin: { number }, + angles: { number }, -- pitch, yaw, roll (degrees) + scale: { number }, + skin: number, + solid: number, + flags: number, + fadeMin: number, + fadeMax: number, + fadeScale: number?, + lightingOrigin: { number }, +} + +function Props.read(b: buffer, at: number, size: number, version: number, maxProps: number): ({ Prop }?, string?) + local e = at + size + local p = at + if p + 4 > e then + return {}, nil + end + local nd = readi32(b, p) + p += 4 + if nd < 0 or p + nd * 128 > e then + return nil, "static prop model names past the end" + end + local names: { string } = table.create(nd) :: any + for i = 0, nd - 1 do + names[i + 1] = string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") :: string + end + p += nd * 128 + if p + 4 > e then + return nil, "static prop leaves truncated" + end + local nl = readi32(b, p) + p += 4 + local leafSize = if version >= 12 then 4 else 2 + if nl < 0 or p + nl * leafSize + 4 > e then + return nil, "static prop leaves past the end" + end + p += nl * leafSize + local np = readi32(b, p) + p += 4 + if np < 0 or np > maxProps then + return nil, "limit: " .. np .. " static props" + end + local out: { Prop } = table.create(np) :: any + if np == 0 then + return out, nil + end + local rec = (e - p) // np + if rec < 56 then + return nil, "static prop records shorter than 56 bytes" + end + for i = 0, np - 1 do + local o = p + i * rec + local mi = readu16(b, o + 24) + local scale = { 1, 1, 1 } + if version == 13 and rec >= 88 then + scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) } + elseif (version == 11 or version == 12) and rec >= 80 then + local s = readf32(b, o + rec - 4) + scale = { s, s, s } + end + out[i + 1] = { + model = names[mi + 1] or "", + origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, + angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) }, + scale = scale, + solid = readu8(b, o + 30), + flags = readu8(b, o + 31), + skin = readi32(b, o + 32), + fadeMin = readf32(b, o + 36), + fadeMax = readf32(b, o + 40), + lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) }, + fadeScale = if version >= 5 and rec >= 60 then readf32(b, o + 56) else nil, + } + end + return out, nil +end + +return Props +end +__FILES["model/vmf"] = function() + +-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush +-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement, +-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in +-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from +-- opts.textureSizes, materials/<name>.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances +-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Build = __include("model/vmf/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Vmf = { + name = "vmf", + category = "model", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + tools: boolean?, -- keep tools/* materials (nodraw, clip, trigger, skybox, ...), default false + textureSizes: { [string]: { number } }?, -- material name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> any)?, + maxPolygons: number?, -- default 2^20 +} +type EncodeOptions = {} +type SideSpec = { + points: { { number } }, -- three points, clockwise seen from outside (Hammer) + material: string?, + uaxis: { number }?, -- x, y, z, shift, scale; default from the face's dominant axis + vaxis: { number }?, + rotation: number?, + lightmapscale: number?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Vmf.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then + return 0.9 + end + if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function sizer(opts: DecodeOptions?): (string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h, known = 512, 512, false + local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)]) + if given and type(given[1]) == "number" and type(given[2]) == "number" then + w, h, known = given[1], given[2], true + elseif opts and opts.decodeImage then + local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf") + if data then + local ok, img = pcall(opts.decodeImage :: any, data) + if ok and type(img) == "table" and type(img.width) == "number" then + w, h, known = img.width, img.height, true + end + end + end + cache[name] = { w, h, if known then 1 else 0 } + return w, h, known + end +end + +function Vmf.parse(src: buffer | string): (KeyValues.Block?, Err.Err?) + return KeyValues.parse(src, { escapes = "quotes", defines = false }) +end + +function Vmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, err + end + local scene, msg = Build.scene(doc, { + tools = opts ~= nil and opts.tools == true, + size = sizer(opts), + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(msg) + end + local vi = KeyValues.get(doc, "versioninfo") + local info: any = if type(vi) == "table" then KeyValues.toObject(vi) else {} + scene.meta.vmf = doc + scene.meta.source = { + format = "vmf", + editorVersion = tonumber(info.editorversion), + editorBuild = tonumber(info.editorbuild), + mapVersion = tonumber(info.mapversion), + formatVersion = tonumber(info.formatversion), + prefab = info.prefab == "1", + } + return scene, nil +end + +-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world) +function Vmf.brushes(doc: KeyValues.Block): ({ { id: number?, entity: number, faces: { any }, materials: { string } } }?, Err.Err?) + local out = {} + local entity = 0 + local function walk(b: KeyValues.Block): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: KeyValues.Block, entity) + if not s then + return err + end + local faces, mats = {}, {} + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(mats, sd.material) + end + end + table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats }) + elseif k == "hidden" then + local err = walk(p.value :: KeyValues.Block) + if err then + return err + end + end + end + end + return nil + end + for _, p in doc do + local k = string.lower(p.key) + if type(p.value) == "table" and (k == "world" or k == "entity") then + entity += 1 + local err = walk(p.value :: KeyValues.Block) + if err then + return nil, Err.new(Err.CORRUPT, err) + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Hammer writes dispinfo rows at their block's own indent +local FLAT: { [string]: boolean } = {} +for _, k in { "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" } do + FLAT[k] = true +end + +function Vmf.encode(value: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local doc = value + if type(value) == "table" and value.kind == "scene" then + doc = value.meta and value.meta.vmf + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written") + end + end + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document") + end + local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function fmt(x: number): string + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + return (string.gsub(string.format("%.6f", x), "%.?0+$", "")) +end + +local function kv(k: string, v: string): KeyValues.Pair + return { key = k, value = v } +end + +-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls) +local function defaultAxes(points: { { number } }): ({ number }, { number }) + local a, b, c = points[1], points[2], points[3] + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx) + if nz >= nx and nz >= ny then + return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 } + elseif nx >= ny then + return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } + end + return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } +end + +local function id(given: number?, default: number): string + return fmt(given or default) +end + +function Vmf.side(s: SideSpec, sideId: number?): KeyValues.Pair + local p = s.points + local du, dv = defaultAxes(p) + local u, v = s.uaxis or du, s.vaxis or dv + local function axis(x: { number }): string + return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25) + end + local function pt(x: { number }): string + return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")" + end + return { key = "side", value = { + kv("id", id(sideId, 1)), + kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])), + kv("material", s.material or "TOOLS/TOOLSNODRAW"), + kv("uaxis", axis(u)), + kv("vaxis", axis(v)), + kv("rotation", fmt(s.rotation or 0)), + kv("lightmapscale", fmt(s.lightmapscale or 16)), + kv("smoothing_groups", "0"), + } } +end + +function Vmf.solid(sides: { SideSpec }, solidId: number?): KeyValues.Pair + local blk: KeyValues.Block = { kv("id", id(solidId, 1)) } + for i, s in sides do + table.insert(blk, Vmf.side(s, i)) + end + table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } }) + return { key = "solid", value = blk } +end + +-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north, +-- south) +function Vmf.box(lo: { number }, hi: { number }, material: string | { string }, solidId: number?): KeyValues.Pair + local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] + local function m(i: number): string + return if type(material) == "table" then material[i] or material[1] else material + end + return Vmf.solid({ + { points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) }, + { points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) }, + { points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) }, + { points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) }, + { points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) }, + { points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) }, + }, solidId) +end + +-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons +function Vmf.document(worldKeys: { [string]: string }?): KeyValues.Block + local world: KeyValues.Block = { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") } + if worldKeys then + local keys = {} + for k in worldKeys do + table.insert(keys, k) + end + table.sort(keys) + for _, k in keys do + table.insert(world, kv(k, worldKeys[k])) + end + end + return { + { key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } }, + { key = "visgroups", value = {} }, + { key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } }, + { key = "world", value = world }, + { key = "cameras", value = { kv("activecamera", "-1") } }, + { key = "cordons", value = { kv("active", "0") } }, + } +end + +-- an entity block (keys in the given order, then its solids) appended to doc before cameras +function Vmf.entity(doc: KeyValues.Block, keys: { { string } }, solids: { KeyValues.Pair }?): KeyValues.Pair + local count = 1 + for _, p in doc do + if string.lower(p.key) == "entity" then + count += 1 + end + end + local blk: KeyValues.Block = { kv("id", id(nil, count + 1)) } + for _, k in keys do + table.insert(blk, kv(k[1], k[2])) + end + for _, s in solids or {} do + table.insert(blk, s) + end + local pair = { key = "entity", value = blk } + local at = #doc + 1 + for i, p in doc do + if string.lower(p.key) == "cameras" then + at = i + break + end + end + table.insert(doc, at, pair) + return pair +end + +-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...))) +function Vmf.world(doc: KeyValues.Block): KeyValues.Block? + local w = KeyValues.get(doc, "world") + return if type(w) == "table" then w else nil +end + +return Vmf +end +__FILES["model/vmf/Build"] = function() + +-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes +-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one +-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras. +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Brush = __include("codecs/model/Brush") +local Displacement = __include("codecs/model/Displacement") +local Mat4 = __include("codecs/model/Mat4") + +local Build = {} + +type Block = KeyValues.Block + +type Side = { + id: number?, + points: { number }, -- 9: the plane's three points + material: string, + uaxis: { number }, -- x, y, z, shift, scale + vaxis: { number }, + disp: Block?, +} +type Solid = { id: number?, sides: { Side }, editor: any, entity: number } +type Options = { + tools: boolean, + size: (name: string) -> (number, number, boolean), + maxPolygons: number?, +} + +local function nums(s: any): { number } + local out: { number } = {} + if type(s) ~= "string" then + return out + end + for w in string.gmatch(s, "[^%s%(%)%[%]]+") do + local n = tonumber(w) + if n then + table.insert(out, n) + end + end + return out +end +Build.nums = nums + +local function get(b: Block, key: string): any + return KeyValues.get(b, key) +end + +local function editor(b: Block): any + local e = KeyValues.find(b, "editor") + return if e and type(e.value) == "table" then KeyValues.toObject(e.value) else nil +end + +function Build.solid(b: Block, entity: number): (Solid?, string?) + local sides: { Side } = {} + for _, p in KeyValues.all(b, "side") do + if type(p.value) == "table" then + local sb = p.value :: Block + local pts = nums(get(sb, "plane")) + if #pts ~= 9 then + return nil, "side without a 3-point plane" + end + local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis")) + local d = KeyValues.find(sb, "dispinfo") + table.insert(sides, { + id = tonumber(get(sb, "id")), + points = pts, + material = tostring(get(sb, "material") or ""), + uaxis = if #u >= 5 then u else { 1, 0, 0, 0, 1 }, + vaxis = if #v >= 5 then v else { 0, -1, 0, 0, 1 }, + disp = if d and type(d.value) == "table" then d.value :: Block else nil, + }) + end + end + return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil +end + +function Build.face(s: Side): Brush.Face? + local p = s.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) } +end + +local function rows(d: Block, name: string, per: number, n: number): { number }? + local blk = KeyValues.get(d, name) + if type(blk) ~= "table" then + return nil + end + local out: { number } = table.create(n * n * per, 0) :: any + for i = 0, n - 1 do + local r = nums(KeyValues.get(blk, "row" .. i)) + for k = 1, math.min(#r, n * per) do + out[i * n * per + k] = r[k] + end + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number }, blend: { number } } + +-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp) +local function displace(s: Side, face: Brush.Face, poly: Brush.Polygon, acc: Acc, w: number, h: number): string? + local d = s.disp :: Block + local power = tonumber(KeyValues.get(d, "power")) or 0 + if power < 1 or power > 4 or power % 1 ~= 0 then + return "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + local start = nums(KeyValues.get(d, "startposition")) + if #start < 3 then + return "displacement without a start position" + end + local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n) + local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n) + local elev = tonumber(KeyValues.get(d, "elevation")) or 0 + local pn = face.plane + local offsets: { number } = table.create(n * n * 3, 0) :: any + for k = 0, n * n - 1 do + for c = 1, 3 do + local v = elev * pn[c] + if normals and dists then + v += normals[k * 3 + c] * dists[k + 1] + end + if offs then + v += offs[k * 3 + c] + end + offsets[k * 3 + c] = v + end + end + -- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise + local pts = poly.points + local cw: { number } = {} + for k = #pts // 3 - 1, 0, -1 do + table.insert(cw, pts[k * 3 + 1]) + table.insert(cw, pts[k * 3 + 2]) + table.insert(cw, pts[k * 3 + 3]) + end + local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] }) + if not surf then + return err + end + local base = #acc.pos // 3 + for k = 0, n * n - 1 do + local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3] + for c = 1, 3 do + table.insert(acc.pos, surf.pos[k * 3 + c]) + table.insert(acc.nrm, surf.nrm[k * 3 + c]) + end + local u, v = Brush.uv(face, x, y, z, w, h) + table.insert(acc.uv, u) + table.insert(acc.uv, v) + table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1)) + end + for _, i in surf.idx do + table.insert(acc.idx, base + i) + end + return nil +end + +local function isTool(name: string): boolean + return string.sub(string.lower(name), 1, 6) == "tools/" +end + +-- the solids of one entity -> its primitives (material indices by name through matOf) +function Build.mesh(solids: { Solid }, o: Options, matOf: (string) -> number, name: string): (Types.Mesh?, string?) + local brushes: { { Brush.Face } } = {} + local sideOf: { { Side } } = {} + local hasDisp: { boolean } = {} + for _, s in solids do + local faces: { Brush.Face } = {} + local sides: { Side } = {} + local disp = false + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(sides, sd) + disp = disp or sd.disp ~= nil + end + end + if #faces >= 4 then + table.insert(brushes, faces) + table.insert(sideOf, sides) + table.insert(hasDisp, disp) + end + end + local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons }) + if not polys then + return nil, perr + end + local keep: { Brush.Polygon } = {} + local disps: { [string]: Acc } = {} + local dispOrder: { string } = {} + for _, p in polys do + local sd = sideOf[p.brush][p.face] + if o.tools or not isTool(sd.material) then + if sd.disp then + local acc = disps[sd.material] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} } + disps[sd.material] = acc + table.insert(dispOrder, sd.material) + end + local w, h = o.size(sd.material) + local err = displace(sd, brushes[p.brush][p.face], p, acc :: Acc, w, h) + if err then + return nil, err + end + elseif not hasDisp[p.brush] then + table.insert(keep, p) + end + end + end + local mesh: Types.Mesh = { name = name, primitives = {} } + local function size(n: string): (number, number) + local w, h = o.size(n) + return w, h + end + for _, b in Brush.primitives(keep, brushes, size) do + b.primitive.material = matOf(b.texture) + table.insert(mesh.primitives, b.primitive) + end + for _, m in dispOrder do + local prim = Displacement.primitive(disps[m] :: any) + prim.material = matOf(m) + table.insert(mesh.primitives, prim) + end + return mesh, nil +end + +local function quat(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +-- a camera at position looking at look, z up: glTF cameras look along -z with +y up +local function lookAt(pos: { number }, look: { number }): { number } + local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3] + local l = math.sqrt(fx * fx + fy * fy + fz * fz) + if l < 1e-9 then + return { 0, 0, 0, 1 } + end + fx, fy, fz = fx / l, fy / l, fz / l + local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1) + local rl = math.sqrt(rx * rx + ry * ry) + if rl < 1e-9 then + rx, ry, rl = 1, 0, 1 + end + rx, ry = rx / rl, ry / rl + local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f + return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +local function visgroups(b: Block): { any } + local out = {} + for _, p in KeyValues.all(b, "visgroup") do + if type(p.value) == "table" then + local v = p.value :: Block + table.insert(out, { + name = KeyValues.get(v, "name"), + id = tonumber(KeyValues.get(v, "visgroupid")), + color = KeyValues.get(v, "color"), + children = visgroups(v), + }) + end + end + return out +end + +-- solids of a block, including those inside its hidden { } blocks +local function solidsOf(b: Block, entity: number, out: { Solid }): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: Block, entity) + if not s then + return err + end + table.insert(out, s) + elseif k == "hidden" then + local err = solidsOf(p.value :: Block, entity, out) + if err then + return err + end + end + end + end + return nil +end + +function Build.scene(doc: Block, o: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + local mats: { [string]: number } = {} + local function matOf(name: string): number + local m = mats[name] + if m then + return m + end + local w, h, known = o.size(name) + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + table.insert(scene.textures, { name = name, uri = path .. ".vtf" }) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + mats[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "vmf", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local ents: { any } = {} + local solidsMeta: { any } = {} + local groups: { any } = {} + -- world and entities, hidden ones included + local blocks: { { key: string, block: Block } } = {} + for _, p in doc do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "world" or k == "entity" then + table.insert(blocks, { key = k, block = p.value :: Block }) + elseif k == "hidden" then + for _, q in KeyValues.all(p.value :: Block, "entity") do + if type(q.value) == "table" then + table.insert(blocks, { key = "entity", block = q.value :: Block }) + end + end + end + end + end + for _, item in blocks do + local b = item.block + local keys: Block = {} + local conns: any = nil + for _, p in b do + if type(p.value) == "string" then + table.insert(keys, p) + elseif string.lower(p.key) == "connections" then + conns = KeyValues.toObject(p.value :: Block) + elseif item.key == "world" and string.lower(p.key) == "group" then + local g = p.value :: Block + table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) }) + end + end + local e = KeyValues.toObject(keys) + if conns then + e.connections = conns + end + table.insert(ents, e) + local ei = #ents + local solids: { Solid } = {} + local serr = solidsOf(b, ei, solids) + if serr then + return nil, serr + end + local class = if type(e.classname) == "string" then e.classname else item.key + local name = if item.key == "world" then "world" elseif type(e.targetname) == "string" then e.targetname else class + local node: Types.Node = { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } } + if #solids > 0 then + local mesh, merr = Build.mesh(solids, o, matOf, name) + if not mesh then + return nil, merr + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + for _, s in solids do + table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor }) + end + else + local org = nums(e.origin) + if #org >= 3 then + node.translation = { org[1], org[2], org[3] } + end + local ang = nums(e.angles) + if #ang >= 3 then + node.rotation = quat(ang[1], ang[2], ang[3]) + end + if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then + (node.extras :: any).model = e.model + end + end + if node.mesh or item.key ~= "world" then + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + end + -- cameras + local cams = KeyValues.get(doc, "cameras") + local camMeta: any = nil + if type(cams) == "table" then + camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} } + for _, p in KeyValues.all(cams, "camera") do + if type(p.value) == "table" then + local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look")) + if #pos >= 3 and #look >= 3 then + local cam: Types.Camera = { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 } + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) }) + table.insert(root.children, #scene.nodes) + table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } }) + end + end + end + end + local vg = KeyValues.get(doc, "visgroups") + scene.meta.entities = ents + scene.meta.solids = solidsMeta + scene.meta.groups = groups + scene.meta.visgroups = if type(vg) == "table" then visgroups(vg) else {} + scene.meta.cameras = camMeta + return scene, nil +end + +return Build +end __FILES["model/vox"] = function() -- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). diff --git a/build/rosetta.lua b/build/rosetta.lua index 5b539fc..e87f36c 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -2255,7 +2255,7 @@ local list= { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, load = function() return __include("model/bsp") @@ -2345,6 +2345,18 @@ local list= { return __include("model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return __include("model/map") + end, + }, { name = "mca", category = "model", @@ -2573,6 +2585,30 @@ local list= { return __include("model/usda") end, }, + { + name = "vbsp", + category = "model", + path = "model/vbsp", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, + load = function() + return __include("model/vbsp") + end, + }, + { + name = "vmf", + category = "model", + path = "model/vmf", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, + load = function() + return __include("model/vmf") + end, + }, { name = "vox", category = "model", @@ -70325,12 +70361,229 @@ end return Yuv end +__FILES["codecs/image/Miptex"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Quantize = __include("codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) + + + + + + + + + + +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +function Miptex.header(b, at, size) +if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b, at, size, hd) +local w, h = hd.width, hd.height + local p = hd.offsets[4] + (math.floor(w / 8)) * (math.floor(h / 8)) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b, at, size, opts) +local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = math.floor(hd.width / (2 ^ mip)), math.floor(hd.height / (2 ^ mip) +) if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = (opts and opts.goldsrc and{(Miptex.ownPalette(b, at, size, hd) )}or{nil +})[1] local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = (opts and opts.keyed ~= nil and{opts.keyed }or{(string.sub(hd.name, 1, 1) == "{" +)})[1] if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px, w, h) +local w2, h2 = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s =s+ readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, math.floor((s + 2) / 4)) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img, name, palette, goldsrc) +local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + local colors +if palette then + colors = Pixels.colorList(palette) + elseif goldsrc then + colors = Quantize.palette(img.pixels, w, h, 256) + else + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local levels= {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = keyed and 255 or nil }) + if keyed then + for k = 0, lw * lh - 1 do + if readu8(px, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + levels[m + 1] = idx + end + local total = 40 + for _, l in __iter(levels) do + total =total+ buffer.len(l) + end + local palAt = total + if goldsrc then + total =total+ (2 + 768 + 2 +) end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in __iter(levels) do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o =o+ buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b, base, size, maxLumps) +if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out= {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps, name) +local want = string.lower(name) + local best= nil + for _, l in __iter(lumps) do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +return Miptex +end __FILES["codecs/image/Pixels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -70587,6 +70840,61 @@ local seen= {} return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +function Pixels.grey() +local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and +-- '{' textures) +function Pixels.keyed(pal, index) +local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu32(out, index * 4, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +function Pixels.colorList(pal, n) +local out= {} + for i = 0, math.clamp(n or 256, 0, math.floor(buffer.len(pal) / 4)) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +function Pixels.colormap(pal, cmap, base, row) +local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +function Pixels.paletteBytes(pal, n) +local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels end __FILES["codecs/image/Quantize"] = function() @@ -77153,6 +77461,795 @@ end return Yuv end +__FILES["codecs/model/Brush"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = __include("Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north + + + + + + + + + + + + + + + + + + + + + + + +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +local function snap(x) +local r = floor(x + 0.5) + return (abs(x - r) < 1e-6 and{r }or{x +})[1]end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +function Brush.planeFromPoints(a, b, c) +local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +function Brush.baseAxis(n) +local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +function Brush.quakeVecs(n, xoff, yoff, rot, xscale, yscale) +local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = vecs[1][1] ~= 0 and 1 or(vecs[1][2] ~= 0 and 2 or 3 +) local tv = vecs[2][1] ~= 0 and 1 or(vecs[2][2] ~= 0 and 2 or 3 +) for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +function Brush.valveVecs(u, v, xscale, yscale) +local su, sv = xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +function Brush.axisBase(normal) +local nx, ny, nz = normal[1], normal[2], normal[3] + nx = abs(nx) < 1e-6 and 0 or nx + ny = abs(ny) < 1e-6 and 0 or ny + nz = abs(nz) < 1e-6 and 0 or nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +function Brush.bpVecs(normal, m, w, h) +local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in __iter({ w, h }) do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +function Brush.vecsToBp(normal, vecs, w, h) +local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in __iter({ w, h }) do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +function Brush.uv(face, x, y, z, w, h) +local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +function Brush.baseWinding(p, size) +local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +function Brush.split(pts, p, eps) +local n = math.floor(#pts / 3 +) local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = (table.create(n, 0) ) +local side = (table.create(n, 0) ) +local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front =front+ 1 + elseif v < -eps then + side[i + 1] = -1 + back =back+ 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f, b= {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return ((#f >= 9 and{f }or{nil})[1]), ((#b >= 9 and{b }or{nil})[1]), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +local function clean(pts, eps) +local out= {} + local n = math.floor(#pts / 3 +) for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = math.floor(#out / 3 +) for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return (#out >= 9 and{out }or{nil +})[1]end + +local function samePlane(a, b, eps) +return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +local function oppositePlane(a, b, eps) +return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +function Brush.windings(planes, opts) +local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out= {} + for i, p in __iter(planes) do + local w= Brush.baseWinding(p, size) + for j, q in __iter(planes) do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = (on and{nil }or{back +})[1] end + end + end + out[i] = (w and{(clean(w, eps) )}or{nil +})[1] end + return out +end + +local function bounds(polys) +local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in __iter(polys) do + local pts = p.points + for k = 0, math.floor(#pts / 3 )- 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +local function outside(pts, own, a, b, planes, eps) +local kept= {} + local inside= pts + for _, q in __iter(planes) do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +local function faceKey(f) +local parts = { f.texture or "" } + for _, m in __iter({ f.vecs, f.bp }) do + if m then + for _, row in __iter(m) do + for _, v in __iter(row) do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +local function convex(pts, n, eps) +local k = math.floor(#pts / 3 +) for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +local function tryMerge(f1, f2, n, eps) +local n1, n2 = math.floor(#f1 / 3), math.floor(#f2 / 3 +) for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out= {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +local function mergeAll(polys, faces, eps) +local groups= {} + local order= {} + for _, p in __iter(polys) do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out= {} + for _, key in __iter(order) do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in __iter(g) do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +function Brush.polygons(brushes, opts) +local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per= {} + local planesOf= {} + local count = 0 + for bi, faces in __iter(brushes) do + local planes= {} + for fi, f in __iter(faces) do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list= {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count =count+ #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all= {} + if opts and opts.hull then + local boxes= {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in __iter(per[bi]) do + local frags= { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags= {} + for _, fr in __iter(frags) do + for _, kept in __iter(outside(fr, own, bi, bj, planesOf[bj], eps)) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in __iter(frags) do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in __iter(per[bi]) do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +function Brush.area(pts) +local n = math.floor(#pts / 3 +) local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax =ax+ (uy * vz - uz * vy +) ay =ay+ (uz * vx - ux * vz +) az =az+ (ux * vy - uy * vx +) end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +function Brush.primitives(polys, brushes, size) + +local byTex= {} + local order= {} + local sizes= {} + for _, p in __iter(polys) do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a= acc + local pts = p.points + local n = math.floor(#pts / 3 +) local base = math.floor(#a.pos / 3 +) for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out= {} + for _, a in __iter(order) do + local nv, ni = math.floor(#a.pos / 3), #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" , + }, + }) + end + return out +end + +return Brush +end +__FILES["codecs/model/Displacement"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- codecs/model/Displacement: Source engine displacement surfaces (VBSP ddispinfo_t / Hammer dispinfo), as +-- CCoreDispInfo::GenerateDispSurf of the Source SDK 2013 (no code taken): corner 0 is the base face corner nearest the +-- start position, rows run along corner 0 -> 1, columns along 0 -> 3 (the face's own, clockwise, winding), each vertex +-- moved by its offset; the 2^power quads split along alternating diagonals. Normals come from the grid. +local Types = __include("Types") + +local Displacement = {} + +local sqrt = math.sqrt + + + + + + + + + +local function cross(ax, ay, az, bx, by, bz) +return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx +end + +-- corners: the 4 face corners (12 numbers) in the face's clockwise winding; offsets: n * n * 3 numbers (row major, +-- row = i along corner 0 -> 1) added to the flat grid; normal: the face's outward normal +function Displacement.surface(corners, start, power, offsets, normal) +if #corners ~= 12 then + return nil, "a displacement needs a 4-sided face" + end + if power < 1 or power > 4 or power % 1 ~= 0 then + return nil, "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + if #offsets < n * n * 3 then + return nil, "displacement offsets truncated" + end + local best, bestD = 0, math.huge + for k = 0, 3 do + local dx, dy, dz = corners[k * 3 + 1] - start[1], corners[k * 3 + 2] - start[2], corners[k * 3 + 3] - start[3] + local d = dx * dx + dy * dy + dz * dz + if d < bestD then + best, bestD = k, d + end + end + local c= (table.create(12) ) +for k = 0, 3 do + local s = ((best + k) % 4) * 3 + c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = corners[s + 1], corners[s + 2], corners[s + 3] + end + local flat= (table.create(n * n * 3) ) +local pos= (table.create(n * n * 3) ) +for i = 0, n - 1 do + local t = i / (n - 1) + local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t + local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t + for j = 0, n - 1 do + local s = j / (n - 1) + local k = (i * n + j) * 3 + local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s + flat[k + 1], flat[k + 2], flat[k + 3] = x, y, z + pos[k + 1], pos[k + 2], pos[k + 3] = x + offsets[k + 1], y + offsets[k + 2], z + offsets[k + 3] + end + end + local nx, ny, nz = normal[1], normal[2], normal[3] + local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3]) + local sign = ux * nx + uy * ny + uz * nz >= 0 and 1 or-1 + local nrm= (table.create(n * n * 3) ) +for i = 0, n - 1 do + local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1) + for j = 0, n - 1 do + local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1) + local a, b = (i1 * n + j) * 3, (i0 * n + j) * 3 + local e, f = (i * n + j1) * 3, (i * n + j0) * 3 + local x, y, z = cross(pos[a + 1] - pos[b + 1], pos[a + 2] - pos[b + 2], pos[a + 3] - pos[b + 3], pos[e + 1] - pos[f + 1], pos[e + 2] - pos[f + 2], pos[e + 3] - pos[f + 3]) + local l = sqrt(x * x + y * y + z * z) + local k = (i * n + j) * 3 + if l < 1e-12 then + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + else + nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l + end + end + end + -- triangle (i, j), (i + 1, j), (i, j + 1) turns about rows x columns: flipped when that faces away + local idx= (table.create((n - 1) * (n - 1) * 6) ) +local flip = sign < 0 + for i = 0, n - 2 do + for j = 0, n - 2 do + local a = i * n + j + local b, cc, d = a + n, a + n + 1, a + 1 + local t1, t2, t3, t4, t5, t6 + if (i + j) % 2 == 0 then + t1, t2, t3, t4, t5, t6 = a, b, d, b, cc, d + else + t1, t2, t3, t4, t5, t6 = a, b, cc, a, cc, d + end + if flip then + t2, t3, t5, t6 = t3, t2, t6, t5 + end + local q = #idx + idx[q + 1], idx[q + 2], idx[q + 3], idx[q + 4], idx[q + 5], idx[q + 6] = t1, t2, t3, t4, t5, t6 + end + end + return { n = n, flat = flat, pos = pos, nrm = nrm, idx = idx }, nil +end + +-- flat arrays -> an indexed triangle primitive (POSITION, NORMAL, TEXCOORD_0, _BLEND) + + + + + + + + +function Displacement.primitive(a) +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + local nv, ni = math.floor(#a.pos / 3), #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + local attrs= { + POSITION = S.accessor(pb, "f32", 3, nv), + NORMAL = S.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = S.accessor(ub, "f32", 2, nv), + } + local blend = a.blend + if blend then + local bb = buffer.create(nv * 4) + for k = 1, nv do + writef32(bb, (k - 1) * 4, blend[k] or 0) + end + attrs._BLEND = S.accessor(bb, "f32", 1, nv) + end + return { attributes = attrs, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" } +end + +return Displacement +end __FILES["codecs/model/Draco"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). @@ -82818,6 +83915,130 @@ end return Packed end +__FILES["codecs/model/Patch"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +function Patch.valid(w, h, n) +return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +function Patch.grid(ctrl, w, h, comps, levelU, levelV, maxPoints) +local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, math.floor(#ctrl / comps)) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = math.floor((w - 1) / 2), math.floor((h - 1) / 2 +) local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = (table.create(gw * gh * comps, 0) ) +for gy = 0, gh - 1 do + local sy = math.min(math.floor(gy / lv), py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(math.floor(gx / lu), px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = (j == 0 and{bv0 }or{(j == 1 and{bv1 }or{bv2 +})[1]})[1] local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * ((i == 0 and{bu0 }or{(i == 1 and{bu1 }or{bu2})[1]})[1]) + local c = row + i * comps + for k = 1, comps do +do local __DARKLUA_VAR=o + k out[__DARKLUA_VAR]=out[__DARKLUA_VAR]+ ctrl[c + k] * wgt +end end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +function Patch.triangles(gw, gh) +local out = (table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) ) +for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +function Patch.normalize(pts, comps, at) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +function Patch.normals(pts, comps, gw, gh) +local out = (table.create(gw * gh * 3, 0) ) +local function at(x, y, k) +return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, math.floor(i / gw +) for _, d in __iter({ { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } }) do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch +end __FILES["codecs/model/Polygon"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. @@ -88794,6 +90015,9 @@ local KeyValues = {} + + + @@ -88830,6 +90054,7 @@ local s, n = lx.s, lx.n lx.i = i + 1 return c, nil, i - 1, nil elseif c == '"' then + lx.quoted = true local start = i i =i+ 1 if not lx.escapes then @@ -88854,8 +90079,8 @@ local s, n = lx.s, lx.n return "s", table.concat(parts), start - 1, nil end local x = string.sub(s, e + 1, e + 1) - local r = ESCAPE[x] - if r then + local r = (lx.quotesOnly and x ~= '"' and{nil }or{ESCAPE[x] +})[1] if r then table.insert(parts, r) i = e + 2 else @@ -88871,6 +90096,7 @@ local s, n = lx.s, lx.n return "[", string.sub(s, i + 1, e - 1), i - 1, nil end end + lx.quoted = false local e = string.find(s, '[ \t\r\n\f\v"{}]', i) local stop = (e and((e - 1 ))or(n )) lx.i = stop + 1 @@ -88915,7 +90141,7 @@ end local function parseText(text, opts, depth0) local o= opts or {} - local lx= { s = text, i = 1, n = #text, escapes = o.escapes ~= false } + local lx= { s = text, i = 1, n = #text, escapes = o.escapes ~= false, quotesOnly = o.escapes == "quotes" } if string.sub(text, 1, 3) == "\239\187\191" then lx.i = 4 end @@ -88955,7 +90181,8 @@ local o= opts or {} return nil, Err.new(Err.CORRUPT, kind == "{" and"block without a key" or"condition without a key", at) else local key = v -local k2, v2, at2, terr2 = token(lx) +local keyQuoted = lx.quoted + local k2, v2, at2, terr2 = token(lx) if terr2 then return nil, Err.new(Err.TRUNCATED, terr2, at2) end @@ -88978,7 +90205,7 @@ local k2, v2, at2, terr2 = token(lx) if not pass then skipping =skipping+ 1 else - local pair= { key = key, value = {}, cond = (evaluate and{nil }or{cond })[1]} + local pair= { key = key, value = {}, cond = (evaluate and{nil }or{cond})[1], bare = not keyQuoted } local last = cur[#cur] if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then cur[#cur] = pair @@ -89081,7 +90308,7 @@ function KeyValues.copy(b) local out= (table.create(#b) ) for i, p in __iter(b) do local v= p.value - out[i] = { key = p.key, value = (type(v) == "table" and{(KeyValues.copy(v) )}or{v})[1], cond = p.cond, type = p.type } + out[i] = { key = p.key, value = (type(v) == "table" and{(KeyValues.copy(v) )}or{v})[1], cond = p.cond, type = p.type, bare = p.bare } end return out end @@ -89125,17 +90352,22 @@ local out= {} end local function quote(s, escapes) -if escapes then +if escapes == "quotes" then + s = string.gsub(s, '"', '\\"') + elseif escapes then s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) end return '"' .. s .. '"' end -local function writeBlock(b, out, indent, level, escapes, depth) -if depth > 256 then + + +local function writeBlock(b, out, w, level, depth) +local dp = depth or 0 + if dp > 256 then return "nesting deeper than 256" end - local pad = string.rep(indent, level) + local pad = string.rep(w.indent, level) for _, p in __iter(b) do if type(p) ~= "table" or type(p.key) ~= "string" then return "a pair needs a string key" @@ -89143,15 +90375,16 @@ if depth > 256 then local v= p.value local cond = (type(p.cond) == "string" and((" [" .. p.cond .. "]" ))or("" )) if type(v) == "table" then - table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n") - local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1) + local name = (w.bare and (p.bare or (p.bare == nil and string.match(p.key, "^[%w_]+$"))) and{p.key }or{(quote(p.key, w.escapes) +)})[1] table.insert(out, pad .. name .. cond .. "\n" .. pad .. "{\n") + local err = writeBlock(v, out, w, (w.flat[p.key] and{level }or{(level + 1)})[1], dp + 1) if err then return err end table.insert(out, pad .. "}\n") elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then local s = (type(v) == "boolean" and{(v and"1" or"0") }or{(tostring(v) -)})[1] table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n") +)})[1] table.insert(out, pad .. quote(p.key, w.escapes) .. w.sep .. quote(s, w.escapes) .. cond .. "\n") else return "unwritable value for key " .. p.key end @@ -89164,7 +90397,8 @@ if type(b) ~= "table" then return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list") end local out= {} - local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0) + local o= opts or {} + local err = writeBlock(b, out, { indent = o.indent or "\t", escapes = o.escapes == nil and true or o.escapes, sep = o.separator or "\t", bare = o.bareBlocks == true, flat = o.flatBlocks or {} }, 0) if err then return nil, Err.new(Err.ARG, err) end @@ -89342,6 +90576,7 @@ local Binary = {} + local readu8, readu32, readi32, readf32 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32 local TYPES= { [2] = "int32", [3] = "float32", [4] = "pointer", [5] = "wstring", [6] = "color", [7] = "uint64", [10] = "int64" } @@ -146830,7 +148065,7 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, } -- ------------------------------------------------------------------------------------------------ types @@ -146962,6 +148197,7 @@ local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__ite -- size. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") local Brush = {} @@ -146994,34 +148230,18 @@ local out= {} if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = (pal and{(Pixels.palette(pal, 0, 256) )}or{nil + local gpal = (pal and not hl and{(Pixels.palette(pal, 0, 256) )}or{nil })[1] for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = (o >= 0 and o + 40 <= l.size and{(Miptex.header(b, at + o, l.size - o) )}or{nil +})[1] if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t= { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (math.floor(w / 8)) * (math.floor(h / 8)) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = (palAt - at + 768 <= l.size and{(Pixels.palette(b, palAt, 256) )}or{nil -})[1] end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t= { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -147099,12 +148319,12 @@ local q2 = variant == "q2" local orders= {} local skipped = 0 for f = 0, nF - 1 do -local __DARKLUA_CONTINUE_8=false repeat local fo = base + Fc.at + f * 20 +local __DARKLUA_CONTINUE_7=false repeat local fo = base + Fc.at + f * 20 local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) local model = faceModel[f + 1] if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then skipped =skipped+ 1 -__DARKLUA_CONTINUE_8=true break +__DARKLUA_CONTINUE_7=true break end local poly= {} local ok = true @@ -147127,7 +148347,7 @@ __DARKLUA_CONTINUE_8=true break end if not ok then skipped =skipped+ 1 -__DARKLUA_CONTINUE_8=true break +__DARKLUA_CONTINUE_7=true break end local po = base + P.at + plane * 20 local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) @@ -147183,7 +148403,7 @@ __DARKLUA_CONTINUE_8=true break uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h end end -__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end 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) @@ -147236,8 +148456,10 @@ 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 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. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = __include("Types") +local Patch = __include("codecs/model/Patch") local Quake3 = {} @@ -147317,52 +148539,23 @@ for k = 1, 14 do do local __DARKLUA_VAR=kind == 1 and"polygons" or"meshes" counts[__DARKLUA_VAR]=counts[__DARKLUA_VAR]+ 1 end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches =counts.patches+ 1 - local L = level - for py = 0, math.floor((h - 1) / 2 )- 1 do - for px = 0, math.floor((w - 1) / 2 )- 1 do - local ctrl= {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid= {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k]=v[k]+ cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - 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] - -- Quake's control grids are clockwise-front - for _, v in __iter({ a, d, c2, c2, d, e }) do - table.insert(tris, v) - end - end - end - end + local ctrl = (table.create(n * 14, 0) ) +for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = (table.create(gw * gh) ) +for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra((table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) )) + end + for _, v in __iter(Patch.triangles(gw, gh)) do + table.insert(tris, ids[v + 1]) end else counts.skipped =counts.skipped+ 1 @@ -158768,6 +159961,1097 @@ end return Parse end +__FILES["model/map"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Miptex = __include("codecs/image/Miptex") +local Brush = __include("codecs/model/Brush") +local Parse = __include("model/map/Parse") +local Write = __include("model/map/Write") +local Build = __include("model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + +function Map.sniff(r) +local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c ) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return game and string.match(s, "^%s*{") and 0.6 or 0 + end + return (game or string.find(head, '"classname"', 1, true) )and 0.9 or 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m) +local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in __iter(m.entities) do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in __iter(e.brushes) do + if b.type ~= "brush" then + q3 = true + end + for _, f in __iter(b.faces or {}) do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return q2 and"quake2" or"quake" +end + +local function sizer(m, variant, opts) +local cache= {} + local wads= nil + local function loadWads() +local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in __iter(string.gmatch(spec, "[^;]+")) do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name) +local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h= 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] , given[2] +elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads ), 1, -1 do + local wd = (wads )[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in __iter({ ".tga", ".jpg", ".png" }) do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage , b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw, fh= w , h +local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, known and 1 or 0 } + return fw, fh, known + end +end + +function Map.decode(r, opts) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f) +if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x) +return Write.num(x) +end + +function Map.encode(scene, opts) +if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents= {} + for _, node in __iter(scene.nodes) do + local ex= node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes= (type(ex.brushes) == "table" and{ex.brushes }or{{} +})[1] if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv= {} + for _, b in __iter(brushes) do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in __iter(b.faces) do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src= scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents , + game = (fromMap and{src.game }or{nil})[1], + mapFormat = valve and"Valve" or(fromMap and{src.mapFormat }or{nil})[1], + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src) +local text = (type(src) == "buffer" and{(buffer.tostring(src) )}or{(type(src) == "string" and{src }or{nil +})[1]})[1] if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m) +if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f) +return Build.face(f) +end + +return Map +end +__FILES["model/map/Build"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = __include("Types") +local Brush = __include("codecs/model/Brush") +local Patch = __include("codecs/model/Patch") +local Parse = __include("model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + + + + + + + + + + + +function Build.face(f) +local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out= { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + + + +local function patchPrim(b, level, acc) +local size, pts = b.size , b.points +local w, h= size[1] , size[2] +if not Patch.valid(w, h, math.floor(#pts / 5)) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = (table.create(w * h * 5, 0) ) +for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params= b.params or {} + local explicit = b.type == "patchDef3" + local lu= (explicit and{(math.max(1, params[1] or 1) )}or{level +})[1] local lv= (explicit and{(math.max(1, params[2] or 1) )}or{level +})[1] local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = math.floor(#acc.pos / 3 +) for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in __iter(Patch.triangles(gw, gh)) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a) +local nv, ni = math.floor(#a.pos / 3), #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s) +if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map, o) +local scene = Scene.new() + scene.meta.up = "z" + local skip= {} + for _, n in __iter(o.skip or {}) do + skip[string.lower(n)] = true + end + local matOf= {} + local function material(name) +local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root= { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities= {} + local polyTotal = 0 + for ei, ent in __iter(map.entities) do + local keys = ent.keys + table.insert(entities, keys) + local node= { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes= {} + local patchAcc= {} + local patchOrder= {} + for _, b in __iter(ent.brushes) do + if b.faces then + counts.brushes =counts.brushes+ 1 + local faces= {} + for _, f in __iter(b.faces) do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces =skipped.faces+ 1 + end + end + table.insert(brushes, faces) + else + counts.patches =counts.patches+ 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc ) then + skipped.patches =skipped.patches+ 1 + end + end + end + end + local prims= {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal =polyTotal+ #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept= {} + for _, p in __iter(polys) do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name) +local m = scene.materials[material(name)] + local e = (m.extras ).map + return e.width, e.height + end) + for _, bt in __iter(built) do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in __iter(patchOrder) do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build +end +__FILES["model/map/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = __include("Types") + +local Parse = {} + + + + + + + + + + + + + + + + + + + + + + + + + +local function skip(st) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st) +skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st, c) +if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos =st.pos+ 1 + return nil +end + +local function word(st) +skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b ) + 1 + return string.sub(st.s, a, b) +end + +local function number(st) +skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b ) + 1 + end + return v +end + +local function quoted(st) +if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st, n, out) +for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st, n, open, close) +local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st) +local out= {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return (#out > 0 and{out }or{nil +})[1]end + +local function plane(st) +local pts= {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st, bp) +local pts, e = plane(st) + if not pts then + return nil, e + end + local f= { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st, kind, maxPoints) +local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = kind == "patchDef3" and 7 or 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts= {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st, maxPoints) +local c = peek(st) + if c == "(" then + local faces= {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos =st.pos+ 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out, err +if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces= {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s, maxBrushes) +local st= { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents= {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys= {} + local order= {} + local brushes= {} + while true do + local c = peek(st) + if c == "}" then + st.pos =st.pos+ 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos =st.pos+ 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count =count+ 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = (Types.object(keys, order) ), brushes = brushes }) + end + local game, fmt + for _, c in __iter(st.comments) do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse +end +__FILES["model/map/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = __include("Types") +local Parse = __include("model/map/Parse") + +local Write = {} + +function Write.num(x) +if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t, a, b) +local out = (table.create(b - a + 1) ) +for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f, bp) +local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts= { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b, out) +local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = b.type == "patchDef3" and 5 or 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map) +local out= {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in __iter(map.entities) do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in __iter(Types.keys(ent.keys)) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in __iter(ent.brushes or {}) do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in __iter(b.faces or {}) do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +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 (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, @@ -175527,6 +177811,1517 @@ end return Write end +__FILES["model/vbsp"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read, +-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and +-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by +-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a +-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360 +-- (big-endian) and Titanfall / Apex rBSP, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local KeyValues = __include("codecs/text/KeyValues") +local Mat4 = __include("codecs/model/Mat4") +local Zip = __include("containers/Zip") +local Archive = __include("containers/Archive") +local Faces = __include("model/vbsp/Faces") +local Props = __include("model/vbsp/Props") + +-- ------------------------------------------------------------------------------------------------ contract +local Vbsp = { + name = "vbsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local L = { + ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13, + MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43, + TEXDATA_STRING_TABLE = 44, FACES_HDR = 58, +} +local HEADER = 8 + 64 * 16 + 4 +local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vbsp.sniff(r) +if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return v >= 19 and v <= 21 and 1 or 0.5 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +local function angles(p, y, r) +return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +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] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end + +local function vec3(s) +if type(s) ~= "string" then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream +local function unlzma(b, at, size, maxBytes) +if size < 17 then + return nil, "truncated LZMA lump header" + end + local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8) + if actual > maxBytes then + return nil, "limit: LZMA lump of " .. actual .. " bytes" + end + if packed > size - 17 then + return nil, "LZMA lump runs past the end" + end + local props = buffer.create(5) + buffer.copy(props, 0, b, at + 12, 5) + local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes }) + if not out then + return nil, "LZMA lump: " .. tostring((type(err) == "table" and{err.message }or{err})[1]) + end + return out, nil +end + +local function isLzma(b, at, size) +return size >= 17 and buffer.readstring(b, at, 4) == "LZMA" +end + +local function pakArchive(src, maxBytes) +local zc, err = Zip.open(src) + if not zc then + return nil, err + end + local a = Archive.new("zip") + for _, e in __iter(zc:list()) do + local entry= { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = e.method == 0 and"stored" or(e.method == 8 and"deflate" or(e.method == 14 and"lzma" or tostring(e.method))), + mtime = e.mtime, + dir = e.isDir, + } + entry.load = function() +if e.method ~= 14 then + return zc:read(e) + end + -- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks) + local zb = zc.buf + for _, s in __iter(Zip._starts(zb, e)) do + if s + 9 <= buffer.len(zb) then + local psize = buffer.readu16(zb, s + 2) + local start = s + 4 + psize + local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start) + if psize >= 5 and n > 0 and e.size <= maxBytes then + local props = buffer.create(5) + buffer.copy(props, 0, zb, s + 4, 5) + local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes }) + if out then + return out, nil + end + end + end + end + return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry") + end + Archive.put(a, entry) + end + a.meta.source = { format = "zip", lump = "pakfile" } + return a, nil +end + +local function light(scene, e, class) +local l = vec3(e._light) + local rgb= { 1, 1, 1 } + local intensity = 1 + if l then + rgb = { l[1] / 255, l[2] / 255, l[3] / 255 } + local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)") + intensity = (m and tonumber(m)) or 200 + end + local lt= nil +if class == "light" then + lt = { name = nil , type = "point", color = rgb, intensity = intensity } + elseif class == "light_spot" then + local outer = tonumber(e._cone) or 45 + local inner = tonumber(e._inner_cone) or math.min(30, outer) + lt = { name = nil , type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) } + else + lt = { name = nil , type = "directional", color = rgb, intensity = intensity } + end + lt.name = (type(e.targetname) == "string" and{e.targetname }or{class +})[1] table.insert(scene.lights, lt ) + local ang = vec3(e.angles) or { 0, 0, 0 } + if type(e.pitch) == "string" and tonumber(e.pitch) then + ang[1] = -((tonumber(e.pitch) )) -- the FGD's angle_negative_pitch + end + -- the light shines along the entity's forward (+x); a glTF light along -z + return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90)) +end + +function Vbsp.decode(r, opts) +local o= opts or {} + local b, base = r.buf, r.base + local size = r.limit - r.base + if size < HEADER then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VBSP" then + return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0) + end + local version = buffer.readi32(b, base + 4) + if version < 19 or version > 21 then + return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4) + end + local maxBytes = o.maxBytes or 2 ^ 28 + -- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036 + local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER + local dir= {} + for i = 0, 63 do + local p = base + 8 + i * 16 + local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12) + local at, n, v = a, c, d + if l4d2 then + v, at, n = a, c, d + end + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base) + end + dir[i] = { at = at, size = n, version = v, fourcc = f } + end + local cache= {} + local compressed = false + local function lump(i) +local c = cache[i] + if c then + return c, nil + end + local d = dir[i] + local out +if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then + local u, err = unlzma(b, base + d.at, d.size, maxBytes) + if not u then + return nil, "lump " .. i .. ": " .. tostring(err) + end + compressed = true + out = { buf = u, at = 0, size = buffer.len(u) } + else + out = { buf = b, at = base + d.at, size = d.size } + end + cache[i] = out + return out, nil + end + local need= {} + for name, idx in __iter({ planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES }) do + local lp, err = lump(idx) + if not lp then + return nil, Err.from(err) + end + need[name] = lp + end + if need.faces.size == 0 then + local hdr, err = lump(L.FACES_HDR) + if not hdr then + return nil, Err.from(err) + end + need.faces = hdr + end + local groups, ferr, skipped = Faces.build({ + planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges, + faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models, + dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true, + maxVertices = o.maxVertices or 2 ^ 24, + }) + if not groups then + return nil, Err.from(ferr, skipped and skipped - base) + end + + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + + local pak= nil + local pd = dir[L.PAKFILE] + if o.pak ~= false and pd.size > 0 then + local src = buffer.create(pd.size) + buffer.copy(src, 0, b, base + pd.at, pd.size) + pak = pakArchive(src, maxBytes) + scene.meta.pak = pak + end + + -- texdata -> material + texture (materials/.vtf, from the pak when it is there) + local TD, ST, SS = need.texdata, need.table, need.strings + local nTD = math.floor(TD.size / 32 +) local matOf= {} + local function material(td) +if td < 0 or td >= nTD then + return nil + end + local m = matOf[td] + if m then + return m + end + local to = TD.at + td * 32 + local si = buffer.readi32(TD.buf, to + 12) + local name = "texdata" .. td + if si >= 0 and (si + 1) * 4 <= ST.size then + local off = buffer.readi32(ST.buf, ST.at + si * 4) + if off >= 0 and off < SS.size then + name = (string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") ) +end + end + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + local tex= { name = name, uri = path .. ".vtf" } + if pak then + local zc = pak +local ok, data = pcall(zc.read, zc, path .. ".vtf") + if ok and type(data) == "buffer" then + tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil + end + end + table.insert(scene.textures, tex) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { + vbsp = { + vmt = path .. ".vmt", + width = buffer.readi32(TD.buf, to + 16), + height = buffer.readi32(TD.buf, to + 20), + reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) }, + }, + } + table.insert(scene.materials, mat) + matOf[td] = #scene.materials + return #scene.materials + end + + local root= { name = "vbsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelNode= {} + for _, g in __iter(groups) do + local node = modelNode[g.model] + if not node then + local name = g.model == 0 and"world" or"*" .. g.model + table.insert(scene.meshes, { name = name, primitives = {} }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } }) + node = #scene.nodes + modelNode[g.model] = node + table.insert(root.children, node) + end + local mesh = scene.meshes[scene.nodes[node].mesh ] + table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata))) + end + + -- entities + local E = need.entities + local text = (string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") ) +local blocks, eerr = KeyValues.entities(text) + if not blocks then + return nil, Err.new((eerr ).code, "entity lump: " .. (eerr ).message, dir[L.ENTITIES].at) + end + local ents= table.create(#blocks) + for i, blk in __iter(blocks) do + local e = KeyValues.toObject(blk) + ents[i] = e + local class = (type(e.classname) == "string" and{e.classname }or{"" +})[1] local mdl = (type(e.model) == "string" and{(string.match(e.model, "^%*(%d+)$") )}or{nil +})[1] local mi = mdl and tonumber(mdl) + if mi and mi > 0 and modelNode[mi] then + local node = scene.nodes[modelNode[mi] ] + node.name = (type(e.targetname) == "string" and{e.targetname }or{class +})[1] local org = vec3(e.origin) + if org then + node.translation = org + end + local ang = vec3(e.angles) + if ang then + node.rotation = angles(ang[1], ang[2], ang[3]) + end + local x= node.extras + x.vbsp.entity = i + elseif class == "light" or class == "light_spot" or class == "light_environment" then + local li, rot = light(scene, e, class) + table.insert(scene.nodes, { name = scene.lights[li ].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.entities = ents + + -- game lumps + local spVersion= nil + local G = dir[L.GAME_LUMP] + if G.size >= 4 then + local ga = base + G.at + local count = buffer.readi32(b, ga) + if count < 0 or 4 + count * 16 > G.size then + return nil, Err.new(Err.CORRUPT, "game lump directory", G.at) + end + for k = 0, count - 1 do + local eo = ga + 4 + k * 16 + local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6) + local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12) + if id == SPRP then + if off < 0 or len < 0 or off > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local pb, pat, plen = b, base + off, len + if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then + if off + 17 > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local u, err = unlzma(b, base + off, size - off, maxBytes) + if not u then + return nil, Err.from(err, off) + end + pb, pat, plen = u, 0, buffer.len(u) + compressed = true + elseif off + len > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local props, perr = Props.read(pb, pat, plen , ver, o.maxProps or 2 ^ 20) + if not props then + return nil, Err.from(perr, off) + end + spVersion = ver + for pi, p in __iter(props) do + local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model + table.insert(scene.nodes, { + name = nm, + children = {}, + translation = p.origin, + rotation = angles(p.angles[1], p.angles[2], p.angles[3]), + scale = ((p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 )and{p.scale }or{nil})[1], + extras = { + model = p.model, + vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin }, + }, + }) + table.insert(root.children, #scene.nodes) + end + end + end + end + + scene.meta.skippedFaces = skipped + scene.meta.source = { + format = "vbsp", + version = version, + variant = l4d2 and"l4d2" or"v" .. version, + mapRevision = buffer.readi32(b, base + HEADER - 4), + compressed = compressed, + staticPropVersion = spVersion, + entities = text, + } + return scene, nil +end + +return Vbsp +end +__FILES["model/vbsp/Faces"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013 +-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert); displacements through codecs/model/Displacement. +local Types = __include("Types") +local Displacement = __include("codecs/model/Displacement") + +local Faces = {} + +local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8 + +-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP + + + + + + + + + + + + + + + + + +local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200 + +local function emit(g, x, y, z, nx, ny, nz, u, v) +local pos, nrm, uv = g.pos, g.nrm, g.uv + local k = #pos + pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + local q = #uv + uv[q + 1], uv[q + 2] = u, v + return math.floor(k / 3 +)end + +local function displacement(I, g, d, poly, nx, ny, nz, tex) +local di = I.dispinfo + if (d + 1) * 176 > di.size then + return "dispinfo index out of range" + end + local o = di.at + d * 176 + local b = di.buf + local vstart, power = readi32(b, o + 12), readi32(b, o + 20) + if #poly ~= 12 then + return nil -- not a quad: the base face is kept + end + if power < 1 or power > 4 then + return "displacement power " .. power + end + local n = 2 ^ power + 1 + local dv = I.dispverts + if vstart < 0 or (vstart + n * n) * 20 > dv.size then + return "displacement vertices out of range" + end + -- CDispVert: vector * dist, then alpha (0 .. 255) + local offsets= (table.create(n * n * 3) ) +for k = 0, n * n - 1 do + local vo = dv.at + (vstart + k) * 20 + local dist = readf32(dv.buf, vo + 12) + offsets[k * 3 + 1] = readf32(dv.buf, vo) * dist + offsets[k * 3 + 2] = readf32(dv.buf, vo + 4) * dist + offsets[k * 3 + 3] = readf32(dv.buf, vo + 8) * dist + end + local surf, err = Displacement.surface(poly, { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, power, offsets, { nx, ny, nz }) + if not surf then + return err + end + local base = math.floor(#g.pos / 3 +) local blend = g.blend or {} + g.blend = blend + local flat, pos, nrm = surf.flat, surf.pos, surf.nrm + for k = 0, n * n - 1 do + local x, y, z = flat[k * 3 + 1], flat[k * 3 + 2], flat[k * 3 + 3] + emit(g, pos[k * 3 + 1], pos[k * 3 + 2], pos[k * 3 + 3], nrm[k * 3 + 1], nrm[k * 3 + 2], nrm[k * 3 + 3], + (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9], (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10]) + blend[base + k + 1] = math.clamp(readf32(dv.buf, dv.at + (vstart + k) * 20 + 16) / 255, 0, 1) + end + local idx = g.idx + for _, v in __iter(surf.idx) do + idx[#idx + 1] = base + v + end + return nil +end + +function Faces.build(I) +local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes + local nV, nE, nSE, nF = math.floor(V.size / 12), math.floor(E.size / 4), math.floor(SE.size / 4), math.floor(F.size / 56 +) local nTI, nTD, nP = math.floor(TI.size / 72), math.floor(TD.size / 32), math.floor(P.size / 20 +) local faceModel= {} + local M = I.models + for m = 0, math.floor(M.size / 48 )- 1 do + local o = M.at + m * 48 + local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44) + if first >= 0 and count > 0 and first + count <= nF then + for f = first, first + count - 1 do + if faceModel[f] == nil then + faceModel[f] = m + end + end + end + end + local groups= {} + local byKey= {} + local skipped, verts = 0, 0 + local poly= {} + for f = 0, nF - 1 do +local __DARKLUA_CONTINUE_6=false repeat local fo = F.at + f * 56 + local fb = F.buf + local plane, side = readu16(fb, fo), readu8(fb, fo + 2) + local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8) + local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12) + local model = faceModel[f] or 0 + if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then + skipped =skipped+ 1 +__DARKLUA_CONTINUE_6=true break + end + local to = TI.at + ti * 72 + local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68) + if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then +__DARKLUA_CONTINUE_6=true break + end + local w, h = 1, 1 + if td >= 0 and td < nTD then + w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1) + h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1) + else + td = -1 + end + table.clear(poly) + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local vi = readu16(E.buf, E.at + e * 4 + (se >= 0 and 0 or 2)) + if vi >= nV then + ok = false + break + end + local vo = V.at + vi * 12 + poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8) + end + if not ok then + skipped =skipped+ 1 +__DARKLUA_CONTINUE_6=true break + end + local po = P.at + plane * 20 + local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + local key = model * 65536 + td + 1 + local grp= byKey[key] + if not grp then + grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil , idx = {} } + byKey[key] = grp + table.insert(groups, grp) + end + local tex = { + readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12), + readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h, + } + local before = #grp.pos + local done = false + if disp >= 0 then + local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex) + if derr then + return nil, derr, fo + end + done = #grp.pos > before + end + if not done then + local n = numEdges + -- Newell's normal against the plane: the stored winding is clockwise from the front + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local a, b = k * 3, ((k + 1) % n) * 3 + ax =ax+ (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3]) + ay =ay+ (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1]) + az =az+ (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2]) + end + local flip = ax * nx + ay * ny + az * nz < 0 + local first = -1 + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h) + if first < 0 then + first = id + end + end + local idx = grp.idx + for k = 1, n - 2 do + local b, c = first + k, first + k + 1 + if flip then + b, c = c, b + end + idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c + end + end + verts =verts+ math.floor((#grp.pos - before) / 3 +) if verts > I.maxVertices then + return nil, "limit: over maxVertices", fo + end +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end + return groups, nil, skipped +end + +function Faces.primitive(g, material) +local prim = Displacement.primitive(g) + prim.material = material + return prim +end + +return Faces +end +__FILES["model/vbsp/Props"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and +-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the +-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale +-- (v13: last 3 f32), u32 leaf indices (v12+). +local Props = {} + +local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32 + + + + + + + + + + + + + + + +function Props.read(b, at, size, version, maxProps) +local e = at + size + local p = at + if p + 4 > e then + return {}, nil + end + local nd = readi32(b, p) + p =p+ 4 + if nd < 0 or p + nd * 128 > e then + return nil, "static prop model names past the end" + end + local names= (table.create(nd) ) +for i = 0, nd - 1 do + names[i + 1] = (string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") ) +end + p =p+ nd * 128 + if p + 4 > e then + return nil, "static prop leaves truncated" + end + local nl = readi32(b, p) + p =p+ 4 + local leafSize = version >= 12 and 4 or 2 + if nl < 0 or p + nl * leafSize + 4 > e then + return nil, "static prop leaves past the end" + end + p =p+ nl * leafSize + local np = readi32(b, p) + p =p+ 4 + if np < 0 or np > maxProps then + return nil, "limit: " .. np .. " static props" + end + local out= (table.create(np) ) +if np == 0 then + return out, nil + end + local rec = math.floor((e - p) / np +) if rec < 56 then + return nil, "static prop records shorter than 56 bytes" + end + for i = 0, np - 1 do + local o = p + i * rec + local mi = readu16(b, o + 24) + local scale = { 1, 1, 1 } + if version == 13 and rec >= 88 then + scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) } + elseif (version == 11 or version == 12) and rec >= 80 then + local s = readf32(b, o + rec - 4) + scale = { s, s, s } + end + out[i + 1] = { + model = names[mi + 1] or "", + origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, + angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) }, + scale = scale, + solid = readu8(b, o + 30), + flags = readu8(b, o + 31), + skin = readi32(b, o + 32), + fadeMin = readf32(b, o + 36), + fadeMax = readf32(b, o + 40), + lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) }, + fadeScale = (version >= 5 and rec >= 60 and{(readf32(b, o + 56) )}or{nil})[1], + } + end + return out, nil +end + +return Props +end +__FILES["model/vmf"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush +-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement, +-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in +-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from +-- opts.textureSizes, materials/.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances +-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Build = __include("model/vmf/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Vmf = { + name = "vmf", + category = "model", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + + +function Vmf.sniff(r) +local head = Sniff.text(r, 512, true) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then + return 0.9 + end + if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function sizer(opts) +local cache= {} + return function(name) +local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h, known = 512, 512, false + local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)]) + if given and type(given[1]) == "number" and type(given[2]) == "number" then + w, h, known = given[1], given[2], true + elseif opts and opts.decodeImage then + local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf") + if data then + local ok, img = pcall(opts.decodeImage , data) + if ok and type(img) == "table" and type(img.width) == "number" then + w, h, known = img.width, img.height, true + end + end + end + cache[name] = { w, h, known and 1 or 0 } + return w, h, known + end +end + +function Vmf.parse(src) +return KeyValues.parse(src, { escapes = "quotes", defines = false }) +end + +function Vmf.decode(r, opts) +local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, err + end + local scene, msg = Build.scene(doc, { + tools = opts ~= nil and opts.tools == true, + size = sizer(opts), + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(msg) + end + local vi = KeyValues.get(doc, "versioninfo") + local info= (type(vi) == "table" and{(KeyValues.toObject(vi) )}or{{} +})[1] scene.meta.vmf = doc + scene.meta.source = { + format = "vmf", + editorVersion = tonumber(info.editorversion), + editorBuild = tonumber(info.editorbuild), + mapVersion = tonumber(info.mapversion), + formatVersion = tonumber(info.formatversion), + prefab = info.prefab == "1", + } + return scene, nil +end + +-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world) +function Vmf.brushes(doc) +local out = {} + local entity = 0 + local function walk(b) +for _, p in __iter(b) do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value , entity) + if not s then + return err + end + local faces, mats = {}, {} + for _, sd in __iter(s.sides) do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(mats, sd.material) + end + end + table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats }) + elseif k == "hidden" then + local err = walk(p.value ) + if err then + return err + end + end + end + end + return nil + end + for _, p in __iter(doc) do + local k = string.lower(p.key) + if type(p.value) == "table" and (k == "world" or k == "entity") then + entity =entity+ 1 + local err = walk(p.value ) + if err then + return nil, Err.new(Err.CORRUPT, err) + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Hammer writes dispinfo rows at their block's own indent +local FLAT= {} +for _, k in __iter({ "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" }) do + FLAT[k] = true +end + +function Vmf.encode(value, _opts) +local doc = value + if type(value) == "table" and value.kind == "scene" then + doc = value.meta and value.meta.vmf + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written") + end + end + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document") + end + local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function fmt(x) +if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + return (string.gsub(string.format("%.6f", x), "%.?0+$", "")) +end + +local function kv(k, v) +return { key = k, value = v } +end + +-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls) +local function defaultAxes(points) +local a, b, c = points[1], points[2], points[3] + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx) + if nz >= nx and nz >= ny then + return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 } + elseif nx >= ny then + return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } + end + return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } +end + +local function id(given, default) +return fmt(given or default) +end + +function Vmf.side(s, sideId) +local p = s.points + local du, dv = defaultAxes(p) + local u, v = s.uaxis or du, s.vaxis or dv + local function axis(x) +return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25) + end + local function pt(x) +return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")" + end + return { key = "side", value = { + kv("id", id(sideId, 1)), + kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])), + kv("material", s.material or "TOOLS/TOOLSNODRAW"), + kv("uaxis", axis(u)), + kv("vaxis", axis(v)), + kv("rotation", fmt(s.rotation or 0)), + kv("lightmapscale", fmt(s.lightmapscale or 16)), + kv("smoothing_groups", "0"), + } } +end + +function Vmf.solid(sides, solidId) +local blk= { kv("id", id(solidId, 1)) } + for i, s in __iter(sides) do + table.insert(blk, Vmf.side(s, i)) + end + table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } }) + return { key = "solid", value = blk } +end + +-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north, +-- south) +function Vmf.box(lo, hi, material, solidId) +local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] + local function m(i) +return (type(material) == "table" and{material[i] or material[1] }or{material +})[1] end + return Vmf.solid({ + { points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) }, + { points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) }, + { points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) }, + { points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) }, + { points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) }, + { points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) }, + }, solidId) +end + +-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons +function Vmf.document(worldKeys) +local world= { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") } + if worldKeys then + local keys = {} + for k in __iter(worldKeys) do + table.insert(keys, k) + end + table.sort(keys) + for _, k in __iter(keys) do + table.insert(world, kv(k, worldKeys[k])) + end + end + return { + { key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } }, + { key = "visgroups", value = {} }, + { key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } }, + { key = "world", value = world }, + { key = "cameras", value = { kv("activecamera", "-1") } }, + { key = "cordons", value = { kv("active", "0") } }, + } +end + +-- an entity block (keys in the given order, then its solids) appended to doc before cameras +function Vmf.entity(doc, keys, solids) +local count = 1 + for _, p in __iter(doc) do + if string.lower(p.key) == "entity" then + count =count+ 1 + end + end + local blk= { kv("id", id(nil, count + 1)) } + for _, k in __iter(keys) do + table.insert(blk, kv(k[1], k[2])) + end + for _, s in __iter(solids or {}) do + table.insert(blk, s) + end + local pair = { key = "entity", value = blk } + local at = #doc + 1 + for i, p in __iter(doc) do + if string.lower(p.key) == "cameras" then + at = i + break + end + end + table.insert(doc, at, pair) + return pair +end + +-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...))) +function Vmf.world(doc) +local w = KeyValues.get(doc, "world") + return (type(w) == "table" and{w }or{nil +})[1]end + +return Vmf +end +__FILES["model/vmf/Build"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes +-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one +-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras. +local Types = __include("Types") +local KeyValues = __include("codecs/text/KeyValues") +local Brush = __include("codecs/model/Brush") +local Displacement = __include("codecs/model/Displacement") +local Mat4 = __include("codecs/model/Mat4") + +local Build = {} + + + + + + + + + + + + + + + + + + +local function nums(s) +local out= {} + if type(s) ~= "string" then + return out + end + for w in __iter(string.gmatch(s, "[^%s%(%)%[%]]+")) do + local n = tonumber(w) + if n then + table.insert(out, n) + end + end + return out +end +Build.nums = nums + +local function get(b, key) +return KeyValues.get(b, key) +end + +local function editor(b) +local e = KeyValues.find(b, "editor") + return (e and type(e.value) == "table" and{(KeyValues.toObject(e.value) )}or{nil +})[1]end + +function Build.solid(b, entity) +local sides= {} + for _, p in __iter(KeyValues.all(b, "side")) do + if type(p.value) == "table" then + local sb = p.value +local pts = nums(get(sb, "plane")) + if #pts ~= 9 then + return nil, "side without a 3-point plane" + end + local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis")) + local d = KeyValues.find(sb, "dispinfo") + table.insert(sides, { + id = tonumber(get(sb, "id")), + points = pts, + material = tostring(get(sb, "material") or ""), + uaxis = (#u >= 5 and{u }or{{ 1, 0, 0, 0, 1 }})[1], + vaxis = (#v >= 5 and{v }or{{ 0, -1, 0, 0, 1 }})[1], + disp = (d and type(d.value) == "table" and{d.value }or{nil})[1], + }) + end + end + return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil +end + +function Build.face(s) +local p = s.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) } +end + +local function rows(d, name, per, n) +local blk = KeyValues.get(d, name) + if type(blk) ~= "table" then + return nil + end + local out= (table.create(n * n * per, 0) ) +for i = 0, n - 1 do + local r = nums(KeyValues.get(blk, "row" .. i)) + for k = 1, math.min(#r, n * per) do + out[i * n * per + k] = r[k] + end + end + return out +end + +-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp) + + +local function displace(s, face, poly, acc, w, h) +local d = s.disp +local power = tonumber(KeyValues.get(d, "power")) or 0 + if power < 1 or power > 4 or power % 1 ~= 0 then + return "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + local start = nums(KeyValues.get(d, "startposition")) + if #start < 3 then + return "displacement without a start position" + end + local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n) + local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n) + local elev = tonumber(KeyValues.get(d, "elevation")) or 0 + local pn = face.plane + local offsets= (table.create(n * n * 3, 0) ) +for k = 0, n * n - 1 do + for c = 1, 3 do + local v = elev * pn[c] + if normals and dists then + v =v+ normals[k * 3 + c] * dists[k + 1] + end + if offs then + v =v+ offs[k * 3 + c] + end + offsets[k * 3 + c] = v + end + end + -- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise + local pts = poly.points + local cw= {} + for k = math.floor(#pts / 3 )- 1, 0, -1 do + table.insert(cw, pts[k * 3 + 1]) + table.insert(cw, pts[k * 3 + 2]) + table.insert(cw, pts[k * 3 + 3]) + end + local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] }) + if not surf then + return err + end + local base = math.floor(#acc.pos / 3 +) for k = 0, n * n - 1 do + local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3] + for c = 1, 3 do + table.insert(acc.pos, surf.pos[k * 3 + c]) + table.insert(acc.nrm, surf.nrm[k * 3 + c]) + end + local u, v = Brush.uv(face, x, y, z, w, h) + table.insert(acc.uv, u) + table.insert(acc.uv, v) + table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1)) + end + for _, i in __iter(surf.idx) do + table.insert(acc.idx, base + i) + end + return nil +end + +local function isTool(name) +return string.sub(string.lower(name), 1, 6) == "tools/" +end + +-- the solids of one entity -> its primitives (material indices by name through matOf) +function Build.mesh(solids, o, matOf, name) +local brushes= {} + local sideOf= {} + local hasDisp= {} + for _, s in __iter(solids) do + local faces= {} + local sides= {} + local disp = false + for _, sd in __iter(s.sides) do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(sides, sd) + disp = disp or sd.disp ~= nil + end + end + if #faces >= 4 then + table.insert(brushes, faces) + table.insert(sideOf, sides) + table.insert(hasDisp, disp) + end + end + local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons }) + if not polys then + return nil, perr + end + local keep= {} + local disps= {} + local dispOrder= {} + for _, p in __iter(polys) do + local sd = sideOf[p.brush][p.face] + if o.tools or not isTool(sd.material) then + if sd.disp then + local acc = disps[sd.material] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} } + disps[sd.material] = acc + table.insert(dispOrder, sd.material) + end + local w, h = o.size(sd.material) + local err = displace(sd, brushes[p.brush][p.face], p, acc , w, h) + if err then + return nil, err + end + elseif not hasDisp[p.brush] then + table.insert(keep, p) + end + end + end + local mesh= { name = name, primitives = {} } + local function size(n) +local w, h = o.size(n) + return w, h + end + for _, b in __iter(Brush.primitives(keep, brushes, size)) do + b.primitive.material = matOf(b.texture) + table.insert(mesh.primitives, b.primitive) + end + for _, m in __iter(dispOrder) do + local prim = Displacement.primitive(disps[m] ) + prim.material = matOf(m) + table.insert(mesh.primitives, prim) + end + return mesh, nil +end + +local function quat(p, y, r) +return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +-- a camera at position looking at look, z up: glTF cameras look along -z with +y up +local function lookAt(pos, look) +local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3] + local l = math.sqrt(fx * fx + fy * fy + fz * fz) + if l < 1e-9 then + return { 0, 0, 0, 1 } + end + fx, fy, fz = fx / l, fy / l, fz / l + local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1) + local rl = math.sqrt(rx * rx + ry * ry) + if rl < 1e-9 then + rx, ry, rl = 1, 0, 1 + end + rx, ry = rx / rl, ry / rl + local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f + return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +local function visgroups(b) +local out = {} + for _, p in __iter(KeyValues.all(b, "visgroup")) do + if type(p.value) == "table" then + local v = p.value +table.insert(out, { + name = KeyValues.get(v, "name"), + id = tonumber(KeyValues.get(v, "visgroupid")), + color = KeyValues.get(v, "color"), + children = visgroups(v), + }) + end + end + return out +end + +-- solids of a block, including those inside its hidden { } blocks +local function solidsOf(b, entity, out) +for _, p in __iter(b) do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value , entity) + if not s then + return err + end + table.insert(out, s) + elseif k == "hidden" then + local err = solidsOf(p.value , entity, out) + if err then + return err + end + end + end + end + return nil +end + +function Build.scene(doc, o) +local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + local mats= {} + local function matOf(name) +local m = mats[name] + if m then + return m + end + local w, h, known = o.size(name) + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + table.insert(scene.textures, { name = name, uri = path .. ".vtf" }) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + mats[name] = #scene.materials + return #scene.materials + end + local root= { name = "vmf", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local ents= {} + local solidsMeta= {} + local groups= {} + -- world and entities, hidden ones included + local blocks= {} + for _, p in __iter(doc) do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "world" or k == "entity" then + table.insert(blocks, { key = k, block = p.value }) + elseif k == "hidden" then + for _, q in __iter(KeyValues.all(p.value , "entity")) do + if type(q.value) == "table" then + table.insert(blocks, { key = "entity", block = q.value }) + end + end + end + end + end + for _, item in __iter(blocks) do + local b = item.block + local keys= {} + local conns= nil + for _, p in __iter(b) do + if type(p.value) == "string" then + table.insert(keys, p) + elseif string.lower(p.key) == "connections" then + conns = KeyValues.toObject(p.value ) + elseif item.key == "world" and string.lower(p.key) == "group" then + local g = p.value +table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) }) + end + end + local e = KeyValues.toObject(keys) + if conns then + e.connections = conns + end + table.insert(ents, e) + local ei = #ents + local solids= {} + local serr = solidsOf(b, ei, solids) + if serr then + return nil, serr + end + local class = (type(e.classname) == "string" and{e.classname }or{item.key +})[1] local name = item.key == "world" and"world" or(type(e.targetname) == "string" and{e.targetname }or{class +})[1] local node= { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } } + if #solids > 0 then + local mesh, merr = Build.mesh(solids, o, matOf, name) + if not mesh then + return nil, merr + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + for _, s in __iter(solids) do + table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor }) + end + else + local org = nums(e.origin) + if #org >= 3 then + node.translation = { org[1], org[2], org[3] } + end + local ang = nums(e.angles) + if #ang >= 3 then + node.rotation = quat(ang[1], ang[2], ang[3]) + end + if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then + (node.extras ).model = e.model + end + end + if node.mesh or item.key ~= "world" then + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + end + -- cameras + local cams = KeyValues.get(doc, "cameras") + local camMeta= nil + if type(cams) == "table" then + camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} } + for _, p in __iter(KeyValues.all(cams, "camera")) do + if type(p.value) == "table" then + local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look")) + if #pos >= 3 and #look >= 3 then + local cam= { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 } + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) }) + table.insert(root.children, #scene.nodes) + table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } }) + end + end + end + end + local vg = KeyValues.get(doc, "visgroups") + scene.meta.entities = ents + scene.meta.solids = solidsMeta + scene.meta.groups = groups + scene.meta.visgroups = (type(vg) == "table" and{(visgroups(vg) )}or{{} +})[1] scene.meta.cameras = camMeta + return scene, nil +end + +return Build +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 (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index 29fc188..c0582dd 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -1,553 +1,566 @@ [ [660, "src/Rosetta/init.luau"], [1504, "src/Rosetta/Registry.luau"], -[3661, "src/Rosetta/Types.luau"], -[4744, "src/Rosetta/archive/7z/init.luau"], -[5129, "src/Rosetta/archive/7z/Header.luau"], -[5656, "src/Rosetta/archive/adf/init.luau"], -[5938, "src/Rosetta/archive/applesingle/init.luau"], -[6124, "src/Rosetta/archive/ar/init.luau"], -[6527, "src/Rosetta/archive/arj/init.luau"], -[6737, "src/Rosetta/archive/binhex/init.luau"], -[6986, "src/Rosetta/archive/br/init.luau"], -[7061, "src/Rosetta/archive/bz2/init.luau"], -[7125, "src/Rosetta/archive/cab/init.luau"], -[7538, "src/Rosetta/archive/cab/Sum.luau"], -[7579, "src/Rosetta/archive/cpio/init.luau"], -[7747, "src/Rosetta/archive/d64/init.luau"], -[8161, "src/Rosetta/archive/fat/init.luau"], -[8283, "src/Rosetta/archive/grp/init.luau"], -[8397, "src/Rosetta/archive/gzip/init.luau"], -[8582, "src/Rosetta/archive/iso/init.luau"], -[8654, "src/Rosetta/archive/lha/init.luau"], -[9079, "src/Rosetta/archive/lz4/init.luau"], -[9423, "src/Rosetta/archive/macbinary/init.luau"], -[9621, "src/Rosetta/archive/mpq/init.luau"], -[10027, "src/Rosetta/archive/mpq/Crypt.luau"], -[10092, "src/Rosetta/archive/pak/init.luau"], -[10226, "src/Rosetta/archive/rpm/init.luau"], -[10550, "src/Rosetta/archive/tar/init.luau"], -[10668, "src/Rosetta/archive/uu/init.luau"], -[10938, "src/Rosetta/archive/vpk/init.luau"], -[11249, "src/Rosetta/archive/wad/init.luau"], -[11699, "src/Rosetta/archive/wad/Map.luau"], -[12129, "src/Rosetta/archive/wad/Picture.luau"], -[12231, "src/Rosetta/archive/xz/init.luau"], -[12331, "src/Rosetta/archive/yenc/init.luau"], -[12603, "src/Rosetta/archive/z/init.luau"], -[12699, "src/Rosetta/archive/zip/init.luau"], -[12918, "src/Rosetta/archive/zoo/init.luau"], -[13114, "src/Rosetta/archive/zst/init.luau"], -[13178, "src/Rosetta/audio/aac/init.luau"], -[13384, "src/Rosetta/audio/ac3/init.luau"], -[13530, "src/Rosetta/audio/adpcm/init.luau"], -[13675, "src/Rosetta/audio/adx/init.luau"], -[13906, "src/Rosetta/audio/aiff/init.luau"], -[14297, "src/Rosetta/audio/ape/init.luau"], -[14425, "src/Rosetta/audio/au/init.luau"], -[14586, "src/Rosetta/audio/brstm/init.luau"], -[14877, "src/Rosetta/audio/caf/init.luau"], -[15539, "src/Rosetta/audio/flac/init.luau"], -[15687, "src/Rosetta/audio/flac/Meta.luau"], -[15909, "src/Rosetta/audio/flac/Stream.luau"], -[16279, "src/Rosetta/audio/m4a/init.luau"], -[16613, "src/Rosetta/audio/mp3/init.luau"], -[16873, "src/Rosetta/audio/mp3/Index.luau"], -[17064, "src/Rosetta/audio/mp3/Stream.luau"], -[17291, "src/Rosetta/audio/mp3/Tags.luau"], -[17603, "src/Rosetta/audio/mpc/init.luau"], -[17697, "src/Rosetta/audio/opus/init.luau"], -[18075, "src/Rosetta/audio/opus/Encode.luau"], -[18186, "src/Rosetta/audio/qoa/init.luau"], -[18366, "src/Rosetta/audio/tta/init.luau"], -[18484, "src/Rosetta/audio/vag/init.luau"], -[18707, "src/Rosetta/audio/voc/init.luau"], -[18982, "src/Rosetta/audio/vorbis/init.luau"], -[19436, "src/Rosetta/audio/vorbis/Encode.luau"], -[20249, "src/Rosetta/audio/wav/init.luau"], -[20870, "src/Rosetta/audio/wav/Codecs.luau"], -[21036, "src/Rosetta/audio/wavpack/init.luau"], -[21243, "src/Rosetta/cad/step/init.luau"], -[21625, "src/Rosetta/cad/step/Brep.luau"], -[21860, "src/Rosetta/cad/step/Parse.luau"], -[22417, "src/Rosetta/cad/step/Write.luau"], -[22665, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22984, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23867, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24202, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24361, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25246, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25347, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26101, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26403, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26637, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27056, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27468, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27683, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28444, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28541, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28552, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29501, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30098, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30294, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30543, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31501, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31720, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31904, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32113, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32459, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32473, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32532, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34135, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34427, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34812, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35453, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35594, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35820, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36165, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[37059, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37437, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37451, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39298, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40363, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40423, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40883, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41220, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41453, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43489, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43863, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44126, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44423, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44705, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45064, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45118, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45261, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45774, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46555, "src/Rosetta/codecs/audio/Stream.luau"], -[46716, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47198, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47476, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47645, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47773, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49761, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49877, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49994, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50246, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50259, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50643, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51209, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51630, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51669, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51721, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51943, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53398, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53461, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53548, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54517, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55385, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55433, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55949, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56275, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56695, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57130, "src/Rosetta/codecs/compress/Explode.luau"], -[57326, "src/Rosetta/codecs/compress/Lz4.luau"], -[57595, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58199, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58739, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58777, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59250, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59426, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59694, "src/Rosetta/codecs/compress/Lzx.luau"], -[60128, "src/Rosetta/codecs/compress/PackBits.luau"], -[60218, "src/Rosetta/codecs/compress/Quantum.luau"], -[60455, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60759, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60828, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60885, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61843, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61995, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62277, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62288, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62502, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62746, "src/Rosetta/codecs/font/Bitmap.luau"], -[62947, "src/Rosetta/codecs/font/Cff/init.luau"], -[63588, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63738, "src/Rosetta/codecs/font/TrueType/init.luau"], -[64052, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64444, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64946, "src/Rosetta/codecs/image/Bcn/init.luau"], -[65053, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65542, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65971, "src/Rosetta/codecs/image/Blend.luau"], -[66350, "src/Rosetta/codecs/image/Dct/init.luau"], -[66731, "src/Rosetta/codecs/image/Etc.luau"], -[67029, "src/Rosetta/codecs/image/Half.luau"], -[67098, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67452, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67860, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68097, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68857, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69738, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70184, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70262, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70329, "src/Rosetta/codecs/image/Pixels.luau"], -[70593, "src/Rosetta/codecs/image/Quantize/init.luau"], -[71052, "src/Rosetta/codecs/image/Raster.luau"], -[71749, "src/Rosetta/codecs/image/Texel.luau"], -[72122, "src/Rosetta/codecs/image/Texture.luau"], -[72267, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72397, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74353, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74612, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74861, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74980, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75084, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75937, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76889, "src/Rosetta/codecs/image/Yuv.luau"], -[77157, "src/Rosetta/codecs/model/Draco/init.luau"], -[77489, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77958, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79147, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[79296, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79655, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80617, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81091, "src/Rosetta/codecs/model/Mat4.luau"], -[81350, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81878, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[82430, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82509, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82616, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82822, "src/Rosetta/codecs/model/Polygon.luau"], -[83056, "src/Rosetta/codecs/model/Rbx/init.luau"], -[83293, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[84047, "src/Rosetta/codecs/model/Rig.luau"], -[84290, "src/Rosetta/codecs/model/Sampler.luau"], -[84450, "src/Rosetta/codecs/model/SourceAnim.luau"], -[84671, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84819, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85393, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[85556, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86305, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86827, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[87554, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87786, "src/Rosetta/codecs/text/Json/init.luau"], -[88055, "src/Rosetta/codecs/text/Json/Decode.luau"], -[88469, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88771, "src/Rosetta/codecs/text/KeyValues/init.luau"], -[89328, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], -[89633, "src/Rosetta/codecs/text/Nbt/init.luau"], -[89986, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[90678, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[91318, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[91556, "src/Rosetta/codecs/text/Text/init.luau"], -[91647, "src/Rosetta/codecs/text/Url/init.luau"], -[91852, "src/Rosetta/codecs/text/Xml/init.luau"], -[92255, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[92995, "src/Rosetta/codecs/video/Dsp.luau"], -[93718, "src/Rosetta/codecs/video/H263/init.luau"], -[93874, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[94732, "src/Rosetta/codecs/video/H263/Tables.luau"], -[94935, "src/Rosetta/codecs/video/H264/init.luau"], -[95308, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[95583, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[96714, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[97482, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[97740, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[98749, "src/Rosetta/codecs/video/H264/Inter.luau"], -[99003, "src/Rosetta/codecs/video/H264/Intra.luau"], -[99410, "src/Rosetta/codecs/video/H264/Mb.luau"], -[100316, "src/Rosetta/codecs/video/H264/Params.luau"], -[100763, "src/Rosetta/codecs/video/H264/Slice.luau"], -[101014, "src/Rosetta/codecs/video/H264/Tables.luau"], -[101055, "src/Rosetta/codecs/video/H264/Transform.luau"], -[101220, "src/Rosetta/codecs/video/Legacy/init.luau"], -[101418, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[101715, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[102082, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[102200, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[102308, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[102581, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[102976, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[103153, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[103165, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[103532, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[105039, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[105178, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[105316, "src/Rosetta/codecs/video/Theora/init.luau"], -[105579, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[106843, "src/Rosetta/codecs/video/Theora/Header.luau"], -[107206, "src/Rosetta/codecs/video/Video/init.luau"], -[107763, "src/Rosetta/codecs/video/Video/Source.luau"], -[108048, "src/Rosetta/containers/Archive.luau"], -[108315, "src/Rosetta/containers/AudioWrap.luau"], -[108818, "src/Rosetta/containers/Avi/init.luau"], -[109370, "src/Rosetta/containers/Chunks.luau"], -[109505, "src/Rosetta/containers/Cpio.luau"], -[109933, "src/Rosetta/containers/Demux.luau"], -[110208, "src/Rosetta/containers/Ebml/init.luau"], -[110521, "src/Rosetta/containers/Fat.luau"], -[111209, "src/Rosetta/containers/Iso9660.luau"], -[111714, "src/Rosetta/containers/IsoBmff/init.luau"], -[111884, "src/Rosetta/containers/IsoBmff/Box.luau"], -[112072, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[112917, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[113438, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[113954, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[114071, "src/Rosetta/containers/MacFile.luau"], -[114220, "src/Rosetta/containers/MpegEs.luau"], -[114386, "src/Rosetta/containers/MpegPs/init.luau"], -[114606, "src/Rosetta/containers/MpegTs/init.luau"], -[115398, "src/Rosetta/containers/Ogg/init.luau"], -[115823, "src/Rosetta/containers/Ogg/Mux.luau"], -[116018, "src/Rosetta/containers/Ogg/Page.luau"], -[116187, "src/Rosetta/containers/Riff/init.luau"], -[116504, "src/Rosetta/containers/Tar.luau"], -[116918, "src/Rosetta/containers/Zip/init.luau"], -[117550, "src/Rosetta/core/Adler32.luau"], -[117596, "src/Rosetta/core/Base64.luau"], -[117755, "src/Rosetta/core/Bits.luau"], -[118048, "src/Rosetta/core/Bytes.luau"], -[118575, "src/Rosetta/core/Crc16.luau"], -[118627, "src/Rosetta/core/Crc32.luau"], -[118739, "src/Rosetta/core/Err.luau"], -[118821, "src/Rosetta/core/Input.luau"], -[118897, "src/Rosetta/core/Md5.luau"], -[119056, "src/Rosetta/core/Sniff.luau"], -[119085, "src/Rosetta/data/cbor/init.luau"], -[119184, "src/Rosetta/data/cbor/Codec.luau"], -[119753, "src/Rosetta/data/csv/init.luau"], -[120065, "src/Rosetta/data/ini/init.luau"], -[120311, "src/Rosetta/data/json/init.luau"], -[120403, "src/Rosetta/data/msgpack/init.luau"], -[120492, "src/Rosetta/data/msgpack/Codec.luau"], -[120934, "src/Rosetta/data/nbt/init.luau"], -[120993, "src/Rosetta/data/plist/init.luau"], -[121299, "src/Rosetta/data/plist/Binary.luau"], -[121566, "src/Rosetta/data/snbt/init.luau"], -[121629, "src/Rosetta/data/toml/init.luau"], -[121696, "src/Rosetta/data/toml/Decode.luau"], -[122324, "src/Rosetta/data/toml/Encode.luau"], -[122533, "src/Rosetta/data/vdf/init.luau"], -[122634, "src/Rosetta/data/xml/init.luau"], -[122690, "src/Rosetta/data/yaml/init.luau"], -[122763, "src/Rosetta/data/yaml/Emit.luau"], -[123053, "src/Rosetta/data/yaml/Parse.luau"], -[124346, "src/Rosetta/font/bdf/init.luau"], -[124635, "src/Rosetta/font/bmfont/init.luau"], -[125062, "src/Rosetta/font/bmfont/Parse.luau"], -[125515, "src/Rosetta/font/eot/init.luau"], -[125747, "src/Rosetta/font/fon/init.luau"], -[126030, "src/Rosetta/font/hershey/init.luau"], -[126225, "src/Rosetta/font/pcf/init.luau"], -[126505, "src/Rosetta/font/psf/init.luau"], -[126825, "src/Rosetta/font/ttf/init.luau"], -[126876, "src/Rosetta/font/type1/init.luau"], -[127235, "src/Rosetta/font/type1/Charstring.luau"], -[127513, "src/Rosetta/font/woff/init.luau"], -[127645, "src/Rosetta/font/woff2/init.luau"], -[127702, "src/Rosetta/font/woff2/Rebuild.luau"], -[128242, "src/Rosetta/host/init.luau"], -[128287, "src/Rosetta/host/Love.luau"], -[128430, "src/Rosetta/host/LuaJIT.luau"], -[128480, "src/Rosetta/host/Luau.luau"], -[128503, "src/Rosetta/host/Roblox.luau"], -[128862, "src/Rosetta/image/ani/init.luau"], -[129042, "src/Rosetta/image/art/init.luau"], -[129530, "src/Rosetta/image/blp/init.luau"], -[129788, "src/Rosetta/image/bmp/init.luau"], -[130203, "src/Rosetta/image/dds/init.luau"], -[130686, "src/Rosetta/image/exr/init.luau"], -[131446, "src/Rosetta/image/exr/Codec.luau"], -[131557, "src/Rosetta/image/exr/Piz.luau"], -[131914, "src/Rosetta/image/gif/init.luau"], -[132430, "src/Rosetta/image/gif/Decode.luau"], -[132493, "src/Rosetta/image/hdr/init.luau"], -[132722, "src/Rosetta/image/hdr/Codec.luau"], -[132933, "src/Rosetta/image/icns/init.luau"], -[133264, "src/Rosetta/image/ico/init.luau"], -[133541, "src/Rosetta/image/ico/Dib.luau"], -[133636, "src/Rosetta/image/ilbm/init.luau"], -[133955, "src/Rosetta/image/jpeg/init.luau"], -[134091, "src/Rosetta/image/ktx/init.luau"], -[134751, "src/Rosetta/image/pcx/init.luau"], -[135015, "src/Rosetta/image/png/init.luau"], -[135595, "src/Rosetta/image/png/Apng.luau"], -[135675, "src/Rosetta/image/png/Decode.luau"], -[135915, "src/Rosetta/image/png/Encode.luau"], -[136070, "src/Rosetta/image/pnm/init.luau"], -[136448, "src/Rosetta/image/pnm/Codec.luau"], -[136725, "src/Rosetta/image/qoi/init.luau"], -[136847, "src/Rosetta/image/qoi/Codec.luau"], -[136997, "src/Rosetta/image/sgi/init.luau"], -[137282, "src/Rosetta/image/sunras/init.luau"], -[137528, "src/Rosetta/image/tga/init.luau"], -[137798, "src/Rosetta/image/tga/Codec.luau"], -[137950, "src/Rosetta/image/tiff/init.luau"], -[138777, "src/Rosetta/image/tiff/Pixels.luau"], -[139167, "src/Rosetta/image/tim/init.luau"], -[139409, "src/Rosetta/image/vtf/init.luau"], -[139644, "src/Rosetta/image/webp/init.luau"], -[140254, "src/Rosetta/image/webp/Alpha.luau"], -[140330, "src/Rosetta/image/webp/Anim.luau"], -[140485, "src/Rosetta/image/xbm/init.luau"], -[140646, "src/Rosetta/image/xpm/init.luau"], -[140914, "src/Rosetta/image/xpm/Names.luau"], -[140970, "src/Rosetta/layered/aseprite/init.luau"], -[141708, "src/Rosetta/layered/ora/init.luau"], -[141995, "src/Rosetta/layered/psd/init.luau"], -[142730, "src/Rosetta/layered/psd/Channels.luau"], -[143082, "src/Rosetta/model/3ds/init.luau"], -[143165, "src/Rosetta/model/3ds/Build.luau"], -[143812, "src/Rosetta/model/3ds/Read.luau"], -[144308, "src/Rosetta/model/3ds/Write.luau"], -[145113, "src/Rosetta/model/3mf/init.luau"], -[145195, "src/Rosetta/model/3mf/Read.luau"], -[145783, "src/Rosetta/model/3mf/Write.luau"], -[146188, "src/Rosetta/model/b3d/init.luau"], -[146243, "src/Rosetta/model/b3d/Read.luau"], -[146814, "src/Rosetta/model/bsp/init.luau"], -[146959, "src/Rosetta/model/bsp/Brush.luau"], -[147237, "src/Rosetta/model/bsp/Quake3.luau"], -[147492, "src/Rosetta/model/buildmap/init.luau"], -[147764, "src/Rosetta/model/buildmap/Geometry.luau"], -[148167, "src/Rosetta/model/dae/init.luau"], -[148356, "src/Rosetta/model/dae/Math.luau"], -[148403, "src/Rosetta/model/dae/Read.luau"], -[150253, "src/Rosetta/model/dae/Write.luau"], -[150622, "src/Rosetta/model/fbx/init.luau"], -[150770, "src/Rosetta/model/fbx/Ascii.luau"], -[151040, "src/Rosetta/model/fbx/Binary.luau"], -[151495, "src/Rosetta/model/fbx/Read.luau"], -[152857, "src/Rosetta/model/fbx/Write.luau"], -[153842, "src/Rosetta/model/fbx/Xform.luau"], -[153883, "src/Rosetta/model/gltf/init.luau"], -[154120, "src/Rosetta/model/gltf/Pack.luau"], -[154189, "src/Rosetta/model/gltf/Read.luau"], -[154920, "src/Rosetta/model/gltf/Write.luau"], -[155600, "src/Rosetta/model/iqm/init.luau"], -[155676, "src/Rosetta/model/iqm/Read.luau"], -[156031, "src/Rosetta/model/iqm/Write.luau"], -[156718, "src/Rosetta/model/ldraw/init.luau"], -[156796, "src/Rosetta/model/ldraw/Colors.luau"], -[157114, "src/Rosetta/model/ldraw/Read.luau"], -[157691, "src/Rosetta/model/lwo/init.luau"], -[157767, "src/Rosetta/model/lwo/Build.luau"], -[158229, "src/Rosetta/model/lwo/Parse.luau"], -[158772, "src/Rosetta/model/mca/init.luau"], -[159114, "src/Rosetta/model/mca/Chunk.luau"], -[159247, "src/Rosetta/model/mca/Lz4Block.luau"], -[159317, "src/Rosetta/model/md2/init.luau"], -[159516, "src/Rosetta/model/md3/init.luau"], -[159744, "src/Rosetta/model/md5/init.luau"], -[159825, "src/Rosetta/model/md5/Read.luau"], -[160258, "src/Rosetta/model/mdl/init.luau"], -[160340, "src/Rosetta/model/mdl/HalfLife.luau"], -[160644, "src/Rosetta/model/mdl/Quake.luau"], -[160862, "src/Rosetta/model/ms3d/init.luau"], -[160934, "src/Rosetta/model/ms3d/Read.luau"], -[161380, "src/Rosetta/model/ms3d/Write.luau"], -[161849, "src/Rosetta/model/obj/init.luau"], -[162591, "src/Rosetta/model/obj/Mtl.luau"], -[162878, "src/Rosetta/model/off/init.luau"], -[163340, "src/Rosetta/model/ply/init.luau"], -[164445, "src/Rosetta/model/ply/Binary.luau"], -[164646, "src/Rosetta/model/pmx/init.luau"], -[164715, "src/Rosetta/model/pmx/Build.luau"], -[165011, "src/Rosetta/model/pmx/Pmd.luau"], -[165346, "src/Rosetta/model/pmx/Read.luau"], -[165750, "src/Rosetta/model/qb/init.luau"], -[166143, "src/Rosetta/model/rbxm/init.luau"], -[166735, "src/Rosetta/model/rbxmx/init.luau"], -[167388, "src/Rosetta/model/robloxmesh/init.luau"], -[168047, "src/Rosetta/model/robloxmesh/Parse.luau"], -[168504, "src/Rosetta/model/robloxmesh/Write.luau"], -[168613, "src/Rosetta/model/schematic/init.luau"], -[168934, "src/Rosetta/model/schematic/Common.luau"], -[169054, "src/Rosetta/model/schematic/Litematic.luau"], -[169265, "src/Rosetta/model/schematic/Mcedit.luau"], -[169509, "src/Rosetta/model/schematic/Sponge.luau"], -[169638, "src/Rosetta/model/smd/init.luau"], -[169705, "src/Rosetta/model/smd/Read.luau"], -[169974, "src/Rosetta/model/smd/Write.luau"], -[170217, "src/Rosetta/model/sourcemdl/init.luau"], -[170388, "src/Rosetta/model/sourcemdl/Build.luau"], -[170818, "src/Rosetta/model/sourcemdl/Material.luau"], -[170979, "src/Rosetta/model/sourcemdl/Mdl.luau"], -[171506, "src/Rosetta/model/sourcemdl/Phy.luau"], -[171629, "src/Rosetta/model/sourcemdl/Vtx.luau"], -[171811, "src/Rosetta/model/sourcemdl/Vvd.luau"], -[171905, "src/Rosetta/model/stl/init.luau"], -[172355, "src/Rosetta/model/stl/Decode.luau"], -[172429, "src/Rosetta/model/usda/init.luau"], -[172638, "src/Rosetta/model/usda/Build.luau"], -[173916, "src/Rosetta/model/usda/Parse.luau"], -[174714, "src/Rosetta/model/usda/Write.luau"], -[175531, "src/Rosetta/model/vox/init.luau"], -[176417, "src/Rosetta/model/vox/Grid.luau"], -[176474, "src/Rosetta/model/vrml/init.luau"], -[176540, "src/Rosetta/model/x/init.luau"], -[176670, "src/Rosetta/model/x/Build.luau"], -[177233, "src/Rosetta/model/x/Parse.luau"], -[177530, "src/Rosetta/model/x3d/init.luau"], -[177608, "src/Rosetta/music/669/init.luau"], -[177814, "src/Rosetta/music/ahx/init.luau"], -[177865, "src/Rosetta/music/far/init.luau"], -[178094, "src/Rosetta/music/hmp/init.luau"], -[178358, "src/Rosetta/music/hvl/init.luau"], -[178409, "src/Rosetta/music/it/init.luau"], -[178827, "src/Rosetta/music/it/Itsex.luau"], -[178943, "src/Rosetta/music/med/init.luau"], -[179590, "src/Rosetta/music/midi/init.luau"], -[179733, "src/Rosetta/music/midi/Smf.luau"], -[180144, "src/Rosetta/music/mod/init.luau"], -[180497, "src/Rosetta/music/mtm/init.luau"], -[180719, "src/Rosetta/music/mus/init.luau"], -[180876, "src/Rosetta/music/okt/init.luau"], -[181157, "src/Rosetta/music/ptm/init.luau"], -[181379, "src/Rosetta/music/s3m/init.luau"], -[181615, "src/Rosetta/music/sf2/init.luau"], -[181658, "src/Rosetta/music/stm/init.luau"], -[181889, "src/Rosetta/music/ult/init.luau"], -[182193, "src/Rosetta/music/umx/init.luau"], -[182409, "src/Rosetta/music/xm/init.luau"], -[182970, "src/Rosetta/music/xmi/init.luau"], -[183178, "src/Rosetta/ops/AudioOps.luau"], -[183627, "src/Rosetta/ops/ImageOps/init.luau"], -[184271, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[184781, "src/Rosetta/ops/LayerOps.luau"], -[184874, "src/Rosetta/ops/MeshOps/init.luau"], -[185910, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[186077, "src/Rosetta/ops/MusicOps.luau"], -[186425, "src/Rosetta/playlist/m3u/init.luau"], -[186778, "src/Rosetta/playlist/pls/init.luau"], -[186956, "src/Rosetta/playlist/xspf/init.luau"], -[187159, "src/Rosetta/subtitle/ass/init.luau"], -[187603, "src/Rosetta/subtitle/srt/init.luau"], -[187776, "src/Rosetta/subtitle/vtt/init.luau"], -[187979, "src/Rosetta/vector/svg/init.luau"], -[188065, "src/Rosetta/vector/svg/Parse.luau"], -[188811, "src/Rosetta/vector/svg/PathData.luau"], -[189179, "src/Rosetta/vector/svg/Render.luau"], -[189596, "src/Rosetta/vector/svg/Style.luau"], -[189968, "src/Rosetta/vector/svg/Write.luau"], -[190168, "src/Rosetta/vector/tiled/init.luau"], -[190348, "src/Rosetta/vector/tiled/Data.luau"], -[190499, "src/Rosetta/vector/tiled/Tmj.luau"], -[191130, "src/Rosetta/vector/tiled/Tmx.luau"], -[191742, "src/Rosetta/video/avi/init.luau"], -[192036, "src/Rosetta/video/fli/init.luau"], -[192187, "src/Rosetta/video/flv/init.luau"], -[192571, "src/Rosetta/video/flv/Amf.luau"], -[192729, "src/Rosetta/video/flv/Mux.luau"], -[193010, "src/Rosetta/video/h264/init.luau"], -[193149, "src/Rosetta/video/mkv/init.luau"], -[193305, "src/Rosetta/video/mkv/Mux.luau"], -[193584, "src/Rosetta/video/mkv/Parse.luau"], -[194305, "src/Rosetta/video/mp4/init.luau"], -[194633, "src/Rosetta/video/mpegps/init.luau"], -[194820, "src/Rosetta/video/mpegts/init.luau"], -[195058, "src/Rosetta/video/ogv/init.luau"], -[195453, "src/Rosetta/video/smk/init.luau"], -[195762, "src/Rosetta/video/smk/Audio.luau"], -[195882, "src/Rosetta/video/y4m/init.luau"] +[3697, "src/Rosetta/Types.luau"], +[4780, "src/Rosetta/archive/7z/init.luau"], +[5165, "src/Rosetta/archive/7z/Header.luau"], +[5692, "src/Rosetta/archive/adf/init.luau"], +[5974, "src/Rosetta/archive/applesingle/init.luau"], +[6160, "src/Rosetta/archive/ar/init.luau"], +[6563, "src/Rosetta/archive/arj/init.luau"], +[6773, "src/Rosetta/archive/binhex/init.luau"], +[7022, "src/Rosetta/archive/br/init.luau"], +[7097, "src/Rosetta/archive/bz2/init.luau"], +[7161, "src/Rosetta/archive/cab/init.luau"], +[7574, "src/Rosetta/archive/cab/Sum.luau"], +[7615, "src/Rosetta/archive/cpio/init.luau"], +[7783, "src/Rosetta/archive/d64/init.luau"], +[8197, "src/Rosetta/archive/fat/init.luau"], +[8319, "src/Rosetta/archive/grp/init.luau"], +[8433, "src/Rosetta/archive/gzip/init.luau"], +[8618, "src/Rosetta/archive/iso/init.luau"], +[8690, "src/Rosetta/archive/lha/init.luau"], +[9115, "src/Rosetta/archive/lz4/init.luau"], +[9459, "src/Rosetta/archive/macbinary/init.luau"], +[9657, "src/Rosetta/archive/mpq/init.luau"], +[10063, "src/Rosetta/archive/mpq/Crypt.luau"], +[10128, "src/Rosetta/archive/pak/init.luau"], +[10262, "src/Rosetta/archive/rpm/init.luau"], +[10586, "src/Rosetta/archive/tar/init.luau"], +[10704, "src/Rosetta/archive/uu/init.luau"], +[10974, "src/Rosetta/archive/vpk/init.luau"], +[11285, "src/Rosetta/archive/wad/init.luau"], +[11735, "src/Rosetta/archive/wad/Map.luau"], +[12165, "src/Rosetta/archive/wad/Picture.luau"], +[12267, "src/Rosetta/archive/xz/init.luau"], +[12367, "src/Rosetta/archive/yenc/init.luau"], +[12639, "src/Rosetta/archive/z/init.luau"], +[12735, "src/Rosetta/archive/zip/init.luau"], +[12954, "src/Rosetta/archive/zoo/init.luau"], +[13150, "src/Rosetta/archive/zst/init.luau"], +[13214, "src/Rosetta/audio/aac/init.luau"], +[13420, "src/Rosetta/audio/ac3/init.luau"], +[13566, "src/Rosetta/audio/adpcm/init.luau"], +[13711, "src/Rosetta/audio/adx/init.luau"], +[13942, "src/Rosetta/audio/aiff/init.luau"], +[14333, "src/Rosetta/audio/ape/init.luau"], +[14461, "src/Rosetta/audio/au/init.luau"], +[14622, "src/Rosetta/audio/brstm/init.luau"], +[14913, "src/Rosetta/audio/caf/init.luau"], +[15575, "src/Rosetta/audio/flac/init.luau"], +[15723, "src/Rosetta/audio/flac/Meta.luau"], +[15945, "src/Rosetta/audio/flac/Stream.luau"], +[16315, "src/Rosetta/audio/m4a/init.luau"], +[16649, "src/Rosetta/audio/mp3/init.luau"], +[16909, "src/Rosetta/audio/mp3/Index.luau"], +[17100, "src/Rosetta/audio/mp3/Stream.luau"], +[17327, "src/Rosetta/audio/mp3/Tags.luau"], +[17639, "src/Rosetta/audio/mpc/init.luau"], +[17733, "src/Rosetta/audio/opus/init.luau"], +[18111, "src/Rosetta/audio/opus/Encode.luau"], +[18222, "src/Rosetta/audio/qoa/init.luau"], +[18402, "src/Rosetta/audio/tta/init.luau"], +[18520, "src/Rosetta/audio/vag/init.luau"], +[18743, "src/Rosetta/audio/voc/init.luau"], +[19018, "src/Rosetta/audio/vorbis/init.luau"], +[19472, "src/Rosetta/audio/vorbis/Encode.luau"], +[20285, "src/Rosetta/audio/wav/init.luau"], +[20906, "src/Rosetta/audio/wav/Codecs.luau"], +[21072, "src/Rosetta/audio/wavpack/init.luau"], +[21279, "src/Rosetta/cad/step/init.luau"], +[21661, "src/Rosetta/cad/step/Brep.luau"], +[21896, "src/Rosetta/cad/step/Parse.luau"], +[22453, "src/Rosetta/cad/step/Write.luau"], +[22701, "src/Rosetta/codecs/audio/Aac/init.luau"], +[23020, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23903, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24238, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24397, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25282, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25383, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26137, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26439, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26673, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27092, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27504, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27719, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28480, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28577, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28588, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29537, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30134, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30330, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30579, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31537, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31756, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31940, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32149, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32495, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32509, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32568, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34171, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34463, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34848, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35489, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35630, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35856, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36201, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37095, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37473, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37487, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39334, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40399, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40459, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40919, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41256, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41489, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43525, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43899, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44162, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44459, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44741, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45100, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45154, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45297, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45810, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46591, "src/Rosetta/codecs/audio/Stream.luau"], +[46752, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47234, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47512, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47681, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47809, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49797, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49913, "src/Rosetta/codecs/audio/Tta/init.luau"], +[50030, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50282, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50295, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50679, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51245, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51666, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51705, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51757, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51979, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53434, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53497, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53584, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54553, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55421, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55469, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55985, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56311, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56731, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57166, "src/Rosetta/codecs/compress/Explode.luau"], +[57362, "src/Rosetta/codecs/compress/Lz4.luau"], +[57631, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58235, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58775, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58813, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59286, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59462, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59730, "src/Rosetta/codecs/compress/Lzx.luau"], +[60164, "src/Rosetta/codecs/compress/PackBits.luau"], +[60254, "src/Rosetta/codecs/compress/Quantum.luau"], +[60491, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60795, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60864, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60921, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61879, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[62031, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62313, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62324, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62538, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62782, "src/Rosetta/codecs/font/Bitmap.luau"], +[62983, "src/Rosetta/codecs/font/Cff/init.luau"], +[63624, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63774, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64088, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64480, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64982, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65089, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65578, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[66007, "src/Rosetta/codecs/image/Blend.luau"], +[66386, "src/Rosetta/codecs/image/Dct/init.luau"], +[66767, "src/Rosetta/codecs/image/Etc.luau"], +[67065, "src/Rosetta/codecs/image/Half.luau"], +[67134, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67488, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67896, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68133, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68893, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69774, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70220, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70298, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70365, "src/Rosetta/codecs/image/Miptex.luau"], +[70581, "src/Rosetta/codecs/image/Pixels.luau"], +[70901, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71360, "src/Rosetta/codecs/image/Raster.luau"], +[72057, "src/Rosetta/codecs/image/Texel.luau"], +[72430, "src/Rosetta/codecs/image/Texture.luau"], +[72575, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72705, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74661, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74920, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[75169, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[75288, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75392, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[76245, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[77197, "src/Rosetta/codecs/image/Yuv.luau"], +[77465, "src/Rosetta/codecs/model/Brush.luau"], +[78105, "src/Rosetta/codecs/model/Displacement.luau"], +[78254, "src/Rosetta/codecs/model/Draco/init.luau"], +[78586, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[79055, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[80244, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[80393, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80752, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81714, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[82188, "src/Rosetta/codecs/model/Mat4.luau"], +[82447, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[82975, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[83527, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[83606, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83713, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[83919, "src/Rosetta/codecs/model/Patch.luau"], +[84043, "src/Rosetta/codecs/model/Polygon.luau"], +[84277, "src/Rosetta/codecs/model/Rbx/init.luau"], +[84514, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[85268, "src/Rosetta/codecs/model/Rig.luau"], +[85511, "src/Rosetta/codecs/model/Sampler.luau"], +[85671, "src/Rosetta/codecs/model/SourceAnim.luau"], +[85892, "src/Rosetta/codecs/model/Vrml/init.luau"], +[86040, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[86614, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86777, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[87526, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[88048, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88775, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[89007, "src/Rosetta/codecs/text/Json/init.luau"], +[89276, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89690, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89992, "src/Rosetta/codecs/text/KeyValues/init.luau"], +[90562, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], +[90868, "src/Rosetta/codecs/text/Nbt/init.luau"], +[91221, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[91913, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[92553, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[92791, "src/Rosetta/codecs/text/Text/init.luau"], +[92882, "src/Rosetta/codecs/text/Url/init.luau"], +[93087, "src/Rosetta/codecs/text/Xml/init.luau"], +[93490, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[94230, "src/Rosetta/codecs/video/Dsp.luau"], +[94953, "src/Rosetta/codecs/video/H263/init.luau"], +[95109, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[95967, "src/Rosetta/codecs/video/H263/Tables.luau"], +[96170, "src/Rosetta/codecs/video/H264/init.luau"], +[96543, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[96818, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[97949, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[98717, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[98975, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[99984, "src/Rosetta/codecs/video/H264/Inter.luau"], +[100238, "src/Rosetta/codecs/video/H264/Intra.luau"], +[100645, "src/Rosetta/codecs/video/H264/Mb.luau"], +[101551, "src/Rosetta/codecs/video/H264/Params.luau"], +[101998, "src/Rosetta/codecs/video/H264/Slice.luau"], +[102249, "src/Rosetta/codecs/video/H264/Tables.luau"], +[102290, "src/Rosetta/codecs/video/H264/Transform.luau"], +[102455, "src/Rosetta/codecs/video/Legacy/init.luau"], +[102653, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[102950, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[103317, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[103435, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[103543, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[103816, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[104211, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[104388, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[104400, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[104767, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[106274, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[106413, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[106551, "src/Rosetta/codecs/video/Theora/init.luau"], +[106814, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[108078, "src/Rosetta/codecs/video/Theora/Header.luau"], +[108441, "src/Rosetta/codecs/video/Video/init.luau"], +[108998, "src/Rosetta/codecs/video/Video/Source.luau"], +[109283, "src/Rosetta/containers/Archive.luau"], +[109550, "src/Rosetta/containers/AudioWrap.luau"], +[110053, "src/Rosetta/containers/Avi/init.luau"], +[110605, "src/Rosetta/containers/Chunks.luau"], +[110740, "src/Rosetta/containers/Cpio.luau"], +[111168, "src/Rosetta/containers/Demux.luau"], +[111443, "src/Rosetta/containers/Ebml/init.luau"], +[111756, "src/Rosetta/containers/Fat.luau"], +[112444, "src/Rosetta/containers/Iso9660.luau"], +[112949, "src/Rosetta/containers/IsoBmff/init.luau"], +[113119, "src/Rosetta/containers/IsoBmff/Box.luau"], +[113307, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[114152, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[114673, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[115189, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[115306, "src/Rosetta/containers/MacFile.luau"], +[115455, "src/Rosetta/containers/MpegEs.luau"], +[115621, "src/Rosetta/containers/MpegPs/init.luau"], +[115841, "src/Rosetta/containers/MpegTs/init.luau"], +[116633, "src/Rosetta/containers/Ogg/init.luau"], +[117058, "src/Rosetta/containers/Ogg/Mux.luau"], +[117253, "src/Rosetta/containers/Ogg/Page.luau"], +[117422, "src/Rosetta/containers/Riff/init.luau"], +[117739, "src/Rosetta/containers/Tar.luau"], +[118153, "src/Rosetta/containers/Zip/init.luau"], +[118785, "src/Rosetta/core/Adler32.luau"], +[118831, "src/Rosetta/core/Base64.luau"], +[118990, "src/Rosetta/core/Bits.luau"], +[119283, "src/Rosetta/core/Bytes.luau"], +[119810, "src/Rosetta/core/Crc16.luau"], +[119862, "src/Rosetta/core/Crc32.luau"], +[119974, "src/Rosetta/core/Err.luau"], +[120056, "src/Rosetta/core/Input.luau"], +[120132, "src/Rosetta/core/Md5.luau"], +[120291, "src/Rosetta/core/Sniff.luau"], +[120320, "src/Rosetta/data/cbor/init.luau"], +[120419, "src/Rosetta/data/cbor/Codec.luau"], +[120988, "src/Rosetta/data/csv/init.luau"], +[121300, "src/Rosetta/data/ini/init.luau"], +[121546, "src/Rosetta/data/json/init.luau"], +[121638, "src/Rosetta/data/msgpack/init.luau"], +[121727, "src/Rosetta/data/msgpack/Codec.luau"], +[122169, "src/Rosetta/data/nbt/init.luau"], +[122228, "src/Rosetta/data/plist/init.luau"], +[122534, "src/Rosetta/data/plist/Binary.luau"], +[122801, "src/Rosetta/data/snbt/init.luau"], +[122864, "src/Rosetta/data/toml/init.luau"], +[122931, "src/Rosetta/data/toml/Decode.luau"], +[123559, "src/Rosetta/data/toml/Encode.luau"], +[123768, "src/Rosetta/data/vdf/init.luau"], +[123869, "src/Rosetta/data/xml/init.luau"], +[123925, "src/Rosetta/data/yaml/init.luau"], +[123998, "src/Rosetta/data/yaml/Emit.luau"], +[124288, "src/Rosetta/data/yaml/Parse.luau"], +[125581, "src/Rosetta/font/bdf/init.luau"], +[125870, "src/Rosetta/font/bmfont/init.luau"], +[126297, "src/Rosetta/font/bmfont/Parse.luau"], +[126750, "src/Rosetta/font/eot/init.luau"], +[126982, "src/Rosetta/font/fon/init.luau"], +[127265, "src/Rosetta/font/hershey/init.luau"], +[127460, "src/Rosetta/font/pcf/init.luau"], +[127740, "src/Rosetta/font/psf/init.luau"], +[128060, "src/Rosetta/font/ttf/init.luau"], +[128111, "src/Rosetta/font/type1/init.luau"], +[128470, "src/Rosetta/font/type1/Charstring.luau"], +[128748, "src/Rosetta/font/woff/init.luau"], +[128880, "src/Rosetta/font/woff2/init.luau"], +[128937, "src/Rosetta/font/woff2/Rebuild.luau"], +[129477, "src/Rosetta/host/init.luau"], +[129522, "src/Rosetta/host/Love.luau"], +[129665, "src/Rosetta/host/LuaJIT.luau"], +[129715, "src/Rosetta/host/Luau.luau"], +[129738, "src/Rosetta/host/Roblox.luau"], +[130097, "src/Rosetta/image/ani/init.luau"], +[130277, "src/Rosetta/image/art/init.luau"], +[130765, "src/Rosetta/image/blp/init.luau"], +[131023, "src/Rosetta/image/bmp/init.luau"], +[131438, "src/Rosetta/image/dds/init.luau"], +[131921, "src/Rosetta/image/exr/init.luau"], +[132681, "src/Rosetta/image/exr/Codec.luau"], +[132792, "src/Rosetta/image/exr/Piz.luau"], +[133149, "src/Rosetta/image/gif/init.luau"], +[133665, "src/Rosetta/image/gif/Decode.luau"], +[133728, "src/Rosetta/image/hdr/init.luau"], +[133957, "src/Rosetta/image/hdr/Codec.luau"], +[134168, "src/Rosetta/image/icns/init.luau"], +[134499, "src/Rosetta/image/ico/init.luau"], +[134776, "src/Rosetta/image/ico/Dib.luau"], +[134871, "src/Rosetta/image/ilbm/init.luau"], +[135190, "src/Rosetta/image/jpeg/init.luau"], +[135326, "src/Rosetta/image/ktx/init.luau"], +[135986, "src/Rosetta/image/pcx/init.luau"], +[136250, "src/Rosetta/image/png/init.luau"], +[136830, "src/Rosetta/image/png/Apng.luau"], +[136910, "src/Rosetta/image/png/Decode.luau"], +[137150, "src/Rosetta/image/png/Encode.luau"], +[137305, "src/Rosetta/image/pnm/init.luau"], +[137683, "src/Rosetta/image/pnm/Codec.luau"], +[137960, "src/Rosetta/image/qoi/init.luau"], +[138082, "src/Rosetta/image/qoi/Codec.luau"], +[138232, "src/Rosetta/image/sgi/init.luau"], +[138517, "src/Rosetta/image/sunras/init.luau"], +[138763, "src/Rosetta/image/tga/init.luau"], +[139033, "src/Rosetta/image/tga/Codec.luau"], +[139185, "src/Rosetta/image/tiff/init.luau"], +[140012, "src/Rosetta/image/tiff/Pixels.luau"], +[140402, "src/Rosetta/image/tim/init.luau"], +[140644, "src/Rosetta/image/vtf/init.luau"], +[140879, "src/Rosetta/image/webp/init.luau"], +[141489, "src/Rosetta/image/webp/Alpha.luau"], +[141565, "src/Rosetta/image/webp/Anim.luau"], +[141720, "src/Rosetta/image/xbm/init.luau"], +[141881, "src/Rosetta/image/xpm/init.luau"], +[142149, "src/Rosetta/image/xpm/Names.luau"], +[142205, "src/Rosetta/layered/aseprite/init.luau"], +[142943, "src/Rosetta/layered/ora/init.luau"], +[143230, "src/Rosetta/layered/psd/init.luau"], +[143965, "src/Rosetta/layered/psd/Channels.luau"], +[144317, "src/Rosetta/model/3ds/init.luau"], +[144400, "src/Rosetta/model/3ds/Build.luau"], +[145047, "src/Rosetta/model/3ds/Read.luau"], +[145543, "src/Rosetta/model/3ds/Write.luau"], +[146348, "src/Rosetta/model/3mf/init.luau"], +[146430, "src/Rosetta/model/3mf/Read.luau"], +[147018, "src/Rosetta/model/3mf/Write.luau"], +[147423, "src/Rosetta/model/b3d/init.luau"], +[147478, "src/Rosetta/model/b3d/Read.luau"], +[148049, "src/Rosetta/model/bsp/init.luau"], +[148194, "src/Rosetta/model/bsp/Brush.luau"], +[148457, "src/Rosetta/model/bsp/Quake3.luau"], +[148685, "src/Rosetta/model/buildmap/init.luau"], +[148957, "src/Rosetta/model/buildmap/Geometry.luau"], +[149360, "src/Rosetta/model/dae/init.luau"], +[149549, "src/Rosetta/model/dae/Math.luau"], +[149596, "src/Rosetta/model/dae/Read.luau"], +[151446, "src/Rosetta/model/dae/Write.luau"], +[151815, "src/Rosetta/model/fbx/init.luau"], +[151963, "src/Rosetta/model/fbx/Ascii.luau"], +[152233, "src/Rosetta/model/fbx/Binary.luau"], +[152688, "src/Rosetta/model/fbx/Read.luau"], +[154050, "src/Rosetta/model/fbx/Write.luau"], +[155035, "src/Rosetta/model/fbx/Xform.luau"], +[155076, "src/Rosetta/model/gltf/init.luau"], +[155313, "src/Rosetta/model/gltf/Pack.luau"], +[155382, "src/Rosetta/model/gltf/Read.luau"], +[156113, "src/Rosetta/model/gltf/Write.luau"], +[156793, "src/Rosetta/model/iqm/init.luau"], +[156869, "src/Rosetta/model/iqm/Read.luau"], +[157224, "src/Rosetta/model/iqm/Write.luau"], +[157911, "src/Rosetta/model/ldraw/init.luau"], +[157989, "src/Rosetta/model/ldraw/Colors.luau"], +[158307, "src/Rosetta/model/ldraw/Read.luau"], +[158884, "src/Rosetta/model/lwo/init.luau"], +[158960, "src/Rosetta/model/lwo/Build.luau"], +[159422, "src/Rosetta/model/lwo/Parse.luau"], +[159965, "src/Rosetta/model/map/init.luau"], +[160282, "src/Rosetta/model/map/Build.luau"], +[160525, "src/Rosetta/model/map/Parse.luau"], +[160910, "src/Rosetta/model/map/Write.luau"], +[161056, "src/Rosetta/model/mca/init.luau"], +[161398, "src/Rosetta/model/mca/Chunk.luau"], +[161531, "src/Rosetta/model/mca/Lz4Block.luau"], +[161601, "src/Rosetta/model/md2/init.luau"], +[161800, "src/Rosetta/model/md3/init.luau"], +[162028, "src/Rosetta/model/md5/init.luau"], +[162109, "src/Rosetta/model/md5/Read.luau"], +[162542, "src/Rosetta/model/mdl/init.luau"], +[162624, "src/Rosetta/model/mdl/HalfLife.luau"], +[162928, "src/Rosetta/model/mdl/Quake.luau"], +[163146, "src/Rosetta/model/ms3d/init.luau"], +[163218, "src/Rosetta/model/ms3d/Read.luau"], +[163664, "src/Rosetta/model/ms3d/Write.luau"], +[164133, "src/Rosetta/model/obj/init.luau"], +[164875, "src/Rosetta/model/obj/Mtl.luau"], +[165162, "src/Rosetta/model/off/init.luau"], +[165624, "src/Rosetta/model/ply/init.luau"], +[166729, "src/Rosetta/model/ply/Binary.luau"], +[166930, "src/Rosetta/model/pmx/init.luau"], +[166999, "src/Rosetta/model/pmx/Build.luau"], +[167295, "src/Rosetta/model/pmx/Pmd.luau"], +[167630, "src/Rosetta/model/pmx/Read.luau"], +[168034, "src/Rosetta/model/qb/init.luau"], +[168427, "src/Rosetta/model/rbxm/init.luau"], +[169019, "src/Rosetta/model/rbxmx/init.luau"], +[169672, "src/Rosetta/model/robloxmesh/init.luau"], +[170331, "src/Rosetta/model/robloxmesh/Parse.luau"], +[170788, "src/Rosetta/model/robloxmesh/Write.luau"], +[170897, "src/Rosetta/model/schematic/init.luau"], +[171218, "src/Rosetta/model/schematic/Common.luau"], +[171338, "src/Rosetta/model/schematic/Litematic.luau"], +[171549, "src/Rosetta/model/schematic/Mcedit.luau"], +[171793, "src/Rosetta/model/schematic/Sponge.luau"], +[171922, "src/Rosetta/model/smd/init.luau"], +[171989, "src/Rosetta/model/smd/Read.luau"], +[172258, "src/Rosetta/model/smd/Write.luau"], +[172501, "src/Rosetta/model/sourcemdl/init.luau"], +[172672, "src/Rosetta/model/sourcemdl/Build.luau"], +[173102, "src/Rosetta/model/sourcemdl/Material.luau"], +[173263, "src/Rosetta/model/sourcemdl/Mdl.luau"], +[173790, "src/Rosetta/model/sourcemdl/Phy.luau"], +[173913, "src/Rosetta/model/sourcemdl/Vtx.luau"], +[174095, "src/Rosetta/model/sourcemdl/Vvd.luau"], +[174189, "src/Rosetta/model/stl/init.luau"], +[174639, "src/Rosetta/model/stl/Decode.luau"], +[174713, "src/Rosetta/model/usda/init.luau"], +[174922, "src/Rosetta/model/usda/Build.luau"], +[176200, "src/Rosetta/model/usda/Parse.luau"], +[176998, "src/Rosetta/model/usda/Write.luau"], +[177815, "src/Rosetta/model/vbsp/init.luau"], +[178261, "src/Rosetta/model/vbsp/Faces.luau"], +[178485, "src/Rosetta/model/vbsp/Props.luau"], +[178577, "src/Rosetta/model/vmf/init.luau"], +[178902, "src/Rosetta/model/vmf/Build.luau"], +[179326, "src/Rosetta/model/vox/init.luau"], +[180212, "src/Rosetta/model/vox/Grid.luau"], +[180269, "src/Rosetta/model/vrml/init.luau"], +[180335, "src/Rosetta/model/x/init.luau"], +[180465, "src/Rosetta/model/x/Build.luau"], +[181028, "src/Rosetta/model/x/Parse.luau"], +[181325, "src/Rosetta/model/x3d/init.luau"], +[181403, "src/Rosetta/music/669/init.luau"], +[181609, "src/Rosetta/music/ahx/init.luau"], +[181660, "src/Rosetta/music/far/init.luau"], +[181889, "src/Rosetta/music/hmp/init.luau"], +[182153, "src/Rosetta/music/hvl/init.luau"], +[182204, "src/Rosetta/music/it/init.luau"], +[182622, "src/Rosetta/music/it/Itsex.luau"], +[182738, "src/Rosetta/music/med/init.luau"], +[183385, "src/Rosetta/music/midi/init.luau"], +[183528, "src/Rosetta/music/midi/Smf.luau"], +[183939, "src/Rosetta/music/mod/init.luau"], +[184292, "src/Rosetta/music/mtm/init.luau"], +[184514, "src/Rosetta/music/mus/init.luau"], +[184671, "src/Rosetta/music/okt/init.luau"], +[184952, "src/Rosetta/music/ptm/init.luau"], +[185174, "src/Rosetta/music/s3m/init.luau"], +[185410, "src/Rosetta/music/sf2/init.luau"], +[185453, "src/Rosetta/music/stm/init.luau"], +[185684, "src/Rosetta/music/ult/init.luau"], +[185988, "src/Rosetta/music/umx/init.luau"], +[186204, "src/Rosetta/music/xm/init.luau"], +[186765, "src/Rosetta/music/xmi/init.luau"], +[186973, "src/Rosetta/ops/AudioOps.luau"], +[187422, "src/Rosetta/ops/ImageOps/init.luau"], +[188066, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[188576, "src/Rosetta/ops/LayerOps.luau"], +[188669, "src/Rosetta/ops/MeshOps/init.luau"], +[189705, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[189872, "src/Rosetta/ops/MusicOps.luau"], +[190220, "src/Rosetta/playlist/m3u/init.luau"], +[190573, "src/Rosetta/playlist/pls/init.luau"], +[190751, "src/Rosetta/playlist/xspf/init.luau"], +[190954, "src/Rosetta/subtitle/ass/init.luau"], +[191398, "src/Rosetta/subtitle/srt/init.luau"], +[191571, "src/Rosetta/subtitle/vtt/init.luau"], +[191774, "src/Rosetta/vector/svg/init.luau"], +[191860, "src/Rosetta/vector/svg/Parse.luau"], +[192606, "src/Rosetta/vector/svg/PathData.luau"], +[192974, "src/Rosetta/vector/svg/Render.luau"], +[193391, "src/Rosetta/vector/svg/Style.luau"], +[193763, "src/Rosetta/vector/svg/Write.luau"], +[193963, "src/Rosetta/vector/tiled/init.luau"], +[194143, "src/Rosetta/vector/tiled/Data.luau"], +[194294, "src/Rosetta/vector/tiled/Tmj.luau"], +[194925, "src/Rosetta/vector/tiled/Tmx.luau"], +[195537, "src/Rosetta/video/avi/init.luau"], +[195831, "src/Rosetta/video/fli/init.luau"], +[195982, "src/Rosetta/video/flv/init.luau"], +[196366, "src/Rosetta/video/flv/Amf.luau"], +[196524, "src/Rosetta/video/flv/Mux.luau"], +[196805, "src/Rosetta/video/h264/init.luau"], +[196944, "src/Rosetta/video/mkv/init.luau"], +[197100, "src/Rosetta/video/mkv/Mux.luau"], +[197379, "src/Rosetta/video/mkv/Parse.luau"], +[198100, "src/Rosetta/video/mp4/init.luau"], +[198428, "src/Rosetta/video/mpegps/init.luau"], +[198615, "src/Rosetta/video/mpegts/init.luau"], +[198853, "src/Rosetta/video/ogv/init.luau"], +[199248, "src/Rosetta/video/smk/init.luau"], +[199557, "src/Rosetta/video/smk/Audio.luau"], +[199677, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 6b51b18..43eb2dc 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -74,6 +74,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | +| model | map | .map | yes | yes | variants: "quake", "valve220", "quake2", "quake3", patches: true | `tests/model/map.luau` | | model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` | | model | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` | | model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` | @@ -93,6 +94,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | `tests/model/sourcemdl.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | +| model | vbsp | .bsp | yes | - | versions: 19, 20, 21, displacements: true, staticProps: true, pak: true | `tests/model/vbsp.luau` | +| model | vmf | .vmf .vmx | yes | yes | displacements: true, roundTrip: true | `tests/model/vmf.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | | model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` | @@ -240,7 +243,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). - codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. - codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. - - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. + - codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. + - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. - codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). - codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. - codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. @@ -249,10 +253,13 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. - **model** + - codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. + - codecs/model/Displacement: Source engine displacement surfaces (VBSP ddispinfo_t / Hammer dispinfo), as - codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). - codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. + - codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. - codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. - codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. diff --git a/docs/STYLE.md b/docs/STYLE.md index b38ac05..255cbd8 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -29,13 +29,13 @@ src/Rosetta/ codecs// codecs (layer 3) generic algorithms, by domain: compress/ Brotli Bzip2 Deflate Explode Lz4 Lzh Lzma Lzw Lzx PackBits Quantum UnixCompress Xxh32 Zstd entropy/ Huffman RangeCoder - image/ Bcn Blend Dct Etc Half Jpeg Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv + image/ Bcn Blend Dct Etc Half Jpeg Miptex Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) text/ Json KeyValues Nbt Text Url Xml font/ Bitmap Cff GlyphNames TrueType - model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler SourceAnim Vrml + model/ Brush Displacement Draco Mat4 MeshFlatten Minecraft Patch Polygon Rbx Rig Sampler SourceAnim Vrml host/ host (layer 2) runtime adapters; only the api uses them Types.luau types (layer 1) standard types + constructors core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input @@ -243,8 +243,10 @@ them. Anything generic goes down a layer and is called: | animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` | | polygons with holes -> triangles | `codecs/model/Polygon` | | studio model animation values (GoldSrc / Source run-length shorts, Quaternion48 / 64, bone records) | `codecs/model/SourceAnim` | +| plane brushes -> polygons (CSG hull, coplanar merge, Quake / Valve 220 / brush-primitive texturing); Bezier patches | `codecs/model/Brush`, `codecs/model/Patch` | +| Quake / GoldSrc mip textures, WAD2 / WAD3 directories; palettes (keyed index, grey, colormap) | `codecs/image/Miptex`, `codecs/image/Pixels` | | NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` | -| Valve KeyValues (text, binary, the BSP entity lump) | `codecs/text/KeyValues` | +| Valve KeyValues (text, binary, the BSP entity lump); Source displacement surfaces | `codecs/text/KeyValues`, `codecs/model/Displacement` | | Roblox instance trees and property values | `codecs/model/Rbx` | | bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` | | CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index e8d338a..81bcbcf 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -470,6 +470,8 @@ Game model formats load as Scenes too, with what games need: skins (joints + inv | MD5 (Doom 3 `.md5mesh` / `.md5anim`) | skeleton, weighted meshes, shaders as URIs | the `.md5anim` files named in `anims` | | SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames | | BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - | +| VBSP (Source 19 / 20 / 21) | each model a mesh, a primitive per material, displacements; static props as nodes; lights; entities; the pak lump | - | +| VMF (Hammer, read + write) | a mesh per entity with solids, displacements; point entities as nodes; cameras; visgroups | - | ```luau local tank = assert(F.model.load(md2Bytes)) @@ -573,6 +575,56 @@ assert(model.textures[skinA.baseColorTexture.texture].uri == "materials/models/t assert(#src.physics.solids[1].hulls == 2) ``` +### Source maps (VBSP) + +Compiled Source maps (`.bsp` with the `VBSP` magic: HL2, TF2, Portal, L4D2, CS:GO) load as one mesh per brush model +(`world`, `*1`, ...) with a primitive per material; brush entities place their model by `origin` / `angles`. +Displacements are tessellated (their blend alpha is the `_BLEND` attribute), tool faces (nodraw, skip, hint, sky) are +left out unless `tools = true`. Static props are nodes with `extras.model` (the `.mdl` path) and +`extras.vbsp` (skin, solid, fade, ...); `light`, `light_spot` and `light_environment` become lights. Entities are +`meta.entities` (KeyValues objects: a repeated output is an array), the pak lump `meta.pak` (an Archive), and a +material's texture is `materials/.vtf`, embedded when the pak has it. LZMA-compressed lumps and the L4D2 lump +header are read; lightmaps and visibility are not. + +```luau +local room = assert(F.model.load(vbspBytes, { name = "room.bsp" })) +assert(room.meta.source.format == "vbsp" and room.meta.source.version == 21) +local props = {} +for _, n in room.nodes do + if n.extras and n.extras.model then + table.insert(props, n.extras.model) + end +end +assert(props[1] == "models/props_junk/wood_crate001a.mdl") +assert(room.meta.entities[1].classname == "worldspawn") +assert(room.meta.pak:read("materials/custom/note.txt")) +``` + +### Hammer maps (VMF) + +`.vmf` sources load like `.map` files: a mesh per entity with solids (Valve 220 texture axes through +`codecs/model/Brush`), displacements tessellated as the compiler does (a brush with a displaced side keeps only its +displaced sides), point entities as nodes (`extras.model` for props), Hammer cameras as cameras. `tools/*` materials +are left out unless `tools = true`; texture sizes come from `textureSizes`, or `materials/.vtf` through +`resolve` and `decodeImage`, else 512 x 512. `meta.entities` holds the keys (outputs under `connections`), +`meta.visgroups`, `meta.groups` and `meta.solids` the editor data, and `meta.vmf` the parsed document, which `F.save` +writes back exactly as Hammer lays it out. `F.format("vmf")` builds documents: `document`, `world`, `box`, `solid`, +`entity`. + +```luau +local hammer = assert(F.model.load(vmfText, { format = "vmf" })) +assert(hammer.meta.entities[1].classname == "worldspawn" and hammer.meta.visgroups[1].name == "Walls") +assert(#hammer.cameras == 2) +assert(F.saveString(hammer, { format = "vmf" }) == vmfText) -- unchanged documents write back byte for byte + +local Vmf = F.format("vmf") +local doc = Vmf.document({ skyname = "sky_day01_01" }) +table.insert(Vmf.world(doc), Vmf.box({ -128, -128, -16 }, { 128, 128, 0 }, "DEV/DEV_MEASUREGENERIC01B")) +Vmf.entity(doc, { { "classname", "info_player_start" }, { "origin", "0 0 8" } }) +local built = assert(F.model.load(assert(F.saveString(doc, { format = "vmf" })), { format = "vmf" })) +assert(#built.meshes[1].primitives == 1 and built.meta.entities[2].classname == "info_player_start") +``` + ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; @@ -813,6 +865,8 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | Build engine MAP (v7-9) | yes | yes | sloped sectors, walls, sprites as nodes, raw tables in `meta.build`; see "Build engine maps" above | | Source MDL (v44-49) + VVD / VTX / PHY | yes | - | skeleton, body parts, LODs, flexes, animations, VMT materials: see above | +| MD2, MD3, MDL, MD5, BSP, VBSP | yes | - | game models and maps: see "Game models" above | +| VMF | yes | yes (round trip, builders) | Hammer maps: see "Hammer maps (VMF)" above | | SMD | yes | yes | Valve studiomdl data | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 9b56d33..79a0227 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -752,7 +752,7 @@ local list: { Entry } = { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, load = function() return require("@rosetta/model/bsp") @@ -842,6 +842,18 @@ local list: { Entry } = { return require("@rosetta/model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return require("@rosetta/model/map") + end, + }, { name = "mca", category = "model", @@ -1070,6 +1082,30 @@ local list: { Entry } = { return require("@rosetta/model/usda") end, }, + { + name = "vbsp", + category = "model", + path = "model/vbsp", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, + load = function() + return require("@rosetta/model/vbsp") + end, + }, + { + name = "vmf", + category = "model", + path = "model/vmf", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, + load = function() + return require("@rosetta/model/vmf") + end, + }, { name = "vox", category = "model", diff --git a/src/Rosetta/codecs/image/Miptex.luau b/src/Rosetta/codecs/image/Miptex.luau new file mode 100644 index 0000000..eb6edbf --- /dev/null +++ b/src/Rosetta/codecs/image/Miptex.luau @@ -0,0 +1,214 @@ +--!strict +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = require("@rosetta/Types") +local Pixels = require("@rosetta/codecs/image/Pixels") +local Quantize = require("@rosetta/codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +export type Header = { name: string, width: number, height: number, offsets: { number } } +export type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } +export type DecodeOptions = { + palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own + goldsrc: boolean?, -- read the palette stored after mip 3 + mip: number?, -- 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: names starting with '{' + maxPixels: number?, -- default 2^24 +} + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) + if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b: buffer, at: number, size: number, hd: Header): buffer? + local w, h = hd.width, hd.height + local p = hd.offsets[4] + (w // 8) * (h // 8) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = hd.width // (2 ^ mip), hd.height // (2 ^ mip) + if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 1, 1) == "{" + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local w2, h2 = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) + local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + local colors: { { number } } + if palette then + colors = Pixels.colorList(palette) + elseif goldsrc then + colors = Quantize.palette(img.pixels, w, h, 256) + else + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local levels: { buffer } = {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil }) + if keyed then + for k = 0, lw * lh - 1 do + if readu8(px, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + levels[m + 1] = idx + end + local total = 40 + for _, l in levels do + total += buffer.len(l) + end + local palAt = total + if goldsrc then + total += 2 + 768 + 2 + end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in levels do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o += buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) + if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out: { Lump } = {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps: { Lump }, name: string): Lump? + local want = string.lower(name) + local best: Lump? = nil + for _, l in lumps do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +return Miptex diff --git a/src/Rosetta/codecs/image/Pixels.luau b/src/Rosetta/codecs/image/Pixels.luau index 30a15a8..d7db8ab 100644 --- a/src/Rosetta/codecs/image/Pixels.luau +++ b/src/Rosetta/codecs/image/Pixels.luau @@ -1,8 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -259,4 +260,59 @@ function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boole return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +function Pixels.grey(): buffer + local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and +-- '{' textures) +function Pixels.keyed(pal: buffer, index: number): buffer + local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu32(out, index * 4, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +function Pixels.colorList(pal: buffer, n: number?): { { number } } + local out: { { number } } = {} + for i = 0, math.clamp(n or 256, 0, buffer.len(pal) // 4) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? + local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +function Pixels.paletteBytes(pal: buffer, n: number?): buffer + local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels diff --git a/src/Rosetta/codecs/model/Brush.luau b/src/Rosetta/codecs/model/Brush.luau new file mode 100644 index 0000000..a76dfb3 --- /dev/null +++ b/src/Rosetta/codecs/model/Brush.luau @@ -0,0 +1,638 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = require("@rosetta/Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) +export type Face = { + plane: Plane, + texture: string?, + vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) + bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths + [string]: any, +} +export type Polygon = { + brush: number, + face: number, + points: { number }, -- x, y, z per corner, counter-clockwise seen from the front + normal: { number }, +} +export type Options = { + epsilon: number?, -- plane side tolerance, default 1e-3 + size: number?, -- half size of the starting winding, default 2^17 + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + hull: boolean?, -- drop face parts inside / touching other brushes, default false + maxPolygons: number?, -- default 2^20 +} +export type Built = { texture: string, primitive: Types.Primitive } + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +local function snap(x: number): number + local r = floor(x + 0.5) + return if abs(x - r) < 1e-6 then r else x +end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +function Brush.baseAxis(n: { number }): number + local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } + local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 + local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 3 + for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } + local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +function Brush.axisBase(normal: { number }): ({ number }, { number }) + local nx, ny, nz = normal[1], normal[2], normal[3] + nx = if abs(nx) < 1e-6 then 0 else nx + ny = if abs(ny) < 1e-6 then 0 else ny + nz = if abs(nz) < 1e-6 then 0 else nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) + local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +function Brush.baseWinding(p: Plane, size: number): { number } + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) + local n = #pts // 3 + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = table.create(n, 0) :: { number } + local side = table.create(n, 0) :: { number } + local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front += 1 + elseif v < -eps then + side[i + 1] = -1 + back += 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f: { number }, b: { number } = {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +local function clean(pts: { number }, eps: number): { number }? + local out: { number } = {} + local n = #pts // 3 + for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = #out // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return if #out >= 9 then out else nil +end + +local function samePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +local function oppositePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } + local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out: { { number }? } = {} + for i, p in planes do + local w: { number }? = Brush.baseWinding(p, size) + for j, q in planes do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = if on then nil else back + end + end + end + out[i] = if w then clean(w, eps) else nil + end + return out +end + +local function bounds(polys: { Polygon }): { number } + local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in polys do + local pts = p.points + for k = 0, #pts // 3 - 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } + local kept: { { number } } = {} + local inside: { number }? = pts + for _, q in planes do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +local function faceKey(f: Face): string + local parts = { f.texture or "" } + for _, m in { f.vecs, f.bp } do + if m then + for _, row in m do + for _, v in row do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +local function convex(pts: { number }, n: { number }, eps: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? + local n1, n2 = #f1 // 3, #f2 // 3 + for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out: { number } = {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } + local groups: { [string]: { Polygon } } = {} + local order: { string } = {} + for _, p in polys do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out: { Polygon } = {} + for _, key in order do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in g do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) + local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per: { { Polygon } } = {} + local planesOf: { { Plane } } = {} + local count = 0 + for bi, faces in brushes do + local planes: { Plane } = {} + for fi, f in faces do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list: { Polygon } = {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count += #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all: { Polygon } = {} + if opts and opts.hull then + local boxes: { { number } } = {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in per[bi] do + local frags: { { number } } = { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags: { { number } } = {} + for _, fr in frags do + for _, kept in outside(fr, own, bi, bj, planesOf[bj], eps) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in frags do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in per[bi] do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +function Brush.area(pts: { number }): number + local n = #pts // 3 + local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax += uy * vz - uz * vy + ay += uz * vx - ux * vz + az += ux * vy - uy * vx + end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } + type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + local byTex: { [string]: Acc } = {} + local order: { Acc } = {} + local sizes: { [string]: { number } } = {} + for _, p in polys do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a: Acc = acc + local pts = p.points + local n = #pts // 3 + local base = #a.pos // 3 + for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out: { Built } = {} + for _, a in order do + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" :: "triangles", + }, + }) + end + return out +end + +return Brush diff --git a/src/Rosetta/codecs/model/Displacement.luau b/src/Rosetta/codecs/model/Displacement.luau new file mode 100644 index 0000000..14f83c6 --- /dev/null +++ b/src/Rosetta/codecs/model/Displacement.luau @@ -0,0 +1,147 @@ +--!strict +-- codecs/model/Displacement: Source engine displacement surfaces (VBSP ddispinfo_t / Hammer dispinfo), as +-- CCoreDispInfo::GenerateDispSurf of the Source SDK 2013 (no code taken): corner 0 is the base face corner nearest the +-- start position, rows run along corner 0 -> 1, columns along 0 -> 3 (the face's own, clockwise, winding), each vertex +-- moved by its offset; the 2^power quads split along alternating diagonals. Normals come from the grid. +local Types = require("@rosetta/Types") + +local Displacement = {} + +local sqrt = math.sqrt + +export type Surface = { + n: number, -- vertices per row: 2^power + 1 + flat: { number }, -- x, y, z on the base face (texture coordinates are projected from these) + pos: { number }, -- x, y, z displaced + nrm: { number }, -- unit normals on the face normal's side + idx: { number }, -- 0-based triangles, counter-clockwise seen from the face normal's side +} + +local function cross(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number, number) + return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx +end + +-- corners: the 4 face corners (12 numbers) in the face's clockwise winding; offsets: n * n * 3 numbers (row major, +-- row = i along corner 0 -> 1) added to the flat grid; normal: the face's outward normal +function Displacement.surface(corners: { number }, start: { number }, power: number, offsets: { number }, normal: { number }): (Surface?, string?) + if #corners ~= 12 then + return nil, "a displacement needs a 4-sided face" + end + if power < 1 or power > 4 or power % 1 ~= 0 then + return nil, "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + if #offsets < n * n * 3 then + return nil, "displacement offsets truncated" + end + local best, bestD = 0, math.huge + for k = 0, 3 do + local dx, dy, dz = corners[k * 3 + 1] - start[1], corners[k * 3 + 2] - start[2], corners[k * 3 + 3] - start[3] + local d = dx * dx + dy * dy + dz * dz + if d < bestD then + best, bestD = k, d + end + end + local c: { number } = table.create(12) :: any + for k = 0, 3 do + local s = ((best + k) % 4) * 3 + c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = corners[s + 1], corners[s + 2], corners[s + 3] + end + local flat: { number } = table.create(n * n * 3) :: any + local pos: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local t = i / (n - 1) + local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t + local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t + for j = 0, n - 1 do + local s = j / (n - 1) + local k = (i * n + j) * 3 + local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s + flat[k + 1], flat[k + 2], flat[k + 3] = x, y, z + pos[k + 1], pos[k + 2], pos[k + 3] = x + offsets[k + 1], y + offsets[k + 2], z + offsets[k + 3] + end + end + local nx, ny, nz = normal[1], normal[2], normal[3] + local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3]) + local sign = if ux * nx + uy * ny + uz * nz >= 0 then 1 else -1 + local nrm: { number } = table.create(n * n * 3) :: any + for i = 0, n - 1 do + local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1) + for j = 0, n - 1 do + local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1) + local a, b = (i1 * n + j) * 3, (i0 * n + j) * 3 + local e, f = (i * n + j1) * 3, (i * n + j0) * 3 + local x, y, z = cross(pos[a + 1] - pos[b + 1], pos[a + 2] - pos[b + 2], pos[a + 3] - pos[b + 3], pos[e + 1] - pos[f + 1], pos[e + 2] - pos[f + 2], pos[e + 3] - pos[f + 3]) + local l = sqrt(x * x + y * y + z * z) + local k = (i * n + j) * 3 + if l < 1e-12 then + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + else + nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l + end + end + end + -- triangle (i, j), (i + 1, j), (i, j + 1) turns about rows x columns: flipped when that faces away + local idx: { number } = table.create((n - 1) * (n - 1) * 6) :: any + local flip = sign < 0 + for i = 0, n - 2 do + for j = 0, n - 2 do + local a = i * n + j + local b, cc, d = a + n, a + n + 1, a + 1 + local t1, t2, t3, t4, t5, t6 + if (i + j) % 2 == 0 then + t1, t2, t3, t4, t5, t6 = a, b, d, b, cc, d + else + t1, t2, t3, t4, t5, t6 = a, b, cc, a, cc, d + end + if flip then + t2, t3, t5, t6 = t3, t2, t6, t5 + end + local q = #idx + idx[q + 1], idx[q + 2], idx[q + 3], idx[q + 4], idx[q + 5], idx[q + 6] = t1, t2, t3, t4, t5, t6 + end + end + return { n = n, flat = flat, pos = pos, nrm = nrm, idx = idx }, nil +end + +export type Arrays = { + pos: { number }, + nrm: { number }, + uv: { number }, + idx: { number }, -- 0-based + blend: { number }?, -- per vertex 0..1: the _BLEND attribute (displacement alpha) +} + +-- flat arrays -> an indexed triangle primitive (POSITION, NORMAL, TEXCOORD_0, _BLEND) +function Displacement.primitive(a: Arrays): Types.Primitive + local writef32, writeu32 = buffer.writef32, buffer.writeu32 + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + local attrs: { [string]: Types.Accessor } = { + POSITION = S.accessor(pb, "f32", 3, nv), + NORMAL = S.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = S.accessor(ub, "f32", 2, nv), + } + local blend = a.blend + if blend then + local bb = buffer.create(nv * 4) + for k = 1, nv do + writef32(bb, (k - 1) * 4, blend[k] or 0) + end + attrs._BLEND = S.accessor(bb, "f32", 1, nv) + end + return { attributes = attrs, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" } +end + +return Displacement diff --git a/src/Rosetta/codecs/model/Patch.luau b/src/Rosetta/codecs/model/Patch.luau new file mode 100644 index 0000000..188dc00 --- /dev/null +++ b/src/Rosetta/codecs/model/Patch.luau @@ -0,0 +1,122 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +function Patch.valid(w: number, h: number, n: number): boolean + return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) + local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = (w - 1) // 2, (h - 1) // 2 + local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = table.create(gw * gh * comps, 0) :: { number } + for gy = 0, gh - 1 do + local sy = math.min(gy // lv, py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(gx // lu, px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 + local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) + local c = row + i * comps + for k = 1, comps do + out[o + k] += ctrl[c + k] * wgt + end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +function Patch.triangles(gw: number, gh: number): { number } + local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } + for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +function Patch.normalize(pts: { number }, comps: number, at: number) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } + local out = table.create(gw * gh * 3, 0) :: { number } + local function at(x: number, y: number, k: number): number + return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, i // gw + for _, d in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } } do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch diff --git a/src/Rosetta/codecs/text/KeyValues/Binary.luau b/src/Rosetta/codecs/text/KeyValues/Binary.luau index 6d1daa5..c2945a2 100644 --- a/src/Rosetta/codecs/text/KeyValues/Binary.luau +++ b/src/Rosetta/codecs/text/KeyValues/Binary.luau @@ -11,6 +11,7 @@ export type Pair = { key: string, value: any, -- string | number | Block cond: string?, -- text: the [$CONDITION] kept when not evaluated + bare: boolean?, -- text: a block whose name was unquoted (written back so with bareBlocks) type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block) } export type Block = { Pair } diff --git a/src/Rosetta/codecs/text/KeyValues/init.luau b/src/Rosetta/codecs/text/KeyValues/init.luau index 81eebb6..ded4d65 100644 --- a/src/Rosetta/codecs/text/KeyValues/init.luau +++ b/src/Rosetta/codecs/text/KeyValues/init.luau @@ -11,7 +11,7 @@ local KeyValues = {} export type Pair = Binary.Pair export type Block = Binary.Block export type ParseOptions = { - escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true + escapes: (boolean | "quotes")?, -- \n \t \\ \" ... in quoted strings, default true; "quotes": only \" -- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the -- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with -- its cond @@ -20,8 +20,11 @@ export type ParseOptions = { maxDepth: number?, -- default 256 } export type WriteOptions = { - escapes: boolean?, -- default true + escapes: (boolean | "quotes")?, -- default true; "quotes": only " is escaped indent: string?, -- default "\t" + separator: string?, -- between a key and its value, default "\t" (Hammer: " ") + bareBlocks: boolean?, -- block names unquoted when they are plain words (Hammer), default false + flatBlocks: { [string]: boolean }?, -- blocks whose pairs keep the block's own indent (Hammer's dispinfo rows) } export type ObjectOptions = { duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array @@ -31,7 +34,7 @@ local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true } local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' } -type Lexer = { s: string, i: number, n: number, escapes: boolean } +type Lexer = { s: string, i: number, n: number, escapes: boolean, quotesOnly: boolean?, quoted: boolean? } -- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string local function token(lx: Lexer): (string?, string?, number, string?) @@ -60,6 +63,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) lx.i = i + 1 return c, nil, i - 1, nil elseif c == '"' then + lx.quoted = true local start = i i += 1 if not lx.escapes then @@ -84,7 +88,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "s", table.concat(parts), start - 1, nil end local x = string.sub(s, e + 1, e + 1) - local r = ESCAPE[x] + local r = if lx.quotesOnly and x ~= '"' then nil else ESCAPE[x] if r then table.insert(parts, r) i = e + 2 @@ -101,6 +105,7 @@ local function token(lx: Lexer): (string?, string?, number, string?) return "[", string.sub(s, i + 1, e - 1), i - 1, nil end end + lx.quoted = false local e = string.find(s, '[ \t\r\n\f\v"{}]', i) local stop = if e then e - 1 else n lx.i = stop + 1 @@ -145,7 +150,7 @@ end local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?) local o: ParseOptions = opts or {} - local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false } + local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false, quotesOnly = o.escapes == "quotes" } if string.sub(text, 1, 3) == "\239\187\191" then lx.i = 4 end @@ -185,6 +190,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at) else local key = v :: string + local keyQuoted = lx.quoted local k2, v2, at2, terr2 = token(lx) if terr2 then return nil, Err.new(Err.TRUNCATED, terr2, at2) @@ -208,7 +214,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl if not pass then skipping += 1 else - local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond } + local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond, bare = not keyQuoted } local last = cur[#cur] if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then cur[#cur] = pair @@ -311,7 +317,7 @@ function KeyValues.copy(b: Block): Block local out: Block = table.create(#b) :: any for i, p in b do local v: any = p.value - out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type } + out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type, bare = p.bare } end return out end @@ -354,18 +360,23 @@ function KeyValues.all(b: Block, key: string): { Pair } return out end -local function quote(s: string, escapes: boolean): string - if escapes then +local function quote(s: string, escapes: boolean | string): string + if escapes == "quotes" then + s = string.gsub(s, '"', '\\"') + elseif escapes then s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) end return '"' .. s .. '"' end -local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string? - if depth > 256 then +type WriteState = { indent: string, escapes: boolean | string, sep: string, bare: boolean, flat: { [string]: boolean } } + +local function writeBlock(b: Block, out: { string }, w: WriteState, level: number, depth: number?): string? + local dp = depth or 0 + if dp > 256 then return "nesting deeper than 256" end - local pad = string.rep(indent, level) + local pad = string.rep(w.indent, level) for _, p in b do if type(p) ~= "table" or type(p.key) ~= "string" then return "a pair needs a string key" @@ -373,15 +384,16 @@ local function writeBlock(b: Block, out: { string }, indent: string, level: numb local v: any = p.value local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else "" if type(v) == "table" then - table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n") - local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1) + local name = if w.bare and (p.bare or (p.bare == nil and string.match(p.key, "^[%w_]+$"))) then p.key else quote(p.key, w.escapes) + table.insert(out, pad .. name .. cond .. "\n" .. pad .. "{\n") + local err = writeBlock(v, out, w, if w.flat[p.key] then level else level + 1, dp + 1) if err then return err end table.insert(out, pad .. "}\n") elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v) - table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n") + table.insert(out, pad .. quote(p.key, w.escapes) .. w.sep .. quote(s, w.escapes) .. cond .. "\n") else return "unwritable value for key " .. p.key end @@ -394,7 +406,8 @@ function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?) return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list") end local out: { string } = {} - local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0) + local o: WriteOptions = opts or {} + local err = writeBlock(b, out, { indent = o.indent or "\t", escapes = if o.escapes == nil then true else o.escapes, sep = o.separator or "\t", bare = o.bareBlocks == true, flat = o.flatBlocks or {} }, 0) if err then return nil, Err.new(Err.ARG, err) end diff --git a/src/Rosetta/model/bsp/Brush.luau b/src/Rosetta/model/bsp/Brush.luau index f745199..fd47cf7 100644 --- a/src/Rosetta/model/bsp/Brush.luau +++ b/src/Rosetta/model/bsp/Brush.luau @@ -4,6 +4,7 @@ -- size. local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") +local Miptex = require("@rosetta/codecs/image/Miptex") local Brush = {} @@ -36,34 +37,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil + if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil - end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end diff --git a/src/Rosetta/model/bsp/Quake3.luau b/src/Rosetta/model/bsp/Quake3.luau index de8c1a4..0c149b8 100644 --- a/src/Rosetta/model/bsp/Quake3.luau +++ b/src/Rosetta/model/bsp/Quake3.luau @@ -1,7 +1,9 @@ --!strict -- 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. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = require("@rosetta/Types") +local Patch = require("@rosetta/codecs/model/Patch") local Quake3 = {} @@ -81,52 +83,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: counts[if kind == 1 then "polygons" else "meshes"] += 1 elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches += 1 - local L = level - for py = 0, (h - 1) // 2 - 1 do - for px = 0, (w - 1) // 2 - 1 do - local ctrl: { { number } } = {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid: { number } = {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k] += cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - 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] - -- Quake's control grids are clockwise-front - for _, v in { a, d, c2, c2, d, e } do - table.insert(tris, v) - end - end - end - end + local ctrl = table.create(n * 14, 0) :: { number } + for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = table.create(gw * gh) :: { number } + for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number }) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(tris, ids[v + 1]) end else counts.skipped += 1 diff --git a/src/Rosetta/model/bsp/init.luau b/src/Rosetta/model/bsp/init.luau index 02ae8d9..2249bde 100644 --- a/src/Rosetta/model/bsp/init.luau +++ b/src/Rosetta/model/bsp/init.luau @@ -17,7 +17,7 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, } diff --git a/src/Rosetta/model/map/Build.luau b/src/Rosetta/model/map/Build.luau new file mode 100644 index 0000000..cde0d0a --- /dev/null +++ b/src/Rosetta/model/map/Build.luau @@ -0,0 +1,241 @@ +--!strict +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = require("@rosetta/Types") +local Brush = require("@rosetta/codecs/model/Brush") +local Patch = require("@rosetta/codecs/model/Patch") +local Parse = require("@rosetta/model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Options = { + variant: string, -- "quake" | "valve220" | "quake2" | "quake3" + size: (name: string) -> (number, number, boolean), -- width, height, known + hull: boolean?, + merge: boolean?, + epsilon: number?, + patchLevel: number?, + skip: { string }?, + maxPolygons: number?, +} + +function Build.face(f: Parse.Face): Brush.Face? + local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out: Brush.Face = { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + +local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean + local size, pts = b.size :: { number }, b.points :: { number } + local w: number, h: number = size[1] :: number, size[2] :: number + if not Patch.valid(w, h, #pts // 5) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = table.create(w * h * 5, 0) :: { number } + for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params: { number } = b.params or {} + local explicit = b.type == "patchDef3" + local lu: number = if explicit then math.max(1, params[1] or 1) else level + local lv: number = if explicit then math.max(1, params[2] or 1) else level + local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = #acc.pos // 3 + for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a: Acc): Types.Primitive + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s: string?): { number }? + if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?) + local scene = Scene.new() + scene.meta.up = "z" + local skip: { [string]: boolean } = {} + for _, n in o.skip or {} do + skip[string.lower(n)] = true + end + local matOf: { [string]: number } = {} + local function material(name: string): number + local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities: { { [string]: string } } = {} + local polyTotal = 0 + for ei, ent in map.entities do + local keys = ent.keys + table.insert(entities, keys) + local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes: { { Brush.Face } } = {} + local patchAcc: { [string]: Acc } = {} + local patchOrder: { string } = {} + for _, b in ent.brushes do + if b.faces then + counts.brushes += 1 + local faces: { Brush.Face } = {} + for _, f in b.faces do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces += 1 + end + end + table.insert(brushes, faces) + else + counts.patches += 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then + skipped.patches += 1 + end + end + end + end + local prims: { Types.Primitive } = {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal += #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept: { Brush.Polygon } = {} + for _, p in polys do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name: string): (number, number) + local m = scene.materials[material(name)] + local e = (m.extras :: any).map + return e.width, e.height + end) + for _, bt in built do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in patchOrder do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build diff --git a/src/Rosetta/model/map/Parse.luau b/src/Rosetta/model/map/Parse.luau new file mode 100644 index 0000000..cc18e3a --- /dev/null +++ b/src/Rosetta/model/map/Parse.luau @@ -0,0 +1,383 @@ +--!strict +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = require("@rosetta/Types") + +local Parse = {} + +export type Face = { + points: { number }, -- 3 points: x, y, z each + texture: string, + offset: { number }?, -- Quake standard: x, y offset + rotation: number?, -- standard / Valve 220 (degrees) + scale: { number }?, -- standard / Valve 220 + u: { number }?, -- Valve 220: axis x, y, z, offset + v: { number }?, + matrix: { { number } }?, -- Quake III brush primitives: 2 x 3 + flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light) +} +export type Brush = { + type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3" + faces: { Face }?, + texture: string?, -- patches + size: { number }?, -- patches: width, height (columns, points per column as written) + params: { number }?, -- patches: the header numbers after width, height + points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column) +} +export type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object) +export type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } } + +type St = { s: string, pos: number, n: number, comments: { string } } + +local function skip(st: St) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st: St): string + skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st: St, c: string): string? + if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos += 1 + return nil +end + +local function word(st: St): string? + skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b :: number) + 1 + return string.sub(st.s, a, b) +end + +local function number(st: St): number? + skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b :: number) + 1 + end + return v +end + +local function quoted(st: St): string? + if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st: St, n: number, out: { number }): string? + for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?) + local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st: St): { number }? + local out: { number } = {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return if #out > 0 then out else nil +end + +local function plane(st: St): ({ number }?, string?) + local pts: { number } = {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st: St, bp: boolean): (Face?, string?) + local pts, e = plane(st) + if not pts then + return nil, e + end + local f: Face = { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?) + local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = if kind == "patchDef3" then 7 else 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts: { number } = {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st: St, maxPoints: number): (Brush?, string?) + local c = peek(st) + if c == "(" then + local faces: { Face } = {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos += 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out: any, err: string? + if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces: { Face } = {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?) + local st: St = { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents: { Entity } = {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys: { [string]: string } = {} + local order: { string } = {} + local brushes: { Brush } = {} + while true do + local c = peek(st) + if c == "}" then + st.pos += 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos += 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count += 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes }) + end + local game, fmt + for _, c in st.comments do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse diff --git a/src/Rosetta/model/map/Write.luau b/src/Rosetta/model/map/Write.luau new file mode 100644 index 0000000..47ce084 --- /dev/null +++ b/src/Rosetta/model/map/Write.luau @@ -0,0 +1,144 @@ +--!strict +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = require("@rosetta/Types") +local Parse = require("@rosetta/model/map/Parse") + +local Write = {} + +function Write.num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t: { number }, a: number, b: number): string + local out = table.create(b - a + 1) :: { string } + for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f: Parse.Face, bp: boolean): (string?, string?) + local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b: Parse.Brush, out: { string }): string? + local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = if b.type == "patchDef3" then 5 else 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map: Parse.Map): (string?, string?) + local out: { string } = {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in map.entities do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in Types.keys(ent.keys) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in ent.brushes or {} do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in b.faces or {} do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write diff --git a/src/Rosetta/model/map/init.luau b/src/Rosetta/model/map/init.luau new file mode 100644 index 0000000..10b6841 --- /dev/null +++ b/src/Rosetta/model/map/init.luau @@ -0,0 +1,315 @@ +--!strict +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Types = require("@rosetta/Types") +local Miptex = require("@rosetta/codecs/image/Miptex") +local Brush = require("@rosetta/codecs/model/Brush") +local Parse = require("@rosetta/model/map/Parse") +local Write = require("@rosetta/model/map/Write") +local Build = require("@rosetta/model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + epsilon: number?, -- default 1e-3 + patchLevel: number?, -- patchDef2 segments per sub-patch, default 4 + skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...) + textureSizes: { [string]: { number } }?, -- name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes + maxBrushes: number?, -- default 2^20 + maxPolygons: number?, -- default 2^20 +} +export type EncodeOptions = { + variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Map.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c :: number) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return if game and string.match(s, "^%s*{") then 0.6 else 0 + end + return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m: Parse.Map): string + local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in m.entities do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in e.brushes do + if b.type ~= "brush" then + q3 = true + end + for _, f in b.faces or {} do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return if q2 then "quake2" else "quake" +end + +local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil + local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } } + local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in string.gmatch(spec, "[^;]+") do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w: number, h: number = 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] :: number, given[2] :: number + elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads :: any), 1, -1 do + local wd = (wads :: any)[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in { ".tga", ".jpg", ".png" } do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage :: any, b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw: number, fh: number = w :: number, h :: number + local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, if known then 1 else 0 } + return fw, fh, known + end +end + +function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f: Parse.Face): Parse.Face + if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x: number): string + return Write.num(x) +end + +function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents: { any } = {} + for _, node in scene.nodes do + local ex: any = node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {} + if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv: { Parse.Brush } = {} + for _, b in brushes do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in b.faces do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src: any = scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents :: { Parse.Entity }, + game = if fromMap then src.game else nil, + mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil, + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?) + local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil + if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m: Parse.Map): (string?, Err.Err?) + if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f: Parse.Face): Brush.Face? + return Build.face(f) +end + +return Map diff --git a/src/Rosetta/model/vbsp/Faces.luau b/src/Rosetta/model/vbsp/Faces.luau new file mode 100644 index 0000000..5418d04 --- /dev/null +++ b/src/Rosetta/model/vbsp/Faces.luau @@ -0,0 +1,222 @@ +--!strict +-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013 +-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert); displacements through codecs/model/Displacement. +local Types = require("@rosetta/Types") +local Displacement = require("@rosetta/codecs/model/Displacement") + +local Faces = {} + +local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8 + +export type Lump = { buf: buffer, at: number, size: number } +export type Input = { + planes: Lump, + vertices: Lump, + edges: Lump, + surfedges: Lump, + faces: Lump, + texinfo: Lump, + texdata: Lump, + models: Lump, + dispinfo: Lump, + dispverts: Lump, + tools: boolean, -- keep nodraw / skip / hint / sky faces + maxVertices: number, +} +export type Group = { model: number, texdata: number, pos: { number }, nrm: { number }, uv: { number }, blend: { number }?, idx: { number } } + +-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP +local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200 + +local function emit(g: Group, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number + local pos, nrm, uv = g.pos, g.nrm, g.uv + local k = #pos + pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z + nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz + local q = #uv + uv[q + 1], uv[q + 2] = u, v + return k // 3 +end + +local function displacement(I: Input, g: Group, d: number, poly: { number }, nx: number, ny: number, nz: number, tex: { number }): string? + local di = I.dispinfo + if (d + 1) * 176 > di.size then + return "dispinfo index out of range" + end + local o = di.at + d * 176 + local b = di.buf + local vstart, power = readi32(b, o + 12), readi32(b, o + 20) + if #poly ~= 12 then + return nil -- not a quad: the base face is kept + end + if power < 1 or power > 4 then + return "displacement power " .. power + end + local n = 2 ^ power + 1 + local dv = I.dispverts + if vstart < 0 or (vstart + n * n) * 20 > dv.size then + return "displacement vertices out of range" + end + -- CDispVert: vector * dist, then alpha (0 .. 255) + local offsets: { number } = table.create(n * n * 3) :: any + for k = 0, n * n - 1 do + local vo = dv.at + (vstart + k) * 20 + local dist = readf32(dv.buf, vo + 12) + offsets[k * 3 + 1] = readf32(dv.buf, vo) * dist + offsets[k * 3 + 2] = readf32(dv.buf, vo + 4) * dist + offsets[k * 3 + 3] = readf32(dv.buf, vo + 8) * dist + end + local surf, err = Displacement.surface(poly, { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, power, offsets, { nx, ny, nz }) + if not surf then + return err + end + local base = #g.pos // 3 + local blend = g.blend or {} + g.blend = blend + local flat, pos, nrm = surf.flat, surf.pos, surf.nrm + for k = 0, n * n - 1 do + local x, y, z = flat[k * 3 + 1], flat[k * 3 + 2], flat[k * 3 + 3] + emit(g, pos[k * 3 + 1], pos[k * 3 + 2], pos[k * 3 + 3], nrm[k * 3 + 1], nrm[k * 3 + 2], nrm[k * 3 + 3], + (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9], (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10]) + blend[base + k + 1] = math.clamp(readf32(dv.buf, dv.at + (vstart + k) * 20 + 16) / 255, 0, 1) + end + local idx = g.idx + for _, v in surf.idx do + idx[#idx + 1] = base + v + end + return nil +end + +function Faces.build(I: Input): ({ Group }?, string?, number?) + local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, F.size // 56 + local nTI, nTD, nP = TI.size // 72, TD.size // 32, P.size // 20 + local faceModel: { [number]: number } = {} + local M = I.models + for m = 0, M.size // 48 - 1 do + local o = M.at + m * 48 + local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44) + if first >= 0 and count > 0 and first + count <= nF then + for f = first, first + count - 1 do + if faceModel[f] == nil then + faceModel[f] = m + end + end + end + end + local groups: { Group } = {} + local byKey: { [number]: Group } = {} + local skipped, verts = 0, 0 + local poly: { number } = {} + for f = 0, nF - 1 do + local fo = F.at + f * 56 + local fb = F.buf + local plane, side = readu16(fb, fo), readu8(fb, fo + 2) + local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8) + local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12) + local model = faceModel[f] or 0 + if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then + skipped += 1 + continue + end + local to = TI.at + ti * 72 + local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68) + if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then + continue + end + local w, h = 1, 1 + if td >= 0 and td < nTD then + w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1) + h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1) + else + td = -1 + end + table.clear(poly) + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local vi = readu16(E.buf, E.at + e * 4 + (if se >= 0 then 0 else 2)) + if vi >= nV then + ok = false + break + end + local vo = V.at + vi * 12 + poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8) + end + if not ok then + skipped += 1 + continue + end + local po = P.at + plane * 20 + local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + local key = model * 65536 + td + 1 + local grp: Group = byKey[key] + if not grp then + grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil :: { number }?, idx = {} } + byKey[key] = grp + table.insert(groups, grp) + end + local tex = { + readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12), + readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h, + } + local before = #grp.pos + local done = false + if disp >= 0 then + local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex) + if derr then + return nil, derr, fo + end + done = #grp.pos > before + end + if not done then + local n = numEdges + -- Newell's normal against the plane: the stored winding is clockwise from the front + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local a, b = k * 3, ((k + 1) % n) * 3 + ax += (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3]) + ay += (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1]) + az += (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2]) + end + local flip = ax * nx + ay * ny + az * nz < 0 + local first = -1 + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h) + if first < 0 then + first = id + end + end + local idx = grp.idx + for k = 1, n - 2 do + local b, c = first + k, first + k + 1 + if flip then + b, c = c, b + end + idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c + end + end + verts += (#grp.pos - before) // 3 + if verts > I.maxVertices then + return nil, "limit: over maxVertices", fo + end + end + return groups, nil, skipped +end + +function Faces.primitive(g: Group, material: number?): Types.Primitive + local prim = Displacement.primitive(g) + prim.material = material + return prim +end + +return Faces diff --git a/src/Rosetta/model/vbsp/Props.luau b/src/Rosetta/model/vbsp/Props.luau new file mode 100644 index 0000000..3226c9d --- /dev/null +++ b/src/Rosetta/model/vbsp/Props.luau @@ -0,0 +1,90 @@ +--!strict +-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and +-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the +-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale +-- (v13: last 3 f32), u32 leaf indices (v12+). +local Props = {} + +local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32 + +export type Prop = { + model: string, + origin: { number }, + angles: { number }, -- pitch, yaw, roll (degrees) + scale: { number }, + skin: number, + solid: number, + flags: number, + fadeMin: number, + fadeMax: number, + fadeScale: number?, + lightingOrigin: { number }, +} + +function Props.read(b: buffer, at: number, size: number, version: number, maxProps: number): ({ Prop }?, string?) + local e = at + size + local p = at + if p + 4 > e then + return {}, nil + end + local nd = readi32(b, p) + p += 4 + if nd < 0 or p + nd * 128 > e then + return nil, "static prop model names past the end" + end + local names: { string } = table.create(nd) :: any + for i = 0, nd - 1 do + names[i + 1] = string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") :: string + end + p += nd * 128 + if p + 4 > e then + return nil, "static prop leaves truncated" + end + local nl = readi32(b, p) + p += 4 + local leafSize = if version >= 12 then 4 else 2 + if nl < 0 or p + nl * leafSize + 4 > e then + return nil, "static prop leaves past the end" + end + p += nl * leafSize + local np = readi32(b, p) + p += 4 + if np < 0 or np > maxProps then + return nil, "limit: " .. np .. " static props" + end + local out: { Prop } = table.create(np) :: any + if np == 0 then + return out, nil + end + local rec = (e - p) // np + if rec < 56 then + return nil, "static prop records shorter than 56 bytes" + end + for i = 0, np - 1 do + local o = p + i * rec + local mi = readu16(b, o + 24) + local scale = { 1, 1, 1 } + if version == 13 and rec >= 88 then + scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) } + elseif (version == 11 or version == 12) and rec >= 80 then + local s = readf32(b, o + rec - 4) + scale = { s, s, s } + end + out[i + 1] = { + model = names[mi + 1] or "", + origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, + angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) }, + scale = scale, + solid = readu8(b, o + 30), + flags = readu8(b, o + 31), + skin = readi32(b, o + 32), + fadeMin = readf32(b, o + 36), + fadeMax = readf32(b, o + 40), + lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) }, + fadeScale = if version >= 5 and rec >= 60 then readf32(b, o + 56) else nil, + } + end + return out, nil +end + +return Props diff --git a/src/Rosetta/model/vbsp/init.luau b/src/Rosetta/model/vbsp/init.luau new file mode 100644 index 0000000..95449f8 --- /dev/null +++ b/src/Rosetta/model/vbsp/init.luau @@ -0,0 +1,444 @@ +--!strict +-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read, +-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and +-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by +-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a +-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360 +-- (big-endian) and Titanfall / Apex rBSP, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Types = require("@rosetta/Types") +local Lzma = require("@rosetta/codecs/compress/Lzma") +local KeyValues = require("@rosetta/codecs/text/KeyValues") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Zip = require("@rosetta/containers/Zip") +local Archive = require("@rosetta/containers/Archive") +local Faces = require("@rosetta/model/vbsp/Faces") +local Props = require("@rosetta/model/vbsp/Props") + +-- ------------------------------------------------------------------------------------------------ contract +local Vbsp = { + name = "vbsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + tools: boolean?, -- keep nodraw / skip / hint / sky faces, default false + pak: boolean?, -- meta.pak and textures from it, default true + maxBytes: number?, -- per decompressed lump, default 2^28 + maxVertices: number?, -- default 2^24 + maxProps: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ constants +local L = { + ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13, + MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43, + TEXDATA_STRING_TABLE = 44, FACES_HDR = 58, +} +local HEADER = 8 + 64 * 16 + 4 +local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vbsp.sniff(r: Bytes.Reader): number + if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return if v >= 19 and v <= 21 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Lump = Faces.Lump + +local function angles(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +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] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end + +local function vec3(s: any): { number }? + if type(s) ~= "string" then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream +local function unlzma(b: buffer, at: number, size: number, maxBytes: number): (buffer?, string?) + if size < 17 then + return nil, "truncated LZMA lump header" + end + local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8) + if actual > maxBytes then + return nil, "limit: LZMA lump of " .. actual .. " bytes" + end + if packed > size - 17 then + return nil, "LZMA lump runs past the end" + end + local props = buffer.create(5) + buffer.copy(props, 0, b, at + 12, 5) + local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes }) + if not out then + return nil, "LZMA lump: " .. tostring(if type(err) == "table" then err.message else err) + end + return out, nil +end + +local function isLzma(b: buffer, at: number, size: number): boolean + return size >= 17 and buffer.readstring(b, at, 4) == "LZMA" +end + +local function pakArchive(src: buffer, maxBytes: number): (any, Err.Err?) + local zc, err = Zip.open(src) + if not zc then + return nil, err + end + local a = Archive.new("zip") + for _, e in zc:list() do + local entry: any = { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = if e.method == 0 then "stored" elseif e.method == 8 then "deflate" elseif e.method == 14 then "lzma" else tostring(e.method), + mtime = e.mtime, + dir = e.isDir, + } + entry.load = function(): (buffer?, Err.Err?) + if e.method ~= 14 then + return zc:read(e) + end + -- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks) + local zb = zc.buf + for _, s in Zip._starts(zb, e) do + if s + 9 <= buffer.len(zb) then + local psize = buffer.readu16(zb, s + 2) + local start = s + 4 + psize + local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start) + if psize >= 5 and n > 0 and e.size <= maxBytes then + local props = buffer.create(5) + buffer.copy(props, 0, zb, s + 4, 5) + local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes }) + if out then + return out, nil + end + end + end + end + return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry") + end + Archive.put(a, entry) + end + a.meta.source = { format = "zip", lump = "pakfile" } + return a, nil +end + +local function light(scene: Types.Scene, e: any, class: string): (number?, { number }?) + local l = vec3(e._light) + local rgb: { number } = { 1, 1, 1 } + local intensity = 1 + if l then + rgb = { l[1] / 255, l[2] / 255, l[3] / 255 } + local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)") + intensity = (m and tonumber(m)) or 200 + end + local lt: Types.Light = nil :: any + if class == "light" then + lt = { name = nil :: string?, type = "point", color = rgb, intensity = intensity } + elseif class == "light_spot" then + local outer = tonumber(e._cone) or 45 + local inner = tonumber(e._inner_cone) or math.min(30, outer) + lt = { name = nil :: string?, type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) } + else + lt = { name = nil :: string?, type = "directional", color = rgb, intensity = intensity } + end + lt.name = if type(e.targetname) == "string" then e.targetname else class + table.insert(scene.lights, lt :: any) + local ang = vec3(e.angles) or { 0, 0, 0 } + if type(e.pitch) == "string" and tonumber(e.pitch) then + ang[1] = -(tonumber(e.pitch) :: number) -- the FGD's angle_negative_pitch + end + -- the light shines along the entity's forward (+x); a glTF light along -z + return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90)) +end + +function Vbsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base = r.buf, r.base + local size = r.limit - r.base + if size < HEADER then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VBSP" then + return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0) + end + local version = buffer.readi32(b, base + 4) + if version < 19 or version > 21 then + return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4) + end + local maxBytes = o.maxBytes or 2 ^ 28 + -- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036 + local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER + local dir: { { at: number, size: number, version: number, fourcc: number } } = {} + for i = 0, 63 do + local p = base + 8 + i * 16 + local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12) + local at, n, v = a, c, d + if l4d2 then + v, at, n = a, c, d + end + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base) + end + dir[i] = { at = at, size = n, version = v, fourcc = f } + end + local cache: { [number]: Lump } = {} + local compressed = false + local function lump(i: number): (Lump?, string?) + local c = cache[i] + if c then + return c, nil + end + local d = dir[i] + local out: Lump + if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then + local u, err = unlzma(b, base + d.at, d.size, maxBytes) + if not u then + return nil, "lump " .. i .. ": " .. tostring(err) + end + compressed = true + out = { buf = u, at = 0, size = buffer.len(u) } + else + out = { buf = b, at = base + d.at, size = d.size } + end + cache[i] = out + return out, nil + end + local need: { [string]: Lump } = {} + for name, idx in { planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES } :: { [string]: number } do + local lp, err = lump(idx) + if not lp then + return nil, Err.from(err) + end + need[name] = lp + end + if need.faces.size == 0 then + local hdr, err = lump(L.FACES_HDR) + if not hdr then + return nil, Err.from(err) + end + need.faces = hdr + end + local groups, ferr, skipped = Faces.build({ + planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges, + faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models, + dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true, + maxVertices = o.maxVertices or 2 ^ 24, + }) + if not groups then + return nil, Err.from(ferr, skipped and skipped - base) + end + + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + + local pak: any = nil + local pd = dir[L.PAKFILE] + if o.pak ~= false and pd.size > 0 then + local src = buffer.create(pd.size) + buffer.copy(src, 0, b, base + pd.at, pd.size) + pak = pakArchive(src, maxBytes) + scene.meta.pak = pak + end + + -- texdata -> material + texture (materials/.vtf, from the pak when it is there) + local TD, ST, SS = need.texdata, need.table, need.strings + local nTD = TD.size // 32 + local matOf: { [number]: number } = {} + local function material(td: number): number? + if td < 0 or td >= nTD then + return nil + end + local m = matOf[td] + if m then + return m + end + local to = TD.at + td * 32 + local si = buffer.readi32(TD.buf, to + 12) + local name = "texdata" .. td + if si >= 0 and (si + 1) * 4 <= ST.size then + local off = buffer.readi32(ST.buf, ST.at + si * 4) + if off >= 0 and off < SS.size then + name = string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") :: string + end + end + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + local tex: Types.Texture = { name = name, uri = path .. ".vtf" } + if pak then + local zc = pak :: any + local ok, data = pcall(zc.read, zc, path .. ".vtf") + if ok and type(data) == "buffer" then + tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil + end + end + table.insert(scene.textures, tex) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { + vbsp = { + vmt = path .. ".vmt", + width = buffer.readi32(TD.buf, to + 16), + height = buffer.readi32(TD.buf, to + 20), + reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) }, + }, + } + table.insert(scene.materials, mat) + matOf[td] = #scene.materials + return #scene.materials + end + + local root: Types.Node = { name = "vbsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelNode: { [number]: number } = {} + for _, g in groups do + local node = modelNode[g.model] + if not node then + local name = if g.model == 0 then "world" else "*" .. g.model + table.insert(scene.meshes, { name = name, primitives = {} }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } }) + node = #scene.nodes + modelNode[g.model] = node + table.insert(root.children, node) + end + local mesh = scene.meshes[scene.nodes[node].mesh :: number] + table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata))) + end + + -- entities + local E = need.entities + local text = string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") :: string + local blocks, eerr = KeyValues.entities(text) + if not blocks then + return nil, Err.new((eerr :: Err.Err).code, "entity lump: " .. (eerr :: Err.Err).message, dir[L.ENTITIES].at) + end + local ents: { any } = table.create(#blocks) + for i, blk in blocks do + local e = KeyValues.toObject(blk) + ents[i] = e + local class = if type(e.classname) == "string" then e.classname else "" + local mdl = if type(e.model) == "string" then string.match(e.model, "^%*(%d+)$") else nil + local mi = mdl and tonumber(mdl) + if mi and mi > 0 and modelNode[mi] then + local node = scene.nodes[modelNode[mi]] + node.name = if type(e.targetname) == "string" then e.targetname else class + local org = vec3(e.origin) + if org then + node.translation = org + end + local ang = vec3(e.angles) + if ang then + node.rotation = angles(ang[1], ang[2], ang[3]) + end + local x: any = node.extras + x.vbsp.entity = i + elseif class == "light" or class == "light_spot" or class == "light_environment" then + local li, rot = light(scene, e, class) + table.insert(scene.nodes, { name = scene.lights[li :: number].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.entities = ents + + -- game lumps + local spVersion: number? = nil + local G = dir[L.GAME_LUMP] + if G.size >= 4 then + local ga = base + G.at + local count = buffer.readi32(b, ga) + if count < 0 or 4 + count * 16 > G.size then + return nil, Err.new(Err.CORRUPT, "game lump directory", G.at) + end + for k = 0, count - 1 do + local eo = ga + 4 + k * 16 + local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6) + local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12) + if id == SPRP then + if off < 0 or len < 0 or off > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local pb, pat, plen = b, base + off, len + if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then + if off + 17 > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local u, err = unlzma(b, base + off, size - off, maxBytes) + if not u then + return nil, Err.from(err, off) + end + pb, pat, plen = u, 0, buffer.len(u) + compressed = true + elseif off + len > size then + return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base) + end + local props, perr = Props.read(pb, pat, plen :: number, ver, o.maxProps or 2 ^ 20) + if not props then + return nil, Err.from(perr, off) + end + spVersion = ver + for pi, p in props do + local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model + table.insert(scene.nodes, { + name = nm, + children = {}, + translation = p.origin, + rotation = angles(p.angles[1], p.angles[2], p.angles[3]), + scale = if p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 then p.scale else nil, + extras = { + model = p.model, + vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin }, + }, + }) + table.insert(root.children, #scene.nodes) + end + end + end + end + + scene.meta.skippedFaces = skipped + scene.meta.source = { + format = "vbsp", + version = version, + variant = if l4d2 then "l4d2" else "v" .. version, + mapRevision = buffer.readi32(b, base + HEADER - 4), + compressed = compressed, + staticPropVersion = spVersion, + entities = text, + } + return scene, nil +end + +return Vbsp diff --git a/src/Rosetta/model/vmf/Build.luau b/src/Rosetta/model/vmf/Build.luau new file mode 100644 index 0000000..b4a1991 --- /dev/null +++ b/src/Rosetta/model/vmf/Build.luau @@ -0,0 +1,422 @@ +--!strict +-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes +-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one +-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras. +local Types = require("@rosetta/Types") +local KeyValues = require("@rosetta/codecs/text/KeyValues") +local Brush = require("@rosetta/codecs/model/Brush") +local Displacement = require("@rosetta/codecs/model/Displacement") +local Mat4 = require("@rosetta/codecs/model/Mat4") + +local Build = {} + +type Block = KeyValues.Block + +export type Side = { + id: number?, + points: { number }, -- 9: the plane's three points + material: string, + uaxis: { number }, -- x, y, z, shift, scale + vaxis: { number }, + disp: Block?, +} +export type Solid = { id: number?, sides: { Side }, editor: any, entity: number } +export type Options = { + tools: boolean, + size: (name: string) -> (number, number, boolean), + maxPolygons: number?, +} + +local function nums(s: any): { number } + local out: { number } = {} + if type(s) ~= "string" then + return out + end + for w in string.gmatch(s, "[^%s%(%)%[%]]+") do + local n = tonumber(w) + if n then + table.insert(out, n) + end + end + return out +end +Build.nums = nums + +local function get(b: Block, key: string): any + return KeyValues.get(b, key) +end + +local function editor(b: Block): any + local e = KeyValues.find(b, "editor") + return if e and type(e.value) == "table" then KeyValues.toObject(e.value) else nil +end + +function Build.solid(b: Block, entity: number): (Solid?, string?) + local sides: { Side } = {} + for _, p in KeyValues.all(b, "side") do + if type(p.value) == "table" then + local sb = p.value :: Block + local pts = nums(get(sb, "plane")) + if #pts ~= 9 then + return nil, "side without a 3-point plane" + end + local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis")) + local d = KeyValues.find(sb, "dispinfo") + table.insert(sides, { + id = tonumber(get(sb, "id")), + points = pts, + material = tostring(get(sb, "material") or ""), + uaxis = if #u >= 5 then u else { 1, 0, 0, 0, 1 }, + vaxis = if #v >= 5 then v else { 0, -1, 0, 0, 1 }, + disp = if d and type(d.value) == "table" then d.value :: Block else nil, + }) + end + end + return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil +end + +function Build.face(s: Side): Brush.Face? + local p = s.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) } +end + +local function rows(d: Block, name: string, per: number, n: number): { number }? + local blk = KeyValues.get(d, name) + if type(blk) ~= "table" then + return nil + end + local out: { number } = table.create(n * n * per, 0) :: any + for i = 0, n - 1 do + local r = nums(KeyValues.get(blk, "row" .. i)) + for k = 1, math.min(#r, n * per) do + out[i * n * per + k] = r[k] + end + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number }, blend: { number } } + +-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp) +local function displace(s: Side, face: Brush.Face, poly: Brush.Polygon, acc: Acc, w: number, h: number): string? + local d = s.disp :: Block + local power = tonumber(KeyValues.get(d, "power")) or 0 + if power < 1 or power > 4 or power % 1 ~= 0 then + return "displacement power " .. tostring(power) + end + local n = 2 ^ power + 1 + local start = nums(KeyValues.get(d, "startposition")) + if #start < 3 then + return "displacement without a start position" + end + local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n) + local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n) + local elev = tonumber(KeyValues.get(d, "elevation")) or 0 + local pn = face.plane + local offsets: { number } = table.create(n * n * 3, 0) :: any + for k = 0, n * n - 1 do + for c = 1, 3 do + local v = elev * pn[c] + if normals and dists then + v += normals[k * 3 + c] * dists[k + 1] + end + if offs then + v += offs[k * 3 + c] + end + offsets[k * 3 + c] = v + end + end + -- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise + local pts = poly.points + local cw: { number } = {} + for k = #pts // 3 - 1, 0, -1 do + table.insert(cw, pts[k * 3 + 1]) + table.insert(cw, pts[k * 3 + 2]) + table.insert(cw, pts[k * 3 + 3]) + end + local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] }) + if not surf then + return err + end + local base = #acc.pos // 3 + for k = 0, n * n - 1 do + local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3] + for c = 1, 3 do + table.insert(acc.pos, surf.pos[k * 3 + c]) + table.insert(acc.nrm, surf.nrm[k * 3 + c]) + end + local u, v = Brush.uv(face, x, y, z, w, h) + table.insert(acc.uv, u) + table.insert(acc.uv, v) + table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1)) + end + for _, i in surf.idx do + table.insert(acc.idx, base + i) + end + return nil +end + +local function isTool(name: string): boolean + return string.sub(string.lower(name), 1, 6) == "tools/" +end + +-- the solids of one entity -> its primitives (material indices by name through matOf) +function Build.mesh(solids: { Solid }, o: Options, matOf: (string) -> number, name: string): (Types.Mesh?, string?) + local brushes: { { Brush.Face } } = {} + local sideOf: { { Side } } = {} + local hasDisp: { boolean } = {} + for _, s in solids do + local faces: { Brush.Face } = {} + local sides: { Side } = {} + local disp = false + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(sides, sd) + disp = disp or sd.disp ~= nil + end + end + if #faces >= 4 then + table.insert(brushes, faces) + table.insert(sideOf, sides) + table.insert(hasDisp, disp) + end + end + local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons }) + if not polys then + return nil, perr + end + local keep: { Brush.Polygon } = {} + local disps: { [string]: Acc } = {} + local dispOrder: { string } = {} + for _, p in polys do + local sd = sideOf[p.brush][p.face] + if o.tools or not isTool(sd.material) then + if sd.disp then + local acc = disps[sd.material] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} } + disps[sd.material] = acc + table.insert(dispOrder, sd.material) + end + local w, h = o.size(sd.material) + local err = displace(sd, brushes[p.brush][p.face], p, acc :: Acc, w, h) + if err then + return nil, err + end + elseif not hasDisp[p.brush] then + table.insert(keep, p) + end + end + end + local mesh: Types.Mesh = { name = name, primitives = {} } + local function size(n: string): (number, number) + local w, h = o.size(n) + return w, h + end + for _, b in Brush.primitives(keep, brushes, size) do + b.primitive.material = matOf(b.texture) + table.insert(mesh.primitives, b.primitive) + end + for _, m in dispOrder do + local prim = Displacement.primitive(disps[m] :: any) + prim.material = matOf(m) + table.insert(mesh.primitives, prim) + end + return mesh, nil +end + +local function quat(p: number, y: number, r: number): { number } + return Mat4.quat(Mat4.euler(r, p, y, "xyz")) +end + +-- a camera at position looking at look, z up: glTF cameras look along -z with +y up +local function lookAt(pos: { number }, look: { number }): { number } + local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3] + local l = math.sqrt(fx * fx + fy * fy + fz * fz) + if l < 1e-9 then + return { 0, 0, 0, 1 } + end + fx, fy, fz = fx / l, fy / l, fz / l + local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1) + local rl = math.sqrt(rx * rx + ry * ry) + if rl < 1e-9 then + rx, ry, rl = 1, 0, 1 + end + rx, ry = rx / rl, ry / rl + local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f + return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +local function visgroups(b: Block): { any } + local out = {} + for _, p in KeyValues.all(b, "visgroup") do + if type(p.value) == "table" then + local v = p.value :: Block + table.insert(out, { + name = KeyValues.get(v, "name"), + id = tonumber(KeyValues.get(v, "visgroupid")), + color = KeyValues.get(v, "color"), + children = visgroups(v), + }) + end + end + return out +end + +-- solids of a block, including those inside its hidden { } blocks +local function solidsOf(b: Block, entity: number, out: { Solid }): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: Block, entity) + if not s then + return err + end + table.insert(out, s) + elseif k == "hidden" then + local err = solidsOf(p.value :: Block, entity, out) + if err then + return err + end + end + end + end + return nil +end + +function Build.scene(doc: Block, o: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.0254 + local mats: { [string]: number } = {} + local function matOf(name: string): number + local m = mats[name] + if m then + return m + end + local w, h, known = o.size(name) + local path = "materials/" .. string.lower((string.gsub(name, "\\", "/"))) + table.insert(scene.textures, { name = name, uri = path .. ".vtf" }) + local mat = Types.Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + mats[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "vmf", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local ents: { any } = {} + local solidsMeta: { any } = {} + local groups: { any } = {} + -- world and entities, hidden ones included + local blocks: { { key: string, block: Block } } = {} + for _, p in doc do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "world" or k == "entity" then + table.insert(blocks, { key = k, block = p.value :: Block }) + elseif k == "hidden" then + for _, q in KeyValues.all(p.value :: Block, "entity") do + if type(q.value) == "table" then + table.insert(blocks, { key = "entity", block = q.value :: Block }) + end + end + end + end + end + for _, item in blocks do + local b = item.block + local keys: Block = {} + local conns: any = nil + for _, p in b do + if type(p.value) == "string" then + table.insert(keys, p) + elseif string.lower(p.key) == "connections" then + conns = KeyValues.toObject(p.value :: Block) + elseif item.key == "world" and string.lower(p.key) == "group" then + local g = p.value :: Block + table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) }) + end + end + local e = KeyValues.toObject(keys) + if conns then + e.connections = conns + end + table.insert(ents, e) + local ei = #ents + local solids: { Solid } = {} + local serr = solidsOf(b, ei, solids) + if serr then + return nil, serr + end + local class = if type(e.classname) == "string" then e.classname else item.key + local name = if item.key == "world" then "world" elseif type(e.targetname) == "string" then e.targetname else class + local node: Types.Node = { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } } + if #solids > 0 then + local mesh, merr = Build.mesh(solids, o, matOf, name) + if not mesh then + return nil, merr + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + for _, s in solids do + table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor }) + end + else + local org = nums(e.origin) + if #org >= 3 then + node.translation = { org[1], org[2], org[3] } + end + local ang = nums(e.angles) + if #ang >= 3 then + node.rotation = quat(ang[1], ang[2], ang[3]) + end + if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then + (node.extras :: any).model = e.model + end + end + if node.mesh or item.key ~= "world" then + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + end + -- cameras + local cams = KeyValues.get(doc, "cameras") + local camMeta: any = nil + if type(cams) == "table" then + camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} } + for _, p in KeyValues.all(cams, "camera") do + if type(p.value) == "table" then + local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look")) + if #pos >= 3 and #look >= 3 then + local cam: Types.Camera = { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 } + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) }) + table.insert(root.children, #scene.nodes) + table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } }) + end + end + end + end + local vg = KeyValues.get(doc, "visgroups") + scene.meta.entities = ents + scene.meta.solids = solidsMeta + scene.meta.groups = groups + scene.meta.visgroups = if type(vg) == "table" then visgroups(vg) else {} + scene.meta.cameras = camMeta + return scene, nil +end + +return Build diff --git a/src/Rosetta/model/vmf/init.luau b/src/Rosetta/model/vmf/init.luau new file mode 100644 index 0000000..1cc58bb --- /dev/null +++ b/src/Rosetta/model/vmf/init.luau @@ -0,0 +1,323 @@ +--!strict +-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush +-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement, +-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in +-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from +-- opts.textureSizes, materials/.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances +-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Sniff = require("@rosetta/core/Sniff") +local Types = require("@rosetta/Types") +local KeyValues = require("@rosetta/codecs/text/KeyValues") +local Build = require("@rosetta/model/vmf/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Vmf = { + name = "vmf", + category = "model", + extensions = { "vmf", "vmx" }, + mime = { "model/x-vmf" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, displacements = true, roundTrip = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + tools: boolean?, -- keep tools/* materials (nodraw, clip, trigger, skybox, ...), default false + textureSizes: { [string]: { number } }?, -- material name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> any)?, + maxPolygons: number?, -- default 2^20 +} +export type EncodeOptions = {} +export type SideSpec = { + points: { { number } }, -- three points, clockwise seen from outside (Hammer) + material: string?, + uaxis: { number }?, -- x, y, z, shift, scale; default from the face's dominant axis + vaxis: { number }?, + rotation: number?, + lightmapscale: number?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Vmf.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then + return 0.9 + end + if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function sizer(opts: DecodeOptions?): (string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h, known = 512, 512, false + local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)]) + if given and type(given[1]) == "number" and type(given[2]) == "number" then + w, h, known = given[1], given[2], true + elseif opts and opts.decodeImage then + local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf") + if data then + local ok, img = pcall(opts.decodeImage :: any, data) + if ok and type(img) == "table" and type(img.width) == "number" then + w, h, known = img.width, img.height, true + end + end + end + cache[name] = { w, h, if known then 1 else 0 } + return w, h, known + end +end + +function Vmf.parse(src: buffer | string): (KeyValues.Block?, Err.Err?) + return KeyValues.parse(src, { escapes = "quotes", defines = false }) +end + +function Vmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, err + end + local scene, msg = Build.scene(doc, { + tools = opts ~= nil and opts.tools == true, + size = sizer(opts), + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(msg) + end + local vi = KeyValues.get(doc, "versioninfo") + local info: any = if type(vi) == "table" then KeyValues.toObject(vi) else {} + scene.meta.vmf = doc + scene.meta.source = { + format = "vmf", + editorVersion = tonumber(info.editorversion), + editorBuild = tonumber(info.editorbuild), + mapVersion = tonumber(info.mapversion), + formatVersion = tonumber(info.formatversion), + prefab = info.prefab == "1", + } + return scene, nil +end + +-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world) +function Vmf.brushes(doc: KeyValues.Block): ({ { id: number?, entity: number, faces: { any }, materials: { string } } }?, Err.Err?) + local out = {} + local entity = 0 + local function walk(b: KeyValues.Block): string? + for _, p in b do + if type(p.value) == "table" then + local k = string.lower(p.key) + if k == "solid" then + local s, err = Build.solid(p.value :: KeyValues.Block, entity) + if not s then + return err + end + local faces, mats = {}, {} + for _, sd in s.sides do + local f = Build.face(sd) + if f then + table.insert(faces, f) + table.insert(mats, sd.material) + end + end + table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats }) + elseif k == "hidden" then + local err = walk(p.value :: KeyValues.Block) + if err then + return err + end + end + end + end + return nil + end + for _, p in doc do + local k = string.lower(p.key) + if type(p.value) == "table" and (k == "world" or k == "entity") then + entity += 1 + local err = walk(p.value :: KeyValues.Block) + if err then + return nil, Err.new(Err.CORRUPT, err) + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Hammer writes dispinfo rows at their block's own indent +local FLAT: { [string]: boolean } = {} +for _, k in { "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" } do + FLAT[k] = true +end + +function Vmf.encode(value: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local doc = value + if type(value) == "table" and value.kind == "scene" then + doc = value.meta and value.meta.vmf + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written") + end + end + if type(doc) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document") + end + local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function fmt(x: number): string + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + return (string.gsub(string.format("%.6f", x), "%.?0+$", "")) +end + +local function kv(k: string, v: string): KeyValues.Pair + return { key = k, value = v } +end + +-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls) +local function defaultAxes(points: { { number } }): ({ number }, { number }) + local a, b, c = points[1], points[2], points[3] + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx) + if nz >= nx and nz >= ny then + return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 } + elseif nx >= ny then + return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } + end + return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 } +end + +local function id(given: number?, default: number): string + return fmt(given or default) +end + +function Vmf.side(s: SideSpec, sideId: number?): KeyValues.Pair + local p = s.points + local du, dv = defaultAxes(p) + local u, v = s.uaxis or du, s.vaxis or dv + local function axis(x: { number }): string + return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25) + end + local function pt(x: { number }): string + return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")" + end + return { key = "side", value = { + kv("id", id(sideId, 1)), + kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])), + kv("material", s.material or "TOOLS/TOOLSNODRAW"), + kv("uaxis", axis(u)), + kv("vaxis", axis(v)), + kv("rotation", fmt(s.rotation or 0)), + kv("lightmapscale", fmt(s.lightmapscale or 16)), + kv("smoothing_groups", "0"), + } } +end + +function Vmf.solid(sides: { SideSpec }, solidId: number?): KeyValues.Pair + local blk: KeyValues.Block = { kv("id", id(solidId, 1)) } + for i, s in sides do + table.insert(blk, Vmf.side(s, i)) + end + table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } }) + return { key = "solid", value = blk } +end + +-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north, +-- south) +function Vmf.box(lo: { number }, hi: { number }, material: string | { string }, solidId: number?): KeyValues.Pair + local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] + local function m(i: number): string + return if type(material) == "table" then material[i] or material[1] else material + end + return Vmf.solid({ + { points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) }, + { points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) }, + { points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) }, + { points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) }, + { points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) }, + { points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) }, + }, solidId) +end + +-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons +function Vmf.document(worldKeys: { [string]: string }?): KeyValues.Block + local world: KeyValues.Block = { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") } + if worldKeys then + local keys = {} + for k in worldKeys do + table.insert(keys, k) + end + table.sort(keys) + for _, k in keys do + table.insert(world, kv(k, worldKeys[k])) + end + end + return { + { key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } }, + { key = "visgroups", value = {} }, + { key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } }, + { key = "world", value = world }, + { key = "cameras", value = { kv("activecamera", "-1") } }, + { key = "cordons", value = { kv("active", "0") } }, + } +end + +-- an entity block (keys in the given order, then its solids) appended to doc before cameras +function Vmf.entity(doc: KeyValues.Block, keys: { { string } }, solids: { KeyValues.Pair }?): KeyValues.Pair + local count = 1 + for _, p in doc do + if string.lower(p.key) == "entity" then + count += 1 + end + end + local blk: KeyValues.Block = { kv("id", id(nil, count + 1)) } + for _, k in keys do + table.insert(blk, kv(k[1], k[2])) + end + for _, s in solids or {} do + table.insert(blk, s) + end + local pair = { key = "entity", value = blk } + local at = #doc + 1 + for i, p in doc do + if string.lower(p.key) == "cameras" then + at = i + break + end + end + table.insert(doc, at, pair) + return pair +end + +-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...))) +function Vmf.world(doc: KeyValues.Block): KeyValues.Block? + local w = KeyValues.get(doc, "world") + return if type(w) == "table" then w else nil +end + +return Vmf diff --git a/tests/codecs/brush.luau b/tests/codecs/brush.luau new file mode 100644 index 0000000..174a3b1 --- /dev/null +++ b/tests/codecs/brush.luau @@ -0,0 +1,224 @@ +-- codecs/model/Brush tests: random overlapping brushes in Quake standard / Valve 220 / brush-primitive projections +-- against ericw-tools qbsp -nofill (face area per plane after CSG, texture coordinates at every compiled corner); +-- merging, the primitive builder, the fuzz pass. Fixtures: tools/fixtures/brush.py. +local T = require("@tests/T") +local Brush = require("@rosetta/codecs/model/Brush") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/brush") + +local t = T.suite("brush") + +local function faceOf(rec: any): Brush.Face? + local p = rec.pts + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local a = rec.args + local f: Brush.Face = { plane = plane, texture = rec.tex } + if rec.kind == "standard" then + f.vecs = Brush.quakeVecs(plane, a[1], a[2], a[3], a[4], a[5]) + elseif rec.kind == "valve" then + f.vecs = Brush.valveVecs({ a[1], a[2], a[3], a[4] }, { a[5], a[6], a[7], a[8] }, a[10], a[11]) + else + f.bp = { { a[1], a[2], a[3] }, { a[4], a[5], a[6] } } + end + return f +end + +local function key(n: { number }): string + local function r(x: number, k: number): number + return math.floor(x * k + 0.5) + end + return string.format("%d %d %d %d", r(n[1], 1000), r(n[2], 1000), r(n[3], 1000), r(n[4], 100)) +end + +local function inside(pts: { number }, n: { number }, x: number, y: number, z: number, tol: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local j = (i + 1) % k + local ex, ey, ez = pts[j * 3 + 1] - pts[i * 3 + 1], pts[j * 3 + 2] - pts[i * 3 + 2], pts[j * 3 + 3] - pts[i * 3 + 3] + -- inward edge normal = n x e (counter-clockwise polygons) + local ix, iy, iz = n[2] * ez - n[3] * ey, n[3] * ex - n[1] * ez, n[1] * ey - n[2] * ex + local l = math.sqrt(ix * ix + iy * iy + iz * iz) + if l > 0 and ((x - pts[i * 3 + 1]) * ix + (y - pts[i * 3 + 2]) * iy + (z - pts[i * 3 + 3]) * iz) / l < -tol then + return false + end + end + return true +end + +for kind, m in Fx do + local brushes: { { Brush.Face } } = {} + for _, b in m.brushes do + local faces = {} + for _, rec in b do + table.insert(faces, assert(faceOf(rec))) + end + table.insert(brushes, faces) + end + local polys = assert(Brush.polygons(brushes, { hull = true })) + -- area per plane: ours after CSG = qbsp's faces (split by its BSP, merged, subdivided) + local ours, theirs = {}, {} + for _, p in polys do + local k = key(brushes[p.brush][p.face].plane) + ours[k] = (ours[k] or 0) + Brush.area(p.points) + end + for _, f in m.faces do + local k = key(f.plane) + theirs[k] = (theirs[k] or 0) + Brush.area(f.pts) + end + local bad = 0 + for k, a in theirs do + if math.abs((ours[k] or 0) - a) > 0.05 then + bad += 1 + t:note("%s: plane %s area %s, qbsp %s", kind, k, tostring(ours[k]), tostring(a)) + end + end + for k in ours do + if not theirs[k] then + bad += 1 + t:note("%s: plane %s only in ours", kind, k) + end + end + t:eq(bad, 0, kind .. ": face area per plane matches qbsp") + -- every compiled corner lies on one of our polygons with the same texture, and maps to the same texels + local miss, off, worst = 0, 0, 0 + local corners = 0 + for _, f in m.faces do + local pk = key(f.plane) + for c = 0, #f.pts // 3 - 1 do + local x, y, z = f.pts[c * 3 + 1], f.pts[c * 3 + 2], f.pts[c * 3 + 3] + corners += 1 + local s = f.vecs[1] * x + f.vecs[2] * y + f.vecs[3] * z + f.vecs[4] + local tt = f.vecs[5] * x + f.vecs[6] * y + f.vecs[7] * z + f.vecs[8] + local found = false + local best = math.huge + for _, p in polys do + local face = brushes[p.brush][p.face] + if face.texture == f.tex and key(face.plane) == pk and inside(p.points, p.normal, x, y, z, 0.02) then + found = true + local size = m.sizes[f.tex] + local u, v = Brush.uv(face, x, y, z, size[1], size[2]) + best = math.min(best, math.max(math.abs(u * size[1] - s), math.abs(v * size[2] - tt))) + end + end + if not found then + miss += 1 + local any = {} + for _, p in polys do + local face = brushes[p.brush][p.face] + if key(face.plane) == pk and inside(p.points, p.normal, x, y, z, 0.02) then + table.insert(any, face.texture .. "#" .. p.brush) + end + end + t:note("%s miss %s %s %s on %s tex %s: ours %s", kind, x, y, z, pk, f.tex, table.concat(any, ",")) + elseif best > 0.02 then + off += 1 + t:note("%s off %s %s %s on %s tex %s best %s vecs %s", kind, x, y, z, pk, f.tex, best, table.concat(f.vecs, " ")) + worst = math.max(worst, best) + end + end + end + t:eq(miss, 0, kind .. ": every qbsp corner is on one of our faces (" .. corners .. " corners)") + t:eq(off, 0, kind .. ": texture coordinates match qbsp's texinfo (worst " .. worst .. " texels)") + -- primitives: counter-clockwise about the face normals, one per texture + local built = Brush.primitives(polys, brushes, function(name: string) + local s = m.sizes[name] + return s[1], s[2] + end) + local seen, wrong = {}, 0 + for _, b in built do + t:check(not seen[b.texture], kind .. ": one primitive per texture " .. b.texture) + seen[b.texture] = true + local prim = b.primitive + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local nrm = Types.Scene.reader(prim.attributes.NORMAL) :: any + local idx = prim.indices :: Types.Accessor + for k = 0, idx.count - 1, 3 do + local i0, i1, i2 = buffer.readu32(idx.data, k * 4), buffer.readu32(idx.data, k * 4 + 4), buffer.readu32(idx.data, k * 4 + 8) + local ux, uy, uz = pos(i1, 0) - pos(i0, 0), pos(i1, 1) - pos(i0, 1), pos(i1, 2) - pos(i0, 2) + local vx, vy, vz = pos(i2, 0) - pos(i0, 0), pos(i2, 1) - pos(i0, 1), pos(i2, 2) - pos(i0, 2) + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + if cx * nrm(i0, 0) + cy * nrm(i0, 1) + cz * nrm(i0, 2) <= 0 then + wrong += 1 + end + end + end + t:eq(wrong, 0, kind .. ": triangles counter-clockwise about their normals") + -- merging keeps the area per plane + local merged = assert(Brush.polygons(brushes, { hull = true, merge = true })) + t:check(#merged <= #polys, kind .. ": merge does not add polygons") + local after = {} + for _, p in merged do + local k = key(brushes[p.brush][p.face].plane) + after[k] = (after[k] or 0) + Brush.area(p.points) + end + local drift = 0 + for k, a in ours do + drift = math.max(drift, math.abs((after[k] or 0) - a)) + end + t:check(drift < 1e-6, kind .. ": merged area per plane unchanged") +end + +-- two touching cubes merge into one box: 6 faces, no inner faces +do + local function cube(x0: number, x1: number): { Brush.Face } + local f = {} + for _, p in { { 1, 0, 0, x1 }, { -1, 0, 0, -x0 }, { 0, 1, 0, 64 }, { 0, -1, 0, 0 }, { 0, 0, 1, 64 }, { 0, 0, -1, 0 } } do + table.insert(f, { plane = p, texture = "t", vecs = Brush.quakeVecs(p, 0, 0, 0, 1, 1) }) + end + return f + end + local polys = assert(Brush.polygons({ cube(0, 64), cube(64, 128) }, { hull = true, merge = true })) + t:eq(#polys, 6, "touching cubes: 6 merged faces") + local area = 0 + for _, p in polys do + area += Brush.area(p.points) + end + t:eq(area, 2 * 128 * 64 * 2 + 2 * 64 * 64, "touching cubes: surface area") + local plain = assert(Brush.polygons({ cube(0, 64), cube(64, 128) })) + t:eq(#plain, 12, "without hull / merge: every face") + t:check(Brush.planeFromPoints({ 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 }) == nil, "colinear points: no plane") + -- Quake standard with exact rotations, against TextureAxisFromPlane by hand: a floor, rotated 90 degrees + local v = Brush.quakeVecs({ 0, 0, 1, 0 }, 8, 4, 90, 2, 1) + t:eq(v[1][1] .. " " .. v[1][2] .. " " .. v[1][4], "0 0.5 8", "rotated floor s axis") + t:eq(v[2][1] .. " " .. v[2][2] .. " " .. v[2][4], "1 0 4", "rotated floor t axis") + -- brush primitives <-> texel vectors + local n = { 0.6, 0, 0.8, 10 } + local bp = { { 0.01, 0.02, 0.5 }, { -0.03, 0.004, 0.25 } } + local back = Brush.vecsToBp(n, Brush.bpVecs(n, bp, 64, 32), 64, 32) + local err = 0 + for i = 1, 2 do + for j = 1, 3 do + err = math.max(err, math.abs(back[i][j] - bp[i][j])) + end + end + t:check(err < 1e-12, "bpVecs / vecsToBp round trip") +end + +-- fuzz: random planes never throw +do + local rand = T.rng(5) + local threw = 0 + for _ = 1, 200 do + local faces = {} + for _ = 1, 1 + rand(10) do + local p = { rand(2001) / 1000 - 1, rand(2001) / 1000 - 1, rand(2001) / 1000 - 1, rand(200) - 100 } + table.insert(faces, { plane = p, texture = "x", vecs = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 } } }) + end + local ok = pcall(function() + local polys = Brush.polygons({ faces, faces }, { hull = true, merge = true }) + if polys then + Brush.primitives(polys, { faces, faces }, function() + return 64, 64 + end) + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "random planes never throw") +end +t:done() diff --git a/tests/codecs/displacement.luau b/tests/codecs/displacement.luau new file mode 100644 index 0000000..4346181 --- /dev/null +++ b/tests/codecs/displacement.luau @@ -0,0 +1,41 @@ +-- codecs/model/Displacement tests: a flat surface is the base quad's grid, corner 0 follows the start position, +-- offsets move vertices, triangles and normals face the face normal, errors. Displaced maps: tests/model/vbsp.luau. +local T = require("@tests/T") +local Displacement = require("@rosetta/codecs/model/Displacement") + +local t = T.suite("displacement") + +-- a floor facing +z, clockwise seen from above +local quad = { 0, 0, 0, 0, 64, 0, 64, 64, 0, 64, 0, 0 } +local zero = table.create(5 * 5 * 3, 0) +local s = Displacement.surface(quad, { 0, 64, 0 }, 2, zero, { 0, 0, 1 }) :: Displacement.Surface +t:eq(s.n, 5, "power 2: 5 x 5") +t:eq(#s.idx, 4 * 4 * 6, "32 triangles") +t:eq(s.pos[1] .. "," .. s.pos[2], "0,64", "corner 0 is the one nearest the start") +t:eq(s.pos[16] .. "," .. s.pos[17], "16,64", "rows (i) run along corner 0 -> 1") +t:eq(s.pos[4] .. "," .. s.pos[5], "0,48", "columns (j) along corner 0 -> 3") +local up = true +for k = 0, 24 do + up = up and math.abs(s.nrm[k * 3 + 3] - 1) < 1e-9 +end +t:check(up, "flat normals = face normal") +local ccw = true +for k = 0, #s.idx // 3 - 1 do + local a, b, c = s.idx[k * 3 + 1] * 3, s.idx[k * 3 + 2] * 3, s.idx[k * 3 + 3] * 3 + local z = (s.pos[b + 1] - s.pos[a + 1]) * (s.pos[c + 2] - s.pos[a + 2]) - (s.pos[b + 2] - s.pos[a + 2]) * (s.pos[c + 1] - s.pos[a + 1]) + ccw = ccw and z > 0 +end +t:check(ccw, "triangles counter-clockwise about the face normal") +local off = table.clone(zero) +off[12 * 3 + 3] = 10 +local d = Displacement.surface(quad, { 0, 0, 0 }, 2, off, { 0, 0, 1 }) :: Displacement.Surface +t:eq(d.pos[12 * 3 + 3], 10, "centre raised") +t:eq(d.flat[12 * 3 + 3], 0, "flat grid kept") +t:check(d.nrm[11 * 3 + 1] < 0 and d.nrm[13 * 3 + 1] > 0 or d.nrm[11 * 3 + 2] ~= 0, "sloped normals around the bump") +local _, e1 = Displacement.surface({ 0, 0, 0 }, { 0, 0, 0 }, 2, zero, { 0, 0, 1 }) +t:check(e1 ~= nil, "not a quad") +local _, e2 = Displacement.surface(quad, { 0, 0, 0 }, 5, zero, { 0, 0, 1 }) +t:check(e2 ~= nil, "power 5") +local _, e3 = Displacement.surface(quad, { 0, 0, 0 }, 3, zero, { 0, 0, 1 }) +t:check(e3 ~= nil, "offsets truncated") +t:done() diff --git a/tests/codecs/patch.luau b/tests/codecs/patch.luau new file mode 100644 index 0000000..1989e66 --- /dev/null +++ b/tests/codecs/patch.luau @@ -0,0 +1,85 @@ +-- codecs/model/Patch tests: biquadratic Bezier evaluation against the closed form, shared sub-patch edges, triangle +-- winding and normals, explicit (patchDef3-style) subdivisions per axis, the fuzz pass. +local T = require("@tests/T") +local Patch = require("@rosetta/codecs/model/Patch") + +local t = T.suite("patch") + +-- a 5 x 3 grid (two sub-patches along u): x = column * 8, y = row * 8, z = a bump on the middle control row +local ctrl = {} +for j = 0, 2 do + for i = 0, 4 do + table.insert(ctrl, i * 8) + table.insert(ctrl, j * 8) + table.insert(ctrl, if j == 1 then 16 else 0) + end +end +local pts, gw, gh = Patch.grid(ctrl, 5, 3, 3, 4, 2) +t:check(pts ~= nil, "grid") +t:eq(gw, 9, "width: 2 sub-patches x 4 segments + 1") +t:eq(gh, 3, "height: 2 segments + 1") +local p = pts :: { number } +-- z(v) = 2 v (1 - v) * 16 on every column (the bump is constant along u); x is linear in u +local worst = 0 +for gy = 0, gh - 1 do + local v = gy / 2 + for gx = 0, gw - 1 do + local o = (gy * gw + gx) * 3 + worst = math.max(worst, math.abs(p[o + 1] - gx * 4), math.abs(p[o + 2] - v * 16), math.abs(p[o + 3] - 32 * v * (1 - v))) + end +end +t:check(worst < 1e-12, "closed form (worst " .. worst .. ")") +-- corners interpolate the control points +t:eq(p[1] .. " " .. p[2] .. " " .. p[3], "0 0 0", "first corner") +local last = (gw * gh - 1) * 3 +t:eq(p[last + 1] .. " " .. p[last + 2] .. " " .. p[last + 3], "32 16 0", "last corner") + +local tris = Patch.triangles(gw, gh) +t:eq(#tris, (gw - 1) * (gh - 1) * 6, "two triangles per cell") +local nrm = Patch.normals(p, 3, gw, gh) +local bad = 0 +for k = 1, #tris, 3 do + local a, b, c = tris[k] * 3, tris[k + 1] * 3, tris[k + 2] * 3 + local ux, uy, uz = p[b + 1] - p[a + 1], p[b + 2] - p[a + 2], p[b + 3] - p[a + 3] + local vx, vy, vz = p[c + 1] - p[a + 1], p[c + 2] - p[a + 2], p[c + 3] - p[a + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + if cx * nrm[a + 1] + cy * nrm[a + 2] + cz * nrm[a + 3] <= 0 then + bad += 1 + end +end +t:eq(bad, 0, "normals face the front of the triangles") + +-- extra components (texture coordinates) interpolate too; normalize renormalizes a vec3 +local flat = {} +for j = 0, 2 do + for i = 0, 2 do + for _, v in { i, j, 0, i / 2, j / 2, 0, 0, 2 } do + table.insert(flat, v) + end + end +end +local q, qw, qh = Patch.grid(flat, 3, 3, 8, 3, 5) +t:eq(qw * qh, 4 * 6, "explicit subdivisions per axis") +Patch.normalize(q :: { number }, 8, 5) +t:eq((q :: { number })[8], 1, "renormalized normal") +t:eq((q :: { number })[(qw * qh - 1) * 8 + 4], 1, "texture coordinate at the far corner") + +t:check(Patch.grid({ 1, 2, 3 }, 2, 2, 3, 4, 4) == nil, "even grid: nil") +t:check(Patch.grid(ctrl, 5, 3, 3, 1000, 1000, 1000) == nil, "point limit: nil") + +t:fuzz("grid", function(b: buffer) + local n = buffer.len(b) + local w = 1 + 2 * (if n > 0 then buffer.readu8(b, 0) % 4 else 1) + local h = 1 + 2 * (if n > 1 then buffer.readu8(b, 1) % 4 else 1) + local c = {} + for k = 0, n - 1 do + table.insert(c, buffer.readu8(b, k) - 128) + end + local g, gw2, gh2 = Patch.grid(c, w, h, 3, 1 + n % 5, 1 + n % 3) + if g then + Patch.normals(g, 3, gw2, gh2) + Patch.triangles(gw2, gh2) + end + return g +end, { buffer.create(27), buffer.create(45), buffer.create(75) }) +t:done() diff --git a/tests/model/map.luau b/tests/model/map.luau new file mode 100644 index 0000000..1710320 --- /dev/null +++ b/tests/model/map.luau @@ -0,0 +1,325 @@ +-- model/map tests: Quake / Valve 220 / Quake II / Quake III .map files against ericw-tools qbsp (CSG'd face area per +-- plane and texture coordinates at every compiled corner, per entity), texture sizes from WAD2 / WAD3 / .wal through +-- files, the patchDef2 against a Bezier evaluation, entities as nodes, write round trips, errors, the fuzz pass. +-- Fixtures: tools/fixtures/map.py. +local T = require("@tests/T") +local F = require("@rosetta") +local MapFmt = require("@rosetta/model/map") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/map") + +local t = T.suite("map") +t:eq(MapFmt.name, "map", "name") + +local function r(x: number, k: number): number + return math.floor(x * k + 0.5) +end +local function key(nx: number, ny: number, nz: number, d: number): string + return string.format("%d %d %d %d", r(nx, 1000), r(ny, 1000), r(nz, 1000), r(d, 100)) +end + +type Tri = { p: { number }, uv: { number }, n: { number }, tex: string } + +local function triangles(s: any, mesh: any): { Tri } + local out: { Tri } = {} + for _, p in mesh.primitives do + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any + local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any + local tex = s.materials[p.material].name + for k = 0, p.indices.count - 1, 3 do + local tri: Tri = { p = {}, uv = {}, n = {}, tex = tex } + for c = 0, 2 do + local v = buffer.readu32(p.indices.data, (k + c) * 4) + for a = 0, 2 do + table.insert(tri.p, pos(v, a)) + end + table.insert(tri.uv, uv(v, 0)) + table.insert(tri.uv, uv(v, 1)) + if c == 0 then + tri.n = { nrm(v, 0), nrm(v, 1), nrm(v, 2) } + end + end + table.insert(out, tri) + end + end + return out +end + +local function area(p: { number }): number + local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3] + local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + return math.sqrt(cx * cx + cy * cy + cz * cz) / 2 +end + +local function polyArea(p: { number }): number + local a = 0 + for k = 1, #p // 3 - 2 do + a += area({ p[1], p[2], p[3], p[k * 3 + 1], p[k * 3 + 2], p[k * 3 + 3], p[k * 3 + 4], p[k * 3 + 5], p[k * 3 + 6] }) + end + return a +end + +-- barycentric coordinates of x on the triangle's plane (nil when outside) +local function bary(tri: Tri, x: number, y: number, z: number): (number?, number?) + local p = tri.p + local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3] + local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3] + local wx, wy, wz = x - p[1], y - p[2], z - p[3] + local uu, uv, vv = ux * ux + uy * uy + uz * uz, ux * vx + uy * vy + uz * vz, vx * vx + vy * vy + vz * vz + local wu, wv = wx * ux + wy * uy + wz * uz, wx * vx + wy * vy + wz * vz + local den = uu * vv - uv * uv + if den == 0 then + return nil, nil + end + local b = (vv * wu - uv * wv) / den + local c = (uu * wv - uv * wu) / den + local tol = 1e-4 + if b < -tol or c < -tol or b + c > 1 + tol then + return nil, nil + end + return b, c +end + +local function compare(label: string, s: any, model: string, faces: any) + local node + for _, n in s.nodes do + if n.extras and n.extras.entity == tonumber(model) then + node = n + end + end + t:check(node and node.mesh, label .. ": entity " .. model .. " has a mesh") + local tris = {} + for _, tri in triangles(s, s.meshes[node.mesh]) do + if tri.tex ~= "base/curve" then -- the patch: qbsp has no patches + table.insert(tris, tri) + end + end + local ours, theirs = {}, {} + for _, tri in tris do + local n = tri.n + local k = key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) + ours[k] = (ours[k] or 0) + area(tri.p) + end + for _, f in faces do + local k = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4]) + theirs[k] = (theirs[k] or 0) + polyArea(f.pts) + end + local bad = 0 + for k, a in theirs do + if math.abs((ours[k] or 0) - a) > 0.05 then + bad += 1 + t:note("%s model %s plane %s: %s vs qbsp %s", label, model, k, tostring(ours[k]), tostring(a)) + end + end + for k in ours do + if not theirs[k] then + bad += 1 + end + end + t:eq(bad, 0, label .. ": model " .. model .. " face area per plane") + local miss, off = 0, 0 + for _, f in faces do + local fk = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4]) + for c = 0, #f.pts // 3 - 1 do + local x, y, z = f.pts[c * 3 + 1], f.pts[c * 3 + 2], f.pts[c * 3 + 3] + local s0 = (f.vecs[1] * x + f.vecs[2] * y + f.vecs[3] * z + f.vecs[4]) / f.size[1] + local t0 = (f.vecs[5] * x + f.vecs[6] * y + f.vecs[7] * z + f.vecs[8]) / f.size[2] + local found, best = false, math.huge + for _, tri in tris do + local n = tri.n + if tri.tex == f.tex and key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then + local b, cc = bary(tri, x, y, z) + if b and cc then + found = true + local u = tri.uv[1] + b * (tri.uv[3] - tri.uv[1]) + cc * (tri.uv[5] - tri.uv[1]) + local v = tri.uv[2] + b * (tri.uv[4] - tri.uv[2]) + cc * (tri.uv[6] - tri.uv[2]) + best = math.min(best, math.max(math.abs(u - s0) * f.size[1], math.abs(v - t0) * f.size[2])) + end + end + end + if not found then + miss += 1 + if miss <= 3 then + local on = {} + for _, tri in tris do + local n = tri.n + if key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then + table.insert(on, tri.tex) + end + end + t:note("%s model %s: corner %s %s %s (%s) on %s, ours there: %s", label, model, x, y, z, f.tex, fk, table.concat(on, ",")) + end + elseif best > 0.05 then + off += 1 + end + end + end + t:eq(miss, 0, label .. ": model " .. model .. " every qbsp corner on one of our triangles") + t:eq(off, 0, label .. ": model " .. model .. " texture coordinates match qbsp") +end + +for _, label in { "quake", "valve", "quake2", "quake3" } do + local c = Fx[label] + t:eq(F.detect(c.text), "map", label .. ": F.detect") + local s, err = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true }) + t:check(s, label .. ": " .. tostring(err)) + local scene = s :: any + t:eq(scene.meta.source.variant, ({ quake = "quake", valve = "valve220", quake2 = "quake2", quake3 = "quake3" } :: any)[label], label .. ": variant") + t:eq(scene.meta.up, "z", label .. ": z up") + for model, faces in c.models do + compare(label, scene, model, faces) + end + -- texture sizes found in the WAD / .wal files (Quake III needs images: 64 x 64 without decodeImage) + for _, m in scene.materials do + local want = c.sizes[m.name] + if want and label ~= "quake3" then + t:check(m.extras.map.width == want[1] and m.extras.map.height == want[2] and m.extras.map.sizeKnown, label .. ": size of " .. m.name) + end + end + -- entities: nodes with their keys in order + t:eq(#scene.meta.entities, 4, label .. ": entities") + local door = scene.nodes[3] + t:eq(door.name, "door1", label .. ": brush entity named by targetname") + t:eq(door.extras.classname, "func_door", label .. ": classname") + t:eq(table.concat(Types.keys(door.extras.keys), ","), "classname,targetname,angle", label .. ": key order") + local start = scene.nodes[4] + t:eq(start.translation and table.concat(start.translation, " "), "-128 -128 24", label .. ": point entity at its origin") + t:check(start.mesh == nil, label .. ": point entity without a mesh") + -- round trip: write, read again, same entities and geometry + local out, eerr = MapFmt.encode(scene) + t:check(out, label .. ": encode " .. tostring(eerr)) + local again = MapFmt.decode(Bytes.reader(out :: buffer), { files = c.files, hull = true }) :: any + t:check(again ~= nil, label .. ": reload") + local a1, a2 = MapFmt.parse(c.text) :: any, MapFmt.parse(out :: buffer) :: any + local same = #a1.entities == #a2.entities + for i, e in a1.entities do + local e2 = a2.entities[i] + same = same and e2 ~= nil and #e.brushes == #e2.brushes + for k, v in e.keys do + same = same and e2.keys[k] == v + end + for bi, b in e.brushes do + local b2 = e2.brushes[bi] + same = same and b.type == b2.type and #(b.faces or {}) == #(b2.faces or {}) + for fi, f in b.faces or {} do + local f2 = b2.faces[fi] + same = same and f.texture == f2.texture and table.concat(f.points, " ") == table.concat(f2.points, " ") + for _, fld in { "offset", "scale", "u", "v", "flags" } do + same = same and table.concat((f :: any)[fld] or {}, " ") == table.concat((f2 :: any)[fld] or {}, " ") + end + same = same and f.rotation == f2.rotation + if f.matrix then + same = same and table.concat(f.matrix[1], " ") == table.concat(f2.matrix[1], " ") and table.concat(f.matrix[2], " ") == table.concat(f2.matrix[2], " ") + end + end + if b.points then + same = same and table.concat(b.points, " ") == table.concat(b2.points, " ") + end + end + end + t:check(same, label .. ": write -> parse gives the same entities, brushes and faces") + t:eq(again.meta.source.variant, scene.meta.source.variant, label .. ": variant survives the round trip") + t:eq(#again.meshes, #scene.meshes, label .. ": meshes survive the round trip") +end + +-- the Quake III patch: our grid = the Bezier evaluation +do + local c = Fx.quake3 + local s = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any + t:eq(s.meta.source.patches, 1, "quake3: one patch") + local prim + for _, p in s.meshes[1].primitives do + if s.materials[p.material].name == "base/curve" then + prim = p + end + end + t:check(prim, "quake3: patch primitive") + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local uv = Types.Scene.reader(prim.attributes.TEXCOORD_0) :: any + t:eq(prim.attributes.POSITION.count, c.patch.w * c.patch.h, "quake3: grid size") + local worst = 0 + for k = 0, c.patch.w * c.patch.h - 1 do + for a = 0, 2 do + worst = math.max(worst, math.abs(pos(k, a) - c.patch.grid[k * 5 + a + 1])) + end + worst = math.max(worst, math.abs(uv(k, 0) - c.patch.grid[k * 5 + 4]) * 64, math.abs(uv(k, 1) - c.patch.grid[k * 5 + 5]) * 64) + end + t:check(worst < 1e-4, "quake3: patch points match the Bezier evaluation (" .. worst .. ")") + t:eq(s.textures[s.materials[prim.material].baseColorTexture.texture].uri, "textures/base/curve", "quake3: texture URI") + local lean = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { patchLevel = 1, skip = { "brick" } }) :: any + for _, p in lean.meshes[1].primitives do + t:check(lean.materials[p.material].name ~= "brick", "skip: brick left out") + end +end + +-- options and conversions +do + local c = Fx.quake + local merged = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true, merge = true }) :: any + local plain = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any + local function count(sc: any): number + local n = 0 + for _, p in sc.meshes[1].primitives do + n += p.indices.count + end + return n + end + t:check(count(merged) < count(plain), "hull + merge: fewer triangles than every face") + t:eq(plain.materials[1].extras.map.sizeKnown, true, "sizes from the worldspawn WAD") + local nowad = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text))) :: any + t:eq(nowad.materials[1].extras.map.width, 64, "no WAD: 64 x 64") + local sized = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { textureSizes = { brick = { 8, 8 } } }) :: any + for _, m in sized.materials do + if m.name == "brick" then + t:eq(m.extras.map.width, 8, "textureSizes") + end + end + -- Quake standard -> Valve 220: same texture coordinates + local valve = assert(MapFmt.encode(plain, { variant = "valve220" })) + local v = MapFmt.decode(Bytes.reader(valve), { files = c.files }) :: any + t:eq(v.meta.source.variant, "valve220", "converted to Valve 220") + local u1 = Types.Scene.reader(plain.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any + local u2 = Types.Scene.reader(v.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any + local worst = 0 + for k = 0, plain.meshes[1].primitives[1].attributes.TEXCOORD_0.count - 1 do + worst = math.max(worst, math.abs(u1(k, 0) - u2(k, 0)), math.abs(u1(k, 1) - u2(k, 1))) + end + t:check(worst < 1e-5, "Valve 220 conversion keeps the texture coordinates (" .. worst .. ")") + -- edits: a moved point entity writes its new origin + plain.nodes[4].translation = { 1, 2, 3 } + local moved = MapFmt.parse(assert(MapFmt.encode(plain))) :: any + t:eq(moved.entities[3].keys.origin, "1 2 3", "moved entity origin") + -- through the api + local viaApi = assert(F.model.load(c.text, { files = c.files })) + t:eq(viaApi.meta.source.format, "map", "F.model.load") + local saved = assert(F.save(viaApi, nil, { format = "map" })) + t:check(buffer.len(saved) > 100, "F.save as map") +end + +-- sniffing and errors +do + local build = buffer.create(64) + buffer.writeu32(build, 0, 7) + t:eq(MapFmt.sniff(Bytes.reader(build)), 0, "Build engine (binary) .map: not ours") + t:eq(MapFmt.sniff(Bytes.reader(buffer.fromstring('{"classname": "x"}'))), 0, "JSON: not a map") + t:check(MapFmt.sniff(Bytes.reader(buffer.fromstring('{\n"classname" "worldspawn"\n}'))) > 0.5, "minimal map") + local _, e1 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { ( 0 0 0 ) ( 1 0 0 ) brick'))) + t:check(e1 and e1.code == Err.CORRUPT, "truncated face: " .. tostring(e1)) + local _, e2 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { brushDef3 { } } }'))) + t:check(e2 and e2.code == Err.UNSUPPORTED, "Doom 3 brushDef3: unsupported") + local _, e3 = MapFmt.encode(Types.Scene.new()) + t:check(e3 and e3.code == Err.ARG, "encode without entities") + local bad = assert(MapFmt.decode(Bytes.reader(buffer.fromstring(Fx.quake.text)))) :: any + bad.nodes[2].extras.keys.message = 'a "quoted" value' + local _, e4 = MapFmt.encode(bad) + t:check(e4 and e4.code == Err.ARG, "quotes in a value") +end + +t:fuzz("decode", function(b: buffer) + return MapFmt.decode(Bytes.reader(b), { hull = true, merge = true }) +end, { buffer.fromstring(Fx.quake.text), buffer.fromstring(Fx.quake3.text), buffer.fromstring(Fx.valve.text) }, { mutations = 60, garbage = 20 }) +t:done() diff --git a/tests/model/vbsp.luau b/tests/model/vbsp.luau new file mode 100644 index 0000000..d0ad217 --- /dev/null +++ b/tests/model/vbsp.luau @@ -0,0 +1,221 @@ +-- model/vbsp tests: maps written by tools/fixtures/vbsp.py and saved by srctools (v19 / v20 / v21, L4D2 header, LZMA +-- lumps, static props v4 .. v11) against what srctools reads back: face polygons and texture projections per +-- (model, material), the displacement grid, static props, entities, the pak lump; errors and the fuzz pass. +local T = require("@tests/T") +local Vbsp = require("@rosetta/model/vbsp") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Fx = require("@tests/gen/vbsp") + +local t = T.suite("vbsp") +t:eq(Vbsp.name, "vbsp", "name") +t:check(Vbsp.caps.decode and not Vbsp.caps.encode, "caps") + +local function f2(x: number): string + local s = string.format("%.2f", x) + return if s == "-0.00" then "0.00" else s +end + +local function lines(prim: Types.Primitive): (string, number) + local P, U = prim.attributes.POSITION, prim.attributes.TEXCOORD_0 + local out = table.create(P.count) + for i = 0, P.count - 1 do + out[i + 1] = table.concat({ + f2(buffer.readf32(P.data, i * 12)), f2(buffer.readf32(P.data, i * 12 + 4)), f2(buffer.readf32(P.data, i * 12 + 8)), + f2(buffer.readf32(U.data, i * 8)), f2(buffer.readf32(U.data, i * 8 + 4)), + }, " ") + end + table.sort(out) + return table.concat(out, "\n"), (prim.indices :: Types.Accessor).count // 3 +end + +local function fixLines(s: string): string + local out = {} + for l in string.gmatch(s, "[^\n]+") do + table.insert(out, (string.gsub(l, "%-0%.00", "0.00"))) + end + table.sort(out) + return table.concat(out, "\n") +end + +-- every triangle faces its vertices' normals (front faces are counter-clockwise) +local function facing(prim: Types.Primitive): boolean + local P, N, I = prim.attributes.POSITION, prim.attributes.NORMAL, prim.indices :: Types.Accessor + for k = 0, I.count // 3 - 1 do + local a, b, c = buffer.readu32(I.data, k * 12), buffer.readu32(I.data, k * 12 + 4), buffer.readu32(I.data, k * 12 + 8) + local function p(i: number, j: number): number + return buffer.readf32(P.data, i * 12 + j * 4) + end + local ux, uy, uz = p(b, 0) - p(a, 0), p(b, 1) - p(a, 1), p(b, 2) - p(a, 2) + local vx, vy, vz = p(c, 0) - p(a, 0), p(c, 1) - p(a, 1), p(c, 2) - p(a, 2) + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local d = nx * buffer.readf32(N.data, a * 12) + ny * buffer.readf32(N.data, a * 12 + 4) + nz * buffer.readf32(N.data, a * 12 + 8) + if d <= 0 then + return false + end + end + return true +end + +-- Source AngleVectors(pitch, yaw, roll): forward, left (= -right), up +local function basis(p: number, y: number, r: number): { number } + local sp, cp = math.sin(math.rad(p)), math.cos(math.rad(p)) + local sy, cy = math.sin(math.rad(y)), math.cos(math.rad(y)) + local sr, cr = math.sin(math.rad(r)), math.cos(math.rad(r)) + return { + cp * cy, cp * sy, -sp, + sr * sp * cy - cr * sy, sr * sp * sy + cr * cy, sr * cp, + cr * sp * cy + sr * sy, cr * sp * sy - sr * cy, cr * cp, + } +end + +local first: Types.Scene? = nil +for _, c in Fx.cases do + local scene, err = Vbsp.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + if not scene then + continue + end + first = first or scene + local src = scene.meta.source :: any + t:eq(src.version, c.version, c.name .. ": version") + t:eq(src.variant == "l4d2", c.l4d2, c.name .. ": L4D2 header") + t:eq(src.compressed, c.compressed, c.name .. ": LZMA lumps") + t:eq(src.staticPropVersion, c.spversion, c.name .. ": static prop version") + -- faces + local byKey: { [string]: Types.Primitive } = {} + for _, n in scene.nodes do + if n.mesh then + local model = (n.extras :: any).vbsp.model + for _, prim in scene.meshes[n.mesh].primitives do + byKey[model .. "|" .. (scene.materials[prim.material :: number].name :: string)] = prim + end + end + end + local ngroups = 0 + for _ in byKey do + ngroups += 1 + end + t:eq(ngroups, #c.groups, c.name .. ": one primitive per (model, material), nodraw skipped") + for _, g in c.groups do + local prim = byKey[g.model .. "|" .. g.material] + t:check(prim ~= nil, c.name .. ": group " .. g.model .. " " .. g.material) + if prim then + local got, tris = lines(prim) + t:eq(tris, g.tris, c.name .. ": " .. g.material .. " triangles") + t:eq(got, fixLines(g.verts), c.name .. ": " .. g.material .. " positions and UVs as srctools") + t:check(facing(prim), c.name .. ": " .. g.material .. " counter-clockwise fronts") + if string.find(g.material, "BLEND", 1, true) then + t:check(prim.attributes._BLEND ~= nil, c.name .. ": displacement alpha") + end + end + end + -- static props + local props = {} + for _, n in scene.nodes do + if n.extras and (n.extras :: any).model then + table.insert(props, n) + end + end + t:eq(#props, #c.props, c.name .. ": static props") + for i, want in c.props do + local n = props[i] + if n then + t:eq((n.extras :: any).model, want.model, c.name .. ": prop " .. i .. " model") + t:eq((n.extras :: any).vbsp.skin, want.skin, c.name .. ": prop " .. i .. " skin") + local tr = n.translation :: { number } + t:check(math.abs(tr[1] - want.origin[1]) + math.abs(tr[2] - want.origin[2]) + math.abs(tr[3] - want.origin[3]) < 1e-4, c.name .. ": prop " .. i .. " origin") + local m = Mat4.fromQuat(n.rotation :: { number }) + local bv = basis(want.angles[1], want.angles[2], want.angles[3]) + local d = 0 + for col = 0, 2 do + for row = 0, 2 do + d = math.max(d, math.abs(m[col * 4 + row + 1] - bv[col * 3 + row + 1])) + end + end + t:check(d < 1e-5, c.name .. ": prop " .. i .. " rotation is AngleVectors") + end + end + -- entities + local ents = scene.meta.entities :: { any } + t:eq(#ents, c.entities, c.name .. ": entities") + local outputs, classes = 0, {} + for _, e in ents do + table.insert(classes, e.classname) + if type(e.OnTrigger) == "table" then + outputs += #e.OnTrigger + elseif e.OnTrigger then + outputs += 1 + end + end + table.sort(classes) + t:eq(table.concat(classes, ","), table.concat(c.classnames, ","), c.name .. ": classnames") + t:eq(outputs, c.outputs, c.name .. ": repeated outputs") + -- pak + local pak = scene.meta.pak + t:check(pak ~= nil and pak.kind == "archive", c.name .. ": pak archive") + if pak then + local names = {} + for _, e in pak:list() do + table.insert(names, e.name) + end + table.sort(names) + t:eq(table.concat(names, ","), table.concat(c.pak, ","), c.name .. ": pak names") + t:eq(buffer.tostring(pak:read("materials/custom/note.txt") :: buffer), "hello from the pak lump\n", c.name .. ": pak read") + end +end + +if first then + local s = first :: Types.Scene + t:eq(s.meta.up, "z", "z up") + local door, light + for _, n in s.nodes do + if n.name == "door" then + door = n + end + if n.light then + light = n + end + end + t:check(door and door.mesh and door.translation and door.translation[3] == 64, "func_brush placed at its origin") + t:check(light and s.lights[light.light].type == "point" and math.abs(s.lights[light.light].intensity - 300) < 1e-9, "light entity") + local disp = nil + for _, m in s.meshes do + for _, p in m.primitives do + if p.attributes._BLEND then + disp = p + end + end + end + t:check(disp ~= nil and disp.attributes.POSITION.count == 81, "power 3: 9 x 9 grid") + local all = Vbsp.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].data)), { tools = true }) :: Types.Scene + t:check(#all.materials == #s.materials + 1, "tools = true keeps the nodraw face") +end + +do + local plain = buffer.fromstring(Fx.plain) + t:eq(Vbsp.sniff(Bytes.reader(plain)), 1, "sniff") + t:eq(Vbsp.sniff(Bytes.reader(buffer.fromstring("IBSP" .. string.rep("\0", 2000)))), 0, "not Quake") + local bad = buffer.fromstring(Fx.plain) + buffer.writei32(bad, 4, 42) + local _, e1 = Vbsp.decode(Bytes.reader(bad)) + t:eq(e1 and e1.code, Err.UNSUPPORTED, "version 42") + local _, e2 = Vbsp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.plain, 1, 600)))) + t:eq(e2 and e2.code, Err.TRUNCATED, "short header") + local cut = buffer.fromstring(string.sub(Fx.plain, 1, 3000)) + local _, e3 = Vbsp.decode(Bytes.reader(cut)) + t:eq(e3 and e3.code, Err.TRUNCATED, "lumps past the end") +end + +local samples = {} +for i, c in Fx.cases do + if i <= 4 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Vbsp.decode(Bytes.reader(b)) +end, samples, { keepHeader = 8 }) +t:done() diff --git a/tests/model/vmf.luau b/tests/model/vmf.luau new file mode 100644 index 0000000..df59d02 --- /dev/null +++ b/tests/model/vmf.luau @@ -0,0 +1,223 @@ +-- model/vmf tests: srctools' Hammer-written test VMFs (solid polygons against srctools.geometry, byte-exact write +-- back), a generated room (displacement floor equal to tools/fixtures/vbsp.py's, outputs, visgroups, cameras, hidden +-- solids, a prop_static), the document builders, errors and the fuzz pass. Fixtures: tools/fixtures/vmf.py. +local T = require("@tests/T") +local Vmf = require("@rosetta/model/vmf") +local Vbsp = require("@rosetta/model/vbsp") +local Brush = require("@rosetta/codecs/model/Brush") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/vmf") +local VbspFx = require("@tests/gen/vbsp") + +local t = T.suite("vmf") +t:eq(Vmf.name, "vmf", "name") +t:check(Vmf.caps.decode and Vmf.caps.encode, "caps") + +local function f2(x: number): string + local s = string.format("%.2f", x) + return if s == "-0.00" then "0.00" else s +end + +local function canonOf(faces: { any }): string + local polys = Brush.polygons({ faces }) :: { Brush.Polygon } + local out = {} + for _, p in polys do + local pts = {} + for k = 0, #p.points // 3 - 1 do + table.insert(pts, f2(p.points[k * 3 + 1]) .. " " .. f2(p.points[k * 3 + 2]) .. " " .. f2(p.points[k * 3 + 3])) + end + table.sort(pts) + table.insert(out, table.concat(pts, ";")) + end + table.sort(out) + return table.concat(out, "|") +end + +local function solidCanons(doc: any): { string } + local list = {} + for _, s in Vmf.brushes(doc) :: { any } do + table.insert(list, canonOf(s.faces)) + end + table.sort(list) + return list +end + +local function dec(data: string, opts: any?): (Types.Scene?, Err.Err?) + return Vmf.decode(Bytes.reader(buffer.fromstring(data)), opts) +end + +for _, c in Fx.files do + local scene, err = dec(c.data, { tools = true }) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + if scene then + local want = table.clone(c.solids) + table.sort(want) + t:eq(table.concat(solidCanons(scene.meta.vmf), "\n"), table.concat(want, "\n"), c.name .. ": solids as srctools.geometry") + t:eq(buffer.tostring(Vmf.encode(scene) :: buffer), c.data, c.name .. ": written back byte for byte") + local tris, polys = 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + tris += (p.indices :: Types.Accessor).count // 3 + end + end + for _, s in c.solids do + for poly in string.gmatch(s, "[^|]+") do + local _, corners = string.gsub(poly, ";", "") + polys += corners - 1 + end + end + if not string.find(c.data, "dispinfo", 1, true) then + t:eq(tris, polys, c.name .. ": triangles = corners - 2 per polygon") + else + t:eq(tris, 128, c.name .. ": a power-3 displacement replaces its brush") + end + end +end + +do + local R = Fx.room + local scene = dec(R.data) :: Types.Scene + t:check(scene ~= nil, "room decodes") + t:eq(#scene.meta.entities, R.entities, "room: entities as srctools") + local outputs = 0 + for _, e in scene.meta.entities do + if e.connections then + for _, k in Types.keys(e.connections) do + local v = e.connections[k] + outputs += if type(v) == "table" then #v else 1 + end + end + end + t:eq(outputs, R.outputs, "room: outputs as srctools") + local names = {} + local function walk(list: { any }) + for _, v in list do + table.insert(names, v.name) + walk(v.children) + end + end + walk(scene.meta.visgroups) + table.sort(names) + t:eq(table.concat(names, ","), table.concat(R.visgroups, ","), "room: nested visgroups") + t:eq(#scene.cameras, R.cameras, "room: cameras") + t:eq(scene.meta.cameras.active, 0, "room: active camera") + t:eq(#scene.meta.groups, 1, "room: group") + local want = table.clone(R.solids) + table.sort(want) + t:eq(table.concat(solidCanons(scene.meta.vmf), "\n"), table.concat(want, "\n"), "room: solids (hidden one included) as srctools") + t:eq(buffer.tostring(Vmf.encode(scene) :: buffer), R.data, "room: written back byte for byte") + -- the displacement floor + local disp: Types.Primitive? = nil + local nodraw = false + for _, m in scene.meshes do + for _, p in m.primitives do + if p.attributes._BLEND then + disp = p + end + if string.find(scene.materials[p.material :: number].name :: string, "TOOLS", 1, true) then + nodraw = true + end + end + end + t:check(not nodraw, "room: tool materials left out") + t:check(disp ~= nil, "room: displacement") + local function positions(p: Types.Primitive): string + local P = p.attributes.POSITION + local out = {} + for i = 0, P.count - 1 do + table.insert(out, f2(buffer.readf32(P.data, i * 12)) .. " " .. f2(buffer.readf32(P.data, i * 12 + 4)) .. " " .. f2(buffer.readf32(P.data, i * 12 + 8))) + end + table.sort(out) + return table.concat(out, "\n") + end + if disp then + t:eq(positions(disp), R.disp, "room: displacement grid") + local b = Vbsp.decode(Bytes.reader(buffer.fromstring(VbspFx.cases[1].data))) :: Types.Scene + for _, m in b.meshes do + for _, p in m.primitives do + if p.attributes._BLEND then + t:eq(positions(p), positions(disp), "room: the same surface as the compiled map's displacement") + end + end + end + end + local prop, cam + for _, n in scene.nodes do + if n.extras and (n.extras :: any).model then + prop = n + end + if n.camera == 1 then + cam = n + end + end + t:check(prop and prop.translation and prop.translation[1] == 64 and (prop.extras :: any).vmf.classname == "prop_static", "room: prop_static node") + t:check(cam ~= nil and cam.rotation ~= nil, "room: camera node") + if cam then + -- the camera's -z looks at [0 0 64] + local q = cam.rotation :: { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local fx = -(2 * (x * z + w * y)) + local fy = -(2 * (y * z - w * x)) + local fz = -(1 - 2 * (x * x + y * y)) + local dx, dy, dz = 200, 200, -64 + local l = math.sqrt(dx * dx + dy * dy + dz * dz) + t:check(math.abs(fx - dx / l) + math.abs(fy - dy / l) + math.abs(fz - dz / l) < 1e-6, "room: camera looks at its target") + end + t:eq(scene.meta.source.editorBuild, 8864, "versioninfo") +end + +do + -- builders + local doc = Vmf.document({ skyname = "sky_day01_01" }) + table.insert(Vmf.world(doc) :: any, Vmf.box({ -64, -64, 0 }, { 64, 64, 16 }, "DEV/DEV_MEASUREGENERIC01B")) + Vmf.entity(doc, { { "classname", "func_detail" } }, { Vmf.box({ 0, 0, 16 }, { 32, 32, 48 }, "BRICK/BRICKWALL001A") }) + Vmf.entity(doc, { { "classname", "info_player_start" }, { "origin", "0 0 17" } }) + local text = buffer.tostring(Vmf.encode(doc) :: buffer) + local scene = dec(text, { textureSizes = { ["DEV/DEV_MEASUREGENERIC01B"] = { 128, 128 } } }) :: Types.Scene + t:check(scene ~= nil, "built document decodes") + t:eq(#scene.meta.entities, 3, "world + 2 entities") + t:eq(string.sub(text, 1, 12), "versioninfo\n", "Hammer layout") + local ok = true + for _, s in Vmf.brushes(scene.meta.vmf) :: { any } do + local polys = Brush.polygons({ s.faces }) :: { Brush.Polygon } + ok = ok and #polys == 6 + for _, p in polys do + -- outward: the normal points away from the brush centre + local cx, cy, cz = 0, 0, 0 + for _, q in polys do + cx += q.points[1] + cy += q.points[2] + cz += q.points[3] + end + cx, cy, cz = cx / 6, cy / 6, cz / 6 + ok = ok and (p.points[1] - cx) * p.normal[1] + (p.points[2] - cy) * p.normal[2] + (p.points[3] - cz) * p.normal[3] > -1e-9 + end + end + t:check(ok, "boxes: 6 outward faces") + local mat = scene.materials[1] + t:eq((mat.extras :: any).vmf.width, 128, "textureSizes") + local P = scene.meshes[1].primitives[1].attributes.TEXCOORD_0 + local maxU = 0 + for i = 0, P.count - 1 do + maxU = math.max(maxU, math.abs(buffer.readf32(P.data, i * 8))) + end + t:check(math.abs(maxU - 2) < 1e-6, "Valve 220 UVs: 64 units / 0.25 scale / 128 texels") + local _, e1 = dec('world\n{\n\tsolid\n\t{\n\t\tside\n\t\t{\n\t\t\t"plane" "(0 0 0) (1 1)"\n\t\t}\n\t}\n}\n') + t:eq(e1 and e1.code, Err.CORRUPT, "bad plane") + local _, e2 = dec("world\n{\n") + t:eq(e2 and e2.code, Err.TRUNCATED, "truncated") + local _, e3 = Vmf.encode({ kind = "scene", meta = {} }) + t:eq(e3 and e3.code, Err.ARG, "a Scene without meta.vmf") + t:check(Vmf.sniff(Bytes.reader(buffer.fromstring(Fx.room.data))) > 0.5, "sniff") +end + +local samples = { Fx.room.data } +for i = 1, 3 do + table.insert(samples, Fx.files[i].data) +end +t:fuzz("decode", function(b: buffer) + return Vmf.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 7461520..70507a2 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -219,6 +219,26 @@ do end) end +-- ws-source: KeyValues text (a 1 MB file of nested blocks) and an entity lump +do + local KeyValues = require("@rosetta/codecs/text/KeyValues") + local parts = { '"root"\n{\n' } + local ents = {} + for i = 1, 6000 do + table.insert(parts, string.format('\t"block%d"\n\t{\n\t\t"name"\t"item %d"\n\t\t"origin"\t"%d 0 64"\n\t\t"path"\t"models/props/x\\\\y.mdl"\n\t}\n', i, i, i)) + table.insert(ents, string.format('{\n"origin" "%d 0 64"\n"classname" "prop_dynamic"\n"OnTrigger" "a,b,,0,-1"\n}\n', i)) + end + table.insert(parts, "}\n") + local text, lump = table.concat(parts), table.concat(ents) + assert(KeyValues.parse(text)) + bench("keyvalues parse", 5, #text, function() + KeyValues.parse(text) + end) + bench("keyvalues entity lump", 5, #lump, function() + KeyValues.entities(lump) + end) +end + -- ws-arch codecs: zstd, brotli, bzip2, xz / lzma do local Zstd = require("@rosetta/codecs/compress/Zstd") diff --git a/tools/fixtures/_qbsp.py b/tools/fixtures/_qbsp.py new file mode 100644 index 0000000..074439a --- /dev/null +++ b/tools/fixtures/_qbsp.py @@ -0,0 +1,153 @@ +# Shared helpers for the Quake map fixtures (brush.py, map.py, bsp.py, wad2.py): WAD2 / WAD3 writing, running +# ericw-tools (qbsp, light, vis from nixpkgs) on a .map, and a reader of the Quake 1 family BSP files they write +# (BSP 29, BSP2, 2PSB: layouts from bspfile.h of the Quake source release and ericw-tools; no code taken). +# wad(lumps, magic) -> bytes: lumps = [(name, type, data)] +# miptex(name, w, h, rng, palette=None) -> bytes (four mip levels of random indices; WAD3 / BSP 30 add the palette) +# compile(ctx, text, files, qbsp_args, light_args=None, vis=False) -> { bsp, obj?, log } +# read_bsp(data) -> dict of the parsed lumps +import os, shutil, struct, subprocess, tempfile + +Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"] + + +def wad(lumps, magic=b"WAD2"): + body = b"" + dirs = [] + for name, typ, data in lumps: + dirs.append(struct.pack("> m, h >> m + px = pixels[m] if pixels else bytes(rng.randrange(256) for _ in range(lw * lh)) + offs.append(o) + levels.append(px) + o += lw * lh + out += struct.pack("<4I", *offs) + b"".join(levels) + if palette is not None: + out += struct.pack("= 4: + n = struct.unpack_from("= 0 else e[1]]) + return pts + + +def face_plane(b, f): + nx, ny, nz, d, _ = b["planes"][f["plane"]] + if f["side"]: + return (-nx, -ny, -nz, -d) + return (nx, ny, nz, d) diff --git a/tools/fixtures/brush.py b/tools/fixtures/brush.py new file mode 100644 index 0000000..cdbfae9 --- /dev/null +++ b/tools/fixtures/brush.py @@ -0,0 +1,148 @@ +# codecs/model/Brush fixtures (tools/fixtures.py): random convex brushes (boxes on a 16-unit grid, some with corners cut +# by planes through three integer points; overlapping, touching and coplanar ones) written as Quake standard, Valve 220 +# and brush-primitive .map files, compiled with ericw-tools' qbsp -nofill (no outside fill: every CSG face survives) +# against a WAD2 of textures with their sizes. Reference: qbsp's faces (plane, corners, texinfo vectors and texture). +# tests/gen/brush.luau { [format] = { brushes = { { { pts = { 9 numbers }, tex, kind, args } } }, +# sizes = { [tex] = { w, h } }, faces = { { plane = { 4 }, pts = { 3n }, tex, vecs = { 8 } } } } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_qbsp.py"] + +TEXTURES = [("brick", 64, 32), ("metal", 32, 128), ("wood", 128, 64), ("stone", 16, 16)] + + +def helper(ctx): + spec = importlib.util.spec_from_file_location("_qbsp", os.path.join(ctx.root, "tools", "fixtures", "_qbsp.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def sub(a, b): + return (a[0] - b[0], a[1] - b[1], a[2] - b[2]) + + +def cross(u, v): + return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + + +def dot(u, v): + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] + + +def oriented(p1, p2, p3, center): + # qbsp: normal = (p1 - p2) x (p3 - p2) points out of the brush + n = cross(sub(p1, p2), sub(p3, p2)) + if dot(n, sub(center, p2)) > 0: + return (p3, p2, p1) + return (p1, p2, p3) + + +def box_faces(lo, hi): + (x0, y0, z0), (x1, y1, z1) = lo, hi + return [ + ((x0, y0, z0), (x0, y0 + 1, z0), (x0, y0, z0 + 1)), + ((x1, y1, z1), (x1, y1, z1 + 1), (x1, y1 + 1, z1)), + ((x0, y0, z0), (x0, y0, z0 + 1), (x0 + 1, y0, z0)), + ((x1, y1, z1), (x1 + 1, y1, z1), (x1, y1, z1 + 1)), + ((x0, y0, z0), (x0 + 1, y0, z0), (x0, y0 + 1, z0)), + ((x1, y1, z1), (x1, y1 + 1, z1), (x1 + 1, y1, z1)), + ] + + +def brushes(rng): + out = [] + for i in range(14): + lo = tuple(rng.randrange(-8, 6) * 16 for _ in range(3)) + hi = tuple(lo[k] + rng.randrange(2, 7) * 16 for k in range(3)) + faces = box_faces(lo, hi) + center = tuple((lo[k] + hi[k]) / 2 for k in range(3)) + for _ in range(rng.randrange(0, 3)): + corner = tuple(rng.choice((lo[k], hi[k])) for k in range(3)) + pts = [] + for k in range(3): + p = list(corner) + size = hi[k] - lo[k] + step = rng.randrange(4, size // 2 + 1) + p[k] += step if corner[k] == lo[k] else -step + pts.append(tuple(p)) + faces.append(oriented(pts[0], pts[1], pts[2], center)) + out.append(faces) + return out + + +def num(x): + s = ("%.6f" % x).rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + + +def projection(rng, kind): + if kind == "standard": + return [rng.randrange(-64, 65), rng.randrange(-64, 65), rng.choice([0, 90, 180, 270, 15, 30, 45, 33.5]), + rng.choice([1, 0.5, 2, -1, 0.25, 1.5]), rng.choice([1, 0.5, 2, -1, 0.75])] + if kind == "valve": + u = [round(rng.uniform(-1, 1), 4) for _ in range(3)] + v = [round(rng.uniform(-1, 1), 4) for _ in range(3)] + return u + [rng.randrange(-32, 33)] + v + [rng.randrange(-32, 33), 0, rng.choice([1, 0.5, 2, -1]), rng.choice([1, 0.25, 2])] + while True: # qbsp replaces a singular matrix by the default projection + m = [rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16, + rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16] + if m[0] * m[4] - m[1] * m[3] != 0: + return m + + +def face_line(kind, pts, tex, a): + p = " ".join("( %s )" % " ".join(num(c) for c in q) for q in pts) + if kind == "standard": + return "%s %s %s" % (p, tex, " ".join(num(x) for x in a)) + if kind == "valve": + return "%s %s [ %s ] [ %s ] %s" % (p, tex, " ".join(num(x) for x in a[0:4]), " ".join(num(x) for x in a[4:8]), + " ".join(num(x) for x in a[8:11])) + return "%s ( ( %s ) ( %s ) ) %s 0 0 0" % (p, " ".join(num(x) for x in a[0:3]), " ".join(num(x) for x in a[3:6]), tex) + + +def write_map(kind, bl, rng): + lines = ["// Game: Quake", "{", '"classname" "worldspawn"', '"wad" "tex.wad"'] + if kind == "valve": + lines.append('"mapversion" "220"') + recs = [] + for faces in bl: + lines.append("{") + if kind == "bp": + lines.append("brushDef") + lines.append("{") + rec = [] + for pts in faces: + tex = rng.choice(TEXTURES)[0] + a = projection(rng, kind) + lines.append(face_line(kind, pts, tex, a)) + rec.append({"pts": [float(c) for q in pts for c in q], "tex": tex, "kind": kind, "args": [float(x) for x in a]}) + if kind == "bp": + lines.append("}") + lines.append("}") + recs.append(rec) + lines += ["}", "{", '"classname" "info_player_start"', '"origin" "0 0 0"', "}", ""] + return "\n".join(lines), recs + + +def generate(ctx): + H = helper(ctx) + rng = ctx.rng(777) + lumps = [(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEXTURES] + w2 = H.wad(lumps) + out = {} + for kind in ("standard", "valve", "bp"): + bl = brushes(rng) + text, recs = write_map(kind, bl, rng) + res = H.compile(ctx, text, {"tex.wad": w2}, ["-nofill", "-noclip", "-nopercent"]) + b = H.read_bsp(res["bsp"]) + world = b["models"][0] + first, count = world[14], world[15] + faces = [] + for f in b["faces"][first:first + count]: + ti = b["texinfo"][f["texinfo"]] + tex = b["textures"][ti[8]][0] + faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p], + "tex": tex, "vecs": list(ti[0:8])}) + out[kind] = {"brushes": recs, "sizes": {n: [w, h] for n, w, h in TEXTURES}, "faces": faces, "map": text} + ctx.emit("brush", out) diff --git a/tools/fixtures/docs_source.py b/tools/fixtures/docs_source.py new file mode 100644 index 0000000..45abc53 --- /dev/null +++ b/tools/fixtures/docs_source.py @@ -0,0 +1,21 @@ +# Docs inputs for the Source engine sections of the scene page (tools/fixtures.py; tools/docs_check.py explains the +# inputs): the CS:GO-style VBSP of tools/fixtures/vbsp.py (srctools-saved, static props v11) and the Hammer VMF of +# tools/fixtures/vmf.py. +# tests/gen/docs_source.luau { files = { [name] = bytes }, vars = { vbspBytes = "room.bsp", vmfText = "room.vmf" } } +import importlib.util, json, os + +INPUTS = ["tools/docs_check.py", "tools/fixtures/vbsp.py", "tools/fixtures/vmf.py"] + + +def mod(ctx, name): + spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", name + ".py") if name == "docs_check" else os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + res = json.loads(ctx.python(["srctools"], mod(ctx, "vbsp").CODE)) + files = {"room.bsp": next(bytes.fromhex(c["data"]) for c in res["cases"] if c["name"] == "csgo")} + files["room.vmf"] = mod(ctx, "vmf").room().encode() + mod(ctx, "docs_check").emit_inputs(ctx, files, {"vbspBytes": "room.bsp", "vmfText": "room.vmf"}) diff --git a/tools/fixtures/map.py b/tools/fixtures/map.py new file mode 100644 index 0000000..8f49fc2 --- /dev/null +++ b/tools/fixtures/map.py @@ -0,0 +1,172 @@ +# model/map fixtures (tools/fixtures.py): .map files written here in the four dialects and compiled with ericw-tools +# qbsp -nofill (Quake 1 BSP; it reads all four). Reference: qbsp's faces per model (plane, corners, texinfo vectors, +# texture and its size from the WAD), so the test checks our CSG'd polygons and texture coordinates per entity. +# quake: a room (6 wall boxes), a pillar, a func_door, point entities, Quake standard faces, "wad" -> tex.wad (WAD2) +# valve: the same layout in Valve 220 with a WAD3 named by a Windows path +# quake2: Quake II faces with contents / flags / value; sizes from textures/.wal +# quake3: brushDef faces + a patchDef2 (qbsp compiles the brushes of a copy without the patch; the patch reference is +# evaluated here: biquadratic Bezier, 4 segments per sub-patch) +# tests/gen/map.luau { [name] = { text, files = { [name] = bytes }, models = { [model] = { faces } }, sizes, patch? } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_qbsp.py", "tools/fixtures/brush.py"] + +TEX = [("brick", 64, 32), ("metal", 32, 128), ("wood", 128, 64), ("+0lava", 64, 64), ("stone", 16, 16)] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def layout(rng): + world = [] + # room [-256, 256] x [-256, 256] x [0, 256], walls 16 thick + lo, hi = (-256, -256, 0), (256, 256, 256) + t = 16 + world.append(((lo[0] - t, lo[1] - t, lo[2] - t), (hi[0] + t, hi[1] + t, lo[2]))) + world.append(((lo[0] - t, lo[1] - t, hi[2]), (hi[0] + t, hi[1] + t, hi[2] + t))) + world.append(((lo[0] - t, lo[1] - t, lo[2]), (lo[0], hi[1] + t, hi[2]))) + world.append(((hi[0], lo[1] - t, lo[2]), (hi[0] + t, hi[1] + t, hi[2]))) + world.append(((lo[0], lo[1] - t, lo[2]), (hi[0], lo[1], hi[2]))) + world.append(((lo[0], hi[1], lo[2]), (hi[0], hi[1] + t, hi[2]))) + world.append(((-32, -32, 0), (32, 32, 192))) # pillar standing on the floor + world.append(((64, 64, -8), (160, 128, 48))) # a box sunk into the floor + door = [((100, -200, 0), (116, -120, 128))] + return world, door + + +def faces_for(B, box, rng, kind): + out = [] + for pts in B.box_faces(*box): + tex = rng.choice(TEX)[0] + out.append((pts, tex, B.projection(rng, "bp" if kind == "quake3" else ("valve" if kind == "valve" else "standard")))) + return out + + +def face_text(B, kind, pts, tex, a, flags): + k = {"quake": "standard", "quake2": "standard", "valve": "valve", "quake3": "bp"}[kind] + line = B.face_line(k, pts, tex, a) + if kind == "quake3": + line = line[: -len(" 0 0 0")] + " " + " ".join(str(x) for x in flags) + elif kind == "quake2": + line += " " + " ".join(str(x) for x in flags) + return line + + +def write(B, kind, world, door, rng, wadkey, patch=None): + head = {"quake": "// Game: Quake\n// Format: Standard\n", "valve": "// Game: Half-Life\n// Format: Valve\n", + "quake2": "// Game: Quake 2\n// Format: Quake2\n", "quake3": "// Game: Quake 3\n// Format: Quake3\n"}[kind] + lines = [head + "{", '"classname" "worldspawn"', '"message" "fixture room"'] + if wadkey: + lines.append('"wad" "%s"' % wadkey) + if kind == "valve": + lines.append('"mapversion" "220"') + for box in world: + lines.append("{") + if kind == "quake3": + lines += ["brushDef", "{"] + for pts, tex, a in faces_for(B, box, rng, kind): + lines.append(face_text(B, kind, pts, tex, a, [0, rng.randrange(0, 4), 0])) + if kind == "quake3": + lines.append("}") + lines.append("}") + if patch: + lines.append(patch) + lines += ["}", "{", '"classname" "func_door"', '"targetname" "door1"', '"angle" "90"'] + for box in door: + lines.append("{") + if kind == "quake3": + lines += ["brushDef", "{"] + for pts, tex, a in faces_for(B, box, rng, kind): + lines.append(face_text(B, kind, pts, tex, a, [1, 0, 5])) + if kind == "quake3": + lines.append("}") + lines.append("}") + lines += ["}", "{", '"classname" "info_player_start"', '"origin" "-128 -128 24"', '"angle" "45"', "}", + "{", '"classname" "light"', '"origin" "0 0 200"', '"light" "300"', "}", ""] + return "\n".join(lines) + + +def bezier_patch(w, h, ctrl, level): + # ctrl[(i * w + j)] row-major (row i, column j) of (x, y, z, s, t); quadratic Bezier per 3 x 3 sub-patch + px, py = (w - 1) // 2, (h - 1) // 2 + gw, gh = px * level + 1, py * level + 1 + out = [] + for gy in range(gh): + sy = min(gy // level, py - 1) + tv = (gy - sy * level) / level + bv = [(1 - tv) ** 2, 2 * tv * (1 - tv), tv * tv] + for gx in range(gw): + sx = min(gx // level, px - 1) + tu = (gx - sx * level) / level + bu = [(1 - tu) ** 2, 2 * tu * (1 - tu), tu * tu] + p = [0.0] * 5 + for j in range(3): + for i in range(3): + c = ctrl[(sy * 2 + j) * w + sx * 2 + i] + for k in range(5): + p[k] += c[k] * bu[i] * bv[j] + out.append(p) + return out, gw, gh + + +def compile_faces(H, ctx, text, files): + res = H.compile(ctx, text, files, ["-nofill", "-noclip", "-nopercent"]) + b = H.read_bsp(res["bsp"]) + models = {} + for mi, m in enumerate(b["models"]): + first, count = m[14], m[15] + faces = [] + for f in b["faces"][first:first + count]: + ti = b["texinfo"][f["texinfo"]] + name, w, h = b["textures"][ti[8]] + assert name and w and h, "qbsp did not find the texture WAD" + faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p], + "tex": name, "vecs": list(ti[0:8]), "size": [w, h]}) + models[str(mi)] = faces + return models + + +def generate(ctx): + H = load(ctx, "_qbsp") + B = load(ctx, "brush") + rng = ctx.rng(4242) + world, door = layout(rng) + out = {} + wad2 = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEX]) + pal = bytes(rng.randrange(256) for _ in range(768)) + wad3 = H.wad([(n, 0x43, H.miptex(n, w, h, rng, pal)) for n, w, h in TEX], b"WAD3") + sizes = {n: [w, h] for n, w, h in TEX} + # quake + text = write(B, "quake", world, door, rng, "gfx/tex.wad") + out["quake"] = {"text": text, "files": {"gfx/tex.wad": wad2}, "models": compile_faces(H, ctx, text.replace("gfx/tex.wad", "tex.wad"), {"tex.wad": wad2}), "sizes": sizes} + # valve 220 with a WAD3 under a Windows path + text = write(B, "valve", world, door, rng, "\\half-life\\valve\\tex3.wad") + qtext = text.replace("\\half-life\\valve\\tex3.wad", "tex3.wad") + out["valve"] = {"text": text, "files": {"tex3.wad": wad3}, "models": compile_faces(H, ctx, qtext, {"tex3.wad": wad3}), "sizes": sizes} + # quake 2: .wal sizes (qbsp is given the same sizes through a WAD of the same names) + text = write(B, "quake2", world, door, rng, None) + wals = {} + for n, w, h in TEX: + wals["textures/" + n + ".wal"] = (n.encode() + b"\0" * (32 - len(n))) + w.to_bytes(4, "little") + h.to_bytes(4, "little") + bytes(60) + qtext = text.replace('"message" "fixture room"', '"message" "fixture room"\n"wad" "tex.wad"') + out["quake2"] = {"text": text, "files": wals, "models": compile_faces(H, ctx, qtext, {"tex.wad": wad2}), "sizes": sizes} + # quake 3: brushDef + a 5 x 3 patch + W, Hh = 5, 3 + ctrl = [] + for i in range(Hh): + for j in range(W): + ctrl.append([-200 + j * 40, 100 + i * 50, 64 + (48 if i == 1 else 0) + (24 if j % 2 else 0), j / 4, i / 2]) + rows = [] + for j in range(W): # file order: column by column + rows.append("( " + " ".join("( %s )" % " ".join(B.num(x) for x in ctrl[i * W + j]) for i in range(Hh)) + " )") + patch = "{\npatchDef2\n{\nbase/curve\n( %d %d 0 0 0 )\n(\n%s\n)\n}\n}" % (W, Hh, "\n".join(rows)) + text = write(B, "quake3", world, door, rng, "tex.wad", patch) + plain = text.replace(patch + "\n", "") + grid, gw, gh = bezier_patch(W, Hh, ctrl, 4) + out["quake3"] = {"text": text, "files": {"tex.wad": wad2}, "models": compile_faces(H, ctx, plain, {"tex.wad": wad2}), "sizes": sizes, + "patch": {"grid": [c for p in grid for c in p], "w": gw, "h": gh}} + ctx.emit("map", out) diff --git a/tools/fixtures/vbsp.py b/tools/fixtures/vbsp.py new file mode 100644 index 0000000..cedbc27 --- /dev/null +++ b/tools/fixtures/vbsp.py @@ -0,0 +1,305 @@ +# model/vbsp fixtures: a small Source map (a room of brush faces, a non-quad ceiling, a nodraw face, a power-3 +# displacement floor, a func_brush model, entities with repeated outputs, a pak lump) written here from the SDK's +# bspfile.h layouts, then loaded and saved by srctools (BSP.save: static props in game lump versions 4 .. 11, LZMA +# compressed lumps, the L4D2 lump header, a v19 header, a srctools-written entity lump). What srctools reads back from +# each saved file is the reference: face polygons + texinfo projections, static props, entities, pak file names; the +# displacement grid is tessellated here as CCoreDispInfo::GenerateDispSurf does. +# tests/gen/vbsp.luau { cases = { { name, data, version, l4d2?, compressed?, props, entities, pak, groups } } } +# groups: one per (model, material): { model, material, tris, verts = sorted "x y z u v" lines (%.2f) }. +import json + +CODE = r''' +import io, json, math, os, struct, sys, tempfile, zipfile +import srctools.bsp as B +from srctools import Vec, Angle +_out, sys.stdout = sys.stdout, sys.stderr # BSP.save prints + +SURF_NODRAW = 0x80 + +def build(): + texdata = [("BRICK/BRICKWALL001A", 512, 512), ("TOOLS/TOOLSNODRAW", 64, 64), ("NATURE/BLENDGRASSDIRT", 256, 256)] + texinfo = [ # s xyz shift, t xyz shift, flags, texdata + ((0.25, 0, 0, 16), (0, 0, -0.25, 8), 0, 0), + ((0, 0.25, 0, 0), (0, 0, -0.25, 0), 0, 0), + ((0.25, 0, 0, 0), (0, -0.25, 0, 0), 0, 0), + ((0.25, 0, 0, 0), (0, 0.25, 0, 0), SURF_NODRAW, 1), + ((0.125, 0, 0, 0), (0, -0.125, 0, 32), 0, 2), + ] + verts, vindex = [], {} + def v(p): + p = tuple(float(x) for x in p) + if p not in vindex: + vindex[p] = len(verts) + verts.append(p) + return vindex[p] + edges, eindex, surfedges = [(0, 0)], {}, [] + def poly_edges(poly): + first = len(surfedges) + ids = [v(p) for p in poly] + for k in range(len(ids)): + a, b = ids[k], ids[(k + 1) % len(ids)] + if (b, a) in eindex: + surfedges.append(-eindex[(b, a)]) + else: + if (a, b) not in eindex: + eindex[(a, b)] = len(edges) + edges.append((a, b)) + surfedges.append(eindex[(a, b)]) + return first, len(ids) + planes = [] + def plane(n, d): + planes.append((n, d)) + return len(planes) - 1 + def newell(poly): + nx = ny = nz = 0.0 + for k in range(len(poly)): + x1, y1, z1 = poly[k]; x2, y2, z2 = poly[(k + 1) % len(poly)] + nx += (y1 - y2) * (z1 + z2); ny += (z1 - z2) * (x1 + x2); nz += (x1 - x2) * (y1 + y2) + l = math.sqrt(nx * nx + ny * ny + nz * nz) + return (nx / l, ny / l, nz / l) + faces = [] + def face(poly, ti, disp=-1, flip_side=False): + # Source winding: clockwise seen from the front, so the front normal is minus Newell's + n = tuple(-c for c in newell(poly)) + d = sum(a * b for a, b in zip(n, poly[0])) + if flip_side: + pn, side = plane(tuple(-c for c in n), -d), 1 + else: + pn, side = plane(n, d), 0 + fe, ne = poly_edges(poly) + faces.append(dict(plane=pn, side=side, firstedge=fe, numedges=ne, texinfo=ti, disp=disp)) + return len(faces) - 1 + S, H = 256.0, 256.0 + # inward-facing room walls: clockwise seen from inside + face([(-S, -S, 0), (-S, -S, H), (S, -S, H), (S, -S, 0)], 0) # south wall, faces +y + face([(S, S, 0), (S, S, H), (-S, S, H), (-S, S, 0)], 0, flip_side=True) # north wall, faces -y (plane side 1) + face([(-S, S, 0), (-S, S, H), (-S, -S, H), (-S, -S, 0)], 1) # west, faces +x + face([(S, -S, 0), (S, -S, H), (S, S, H), (S, S, 0)], 1) # east, faces -x + # an octagonal ceiling facing down + oc = [] + for k in range(8): + a = -2 * math.pi * k / 8 + oc.append((round(S * math.cos(a), 3), round(S * math.sin(a), 3), H)) + face(list(reversed(oc)), 2) + face([(-S, -S, H + 8), (S, -S, H + 8), (S, S, H + 8), (-S, S, H + 8)], 3) # nodraw + # displacement floor facing up (clockwise seen from above), start position at its second corner + floor = [(-S, -S, 0), (-S, S, 0), (S, S, 0), (S, -S, 0)] + fdisp = face(floor, 4, disp=0) + world_faces = len(faces) + # func_brush: a 32-unit cube around its own origin, outward faces + c = 16.0 + cube = [ + [(-c, -c, c), (-c, c, c), (c, c, c), (c, -c, c)], + [(-c, -c, -c), (c, -c, -c), (c, c, -c), (-c, c, -c)], + [(-c, -c, -c), (-c, -c, c), (c, -c, c), (c, -c, -c)], + [(c, c, -c), (c, c, c), (-c, c, c), (-c, c, -c)], + [(-c, c, -c), (-c, c, c), (-c, -c, c), (-c, -c, -c)], + [(c, -c, -c), (c, -c, c), (c, c, c), (c, c, -c)], + ] + for p in cube: + face(p, 0) + models = [((-S, -S, 0), (S, S, H + 8), (0, 0, 0), 0, world_faces), ((-c, -c, -c), (c, c, c), (0, 0, 0), world_faces, len(faces) - world_faces)] + power = 3 + n = 2 ** power + 1 + dispverts = [] + for i in range(n): + for j in range(n): + dist = 24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8 + dispverts.append(((0.0, 0.0, 1.0) if dist >= 0 else (0.0, 0.0, -1.0), abs(dist), (i * 31 + j * 7) % 256)) + dispinfo = dict(start=floor[1], power=power, face=fdisp) + ents = ( + '{\n"world_maxs" "256 256 264"\n"world_mins" "-256 -256 0"\n"skyname" "sky_day01_01"\n"mapversion" "7"\n"classname" "worldspawn"\n}\n' + '{\n"origin" "0 0 64"\n"model" "*1"\n"targetname" "door"\n"classname" "func_brush"\n}\n' + '{\n"origin" "-128 0 32"\n"angles" "0 90 0"\n"classname" "info_player_start"\n}\n' + '{\n"origin" "0 0 200"\n"_light" "255 240 200 300"\n"classname" "light"\n}\n' + '{\n"targetname" "relay"\n"OnTrigger" "door,Enable,,0,-1"\n"OnTrigger" "door,Disable,,5,-1"\n"classname" "logic_relay"\n}\n' + ) + pak = io.BytesIO() + with zipfile.ZipFile(pak, "w", zipfile.ZIP_STORED) as z: + z.writestr("materials/maps/test/cubemapdefault.vtf", b"VTF\0" + bytes(60)) + z.writestr("materials/custom/note.txt", b"hello from the pak lump\n") + return dict(texdata=texdata, texinfo=texinfo, verts=verts, edges=edges, surfedges=surfedges, planes=planes, + faces=faces, models=models, dispverts=dispverts, dispinfo=dispinfo, ents=ents, pak=pak.getvalue()) + +def write(m, version=20): + lumps = {} + lumps[0] = m["ents"].encode() + b"\0" + lumps[1] = b"".join(struct.pack("<3ffi", *n, d, 0) for n, d in m["planes"]) + names = b"" + table = [] + for name, w, h in m["texdata"]: + table.append(len(names)) + names += name.encode() + b"\0" + lumps[43] = names + lumps[44] = b"".join(struct.pack("= 0 else b]) + start = min(range(4), key=lambda k: sum((corners[k][i] - di["start"][i]) ** 2 for i in range(3))) + p = corners[start:] + corners[:start] + n = 2 ** di["power"] + 1 + out = [] + lerp = lambda a, b, t: tuple(a[i] + (b[i] - a[i]) * t for i in range(3)) + for i in range(n): + e0 = lerp(p[0], p[1], i / (n - 1)) + e1 = lerp(p[3], p[2], i / (n - 1)) + for j in range(n): + base = lerp(e0, e1, j / (n - 1)) + vec, dist, alpha = m["dispverts"][i * n + j] + dist = struct.unpack("= 0: + pw = 2 ** m["dispinfo"]["power"] + g["tris"] += 2 * pw * pw + for base, pos in disp: + g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (*pos, *uv(base))) + else: + poly = [e.a for e in f.edges] + g["tris"] += len(poly) - 2 + for q in poly: + g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (q.x, q.y, q.z, *uv((q.x, q.y, q.z)))) + for g in groups.values(): + g["verts"] = "\n".join(sorted(g["verts"])) + props = [{"model": sp.model, "origin": list(sp.origin), "angles": [sp.angles.pitch, sp.angles.yaw, sp.angles.roll], + "skin": sp.skin, "scale": sp.scaling if isinstance(sp.scaling, float) else sp.scaling.x} for sp in bsp.props] + ents = [bsp.ents.spawn] + list(bsp.ents.entities) + outputs = sum(len(e.outputs) for e in ents) + pak = sorted(bsp.pakfile.namelist()) + return {"groups": sorted(groups.values(), key=lambda g: (g["model"], g["material"])), "props": props, + "entities": len(ents), "outputs": outputs, "classnames": sorted(e["classname"] for e in ents), "pak": pak, + "spversion": bsp.static_prop_version.version} + +m = build() +base = write(m) +cases = [] +V = B.StaticPropVersion +for name, kw in [ + ("v20", dict(sp=V.V6)), + ("v19", dict(version=19, sp=V.V4)), + ("v20_v5", dict(sp=V.V5)), + ("v20_lzma", dict(sp=V.V10, compress=True)), + ("tf2_v7", dict(sp=V.V7)), + ("l4d2", dict(version=B.VERSIONS.L4D2, sp=V.V9, l4d2=True)), + ("csgo", dict(version=21, sp=V.V11)), + ("csgo_lzma", dict(version=21, sp=V.V11, compress=True)), + ("l4d_v8", dict(version=20, sp=V.V8)), + ("srctools_ents", dict(sp=V.V5, rewrite_ents=True)), +]: + data = variant(base, name, **kw) + ref = reference(data, m) + ref.update({"name": name, "data": data.hex(), "version": struct.unpack_from("