merge ws/source: VBSP v19-21, VMF, KeyValues / data/vdf, codecs/model/Displacement (with ws/quake's Brush / Patch / Miptex)

This commit is contained in:
4DBug committed 2026-11-01 19:46:56 -06:00
commit e100366cb8
44 files changed
+18855 -1508

No files matched your search

+214
View File
@@ -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
+58 -2
View File
@@ -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
+638
View File
@@ -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
+147
View File
@@ -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
+122
View File
@@ -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
@@ -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 }
+29 -16
View File
@@ -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