ws-game: archive/wad (IWAD / PWAD read + write; lumps with namespaces and maps; flats / pictures / composed textures as Images via PLAYPAL; maps as Scenes: triangulated sector floors / ceilings, walls with vanilla alignment, things); codecs/model/Polygon (2D polygons with holes -> triangles); licenses: Freedoom (fixture source only)

This commit is contained in:
4DBug committed 2026-10-31 14:05:53 -05:00
1 parent eac069f7dc
commit 5ec3121f65
11 files changed
+1823

No files matched your search

+2
View File
@@ -56,6 +56,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
| archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` |
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
@@ -128,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- **model**
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
- **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
+1
View File
@@ -38,6 +38,7 @@
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `tests/gen/wad` (cut down from the nix freedoom package at fixture time, not committed) | Freedoom 0.13 (freedoom.github.io) | BSD-3-Clause: [freedoom-COPYING.txt](freedoom-COPYING.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+30
View File
@@ -0,0 +1,30 @@
Copyright © 2001-2024
Contributors to the Freedoom project. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Freedoom project nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS
IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For a list of contributors to the Freedoom project, see the file
CREDITS.
+12
View File
@@ -626,6 +626,18 @@ local list: { Entry } = {
return require("@formats/archive/tar")
end,
},
{
name = "wad",
category = "archive",
path = "archive/wad",
extensions = { "wad" },
mime = { "application/x-doom" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
load = function()
return require("@formats/archive/wad")
end,
},
{
name = "xz",
category = "archive",
+441
View File
@@ -0,0 +1,441 @@
--!strict
-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS,
-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a
-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with
-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the
-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one
-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z
-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not
-- supported.
local Types = require("@formats/Types")
local Polygon = require("@formats/codecs/model/Polygon")
local Map = {}
local Scene = Types.Scene
local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { buf: buffer, at: number, size: number }
export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? }
export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? }
export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number }
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number }
export type MapData = {
format: "doom" | "hexen",
things: { Thing },
linedefs: { Linedef },
sidedefs: { Sidedef },
vertices: { number }, -- x1, y1, x2, y2, ...
sectors: { Sector },
}
-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows
export type Textures = {
size: (kind: string, name: string) -> (number?, number?),
image: ((kind: string, name: string) -> Types.Image?)?,
}
-- ------------------------------------------------------------------------------------------------ parse
local function name8(b: buffer, at: number): string
local s = buffer.readstring(b, at, 8)
local z = string.find(s, "\0", 1, true)
return string.upper(if z then string.sub(s, 1, z - 1) else s)
end
local function side(v: number): number?
return if v == 0xFFFF then nil else v + 1
end
-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump)
function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?)
for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do
if not lumps[k] then
return nil, "map has no " .. k
end
end
local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} }
local v = lumps.VERTEXES
for i = 0, v.size // 4 - 1 do
table.insert(m.vertices, readi16(v.buf, v.at + i * 4))
table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2))
end
local s = lumps.SECTORS
for i = 0, s.size // 26 - 1 do
local o = s.at + i * 26
table.insert(m.sectors, {
floor = readi16(s.buf, o),
ceiling = readi16(s.buf, o + 2),
floorFlat = name8(s.buf, o + 4),
ceilingFlat = name8(s.buf, o + 12),
light = readi16(s.buf, o + 20),
special = readu16(s.buf, o + 22),
tag = readu16(s.buf, o + 24),
})
end
local sd = lumps.SIDEDEFS
for i = 0, sd.size // 30 - 1 do
local o = sd.at + i * 30
table.insert(m.sidedefs, {
xoff = readi16(sd.buf, o),
yoff = readi16(sd.buf, o + 2),
upper = name8(sd.buf, o + 4),
lower = name8(sd.buf, o + 12),
middle = name8(sd.buf, o + 20),
sector = readu16(sd.buf, o + 28) + 1,
})
end
local l = lumps.LINEDEFS
local ls = if hexen then 16 else 14
for i = 0, l.size // ls - 1 do
local o = l.at + i * ls
local b = l.buf
if hexen then
table.insert(m.linedefs, {
v1 = readu16(b, o) + 1,
v2 = readu16(b, o + 2) + 1,
flags = readu16(b, o + 4),
special = readu8(b, o + 6),
args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) },
front = side(readu16(b, o + 12)),
back = side(readu16(b, o + 14)),
})
else
table.insert(m.linedefs, {
v1 = readu16(b, o) + 1,
v2 = readu16(b, o + 2) + 1,
flags = readu16(b, o + 4),
special = readu16(b, o + 6),
tag = readu16(b, o + 8),
front = side(readu16(b, o + 10)),
back = side(readu16(b, o + 12)),
})
end
end
local t = lumps.THINGS
if t then
local ts = if hexen then 20 else 10
for i = 0, t.size // ts - 1 do
local o = t.at + i * ts
local b = t.buf
if hexen then
table.insert(m.things, {
tid = readi16(b, o),
x = readi16(b, o + 2),
y = readi16(b, o + 4),
z = readi16(b, o + 6),
angle = readi16(b, o + 8),
type = readu16(b, o + 10),
flags = readu16(b, o + 12),
special = readu8(b, o + 14),
args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) },
})
else
table.insert(m.things, {
x = readi16(b, o),
y = readi16(b, o + 2),
angle = readi16(b, o + 4),
type = readu16(b, o + 6),
flags = readu16(b, o + 8),
})
end
end
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ sector outlines
-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1;
-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks;
-- chains that do not close are dropped
local function loops(m: MapData): { [number]: { { number } } }
local edges: { [number]: { { number } } } = {}
local nv = #m.vertices // 2
local function add(sec: number, a: number, b: number)
local e = edges[sec] or {}
edges[sec] = e
table.insert(e, { a, b })
end
for _, ld in m.linedefs do
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
local fs = ld.front and m.sidedefs[ld.front]
local bs = ld.back and m.sidedefs[ld.back]
local f = fs and fs.sector
local b = bs and bs.sector
if f ~= b then
if f and m.sectors[f] then
add(f, ld.v1, ld.v2)
end
if b and m.sectors[b] then
add(b, ld.v2, ld.v1)
end
end
end
end
local V = m.vertices
local out: { [number]: { { number } } } = {}
for sec, list in edges do
local from: { [number]: { number } } = {}
for i, e in list do
local l = from[e[1]] or {}
from[e[1]] = l
table.insert(l, i)
end
local used: { [number]: boolean } = {}
local res: { { number } } = {}
for start = 1, #list do
if not used[start] then
used[start] = true
local loop = { list[start][1] }
local cur = start
local closed = false
for _ = 1, #list do
local e = list[cur]
local at = e[2]
if at == loop[1] then
closed = true
break
end
table.insert(loop, at)
local cands = from[at]
local best, bestT = nil :: number?, math.huge
if cands then
local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2]
for _, c in cands do
if not used[c] then
local n2 = list[c][2]
local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2]
local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy)
if t < bestT then
best, bestT = c, t
end
end
end
end
if not best then
break
end
used[best] = true
cur = best
end
if closed and #loop >= 3 then
table.insert(res, loop)
end
end
end
out[sec] = res
end
return out
end
local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean
local c = false
local n = #loop
local j = n
for i = 1, n do
local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2]
local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2]
if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then
c = not c
end
j = i
end
return c
end
-- ------------------------------------------------------------------------------------------------ scene
type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } }
local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4
-- scene(m, tex, name) -> Scene
function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
local batches: { [string]: Batch } = {}
local order: { string } = {}
local function batch(kind: string, tname: string): Batch
local key = kind .. ":" .. tname
local b = batches[key]
if not b then
b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} }
batches[key] = b
table.insert(order, key)
end
return b
end
local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number)
local p, n, t = b.pos, b.nrm, b.uv
p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z
n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz
t[#t + 1], t[#t + 2] = u, v
end
local V = m.vertices
local nv = #V // 2
-- floors and ceilings
local secLoops = loops(m)
for sec, ls in secLoops do
local s = m.sectors[sec]
local flat: { { number } } = {}
for li, loop in ls do
local f: { number } = {}
for _, vi in loop do
table.insert(f, V[vi * 2 - 1])
table.insert(f, V[vi * 2])
end
flat[li] = f
end
local tris = Polygon.triangulate(flat)
for pass = 1, 2 do
local tname = if pass == 1 then s.floorFlat else s.ceilingFlat
local fw, fh = tex.size("flat", tname)
local w, h = fw or 64, fh or 64
local z = if pass == 1 then s.floor else s.ceiling
local b = batch("flat", tname)
local nz = if pass == 1 then 1 else -1
for k = 1, #tris, 6 do
for c = 0, 2 do
local cc = if pass == 1 then c else 2 - c
local loop = ls[tris[k + cc * 2]]
local vi = loop[tris[k + cc * 2 + 1]]
local x, y = V[vi * 2 - 1], V[vi * 2]
vert(b, x, y, z, 0, 0, nz, x / w, -y / h)
end
end
end
end
-- walls
local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number)
if tname == "-" or tname == "" or zt <= zb then
return
end
local tw, th = tex.size("texture", tname)
local w, h = tw or 64, th or 128
local b = batch("texture", tname)
local dx, dy = x2 - x1, y2 - y1
local l = math.sqrt(dx * dx + dy * dy)
local nx, ny = dy / l, -dx / l
local u0, u1 = xoff / w, (xoff + len) / w
local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
vert(b, x2, y2, zb, nx, ny, 0, u1, vb)
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
vert(b, x1, y1, zt, nx, ny, 0, u0, vt)
end
for _, ld in m.linedefs do
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2]
local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2)
for sideN = 1, 2 do
local sdi = if sideN == 1 then ld.front else ld.back
local odi = if sideN == 1 then ld.back else ld.front
local sd = sdi and m.sidedefs[sdi]
local me = sd and m.sectors[sd.sector]
if sd and me then
local x1, y1, x2, y2 = ax, ay, bx, by
if sideN == 2 then
x1, y1, x2, y2 = bx, by, ax, ay
end
local od = odi and m.sidedefs[odi]
local other = od and m.sectors[od.sector]
if not other then
local th = select(2, tex.size("texture", sd.middle)) or 128
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling
quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff)
else
if other.floor > me.floor then
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor
quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff)
end
local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY"
if other.ceiling < me.ceiling and not sky then
local th = select(2, tex.size("texture", sd.upper)) or 128
local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th
quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff)
end
if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then
local th = select(2, tex.size("texture", sd.middle)) or 128
local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling)
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi
quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff)
end
end
end
end
end
end
-- the scene
local scene = Scene.new()
scene.meta.up = "z"
local mesh: Types.Mesh = { name = name, primitives = {} }
local texIndex: { [string]: number } = {}
for _, key in order do
local b = batches[key]
local n = #b.pos // 3
if n > 0 then
local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
for i = 1, n * 3 do
writef32(pb, (i - 1) * 4, b.pos[i])
writef32(nb, (i - 1) * 4, b.nrm[i])
end
for i = 1, n * 2 do
writef32(ub, (i - 1) * 4, b.uv[i])
end
for i = 0, n - 1 do
writeu32(ib, i * 4, i)
end
local ti = texIndex[key]
if not ti then
table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } })
ti = #scene.textures
texIndex[key] = ti
end
local mat = Scene.material(b.name)
mat.metallic = 0
mat.baseColorTexture = { texture = ti }
mat.extras = { wad = { kind = b.kind } }
table.insert(scene.materials, mat)
table.insert(mesh.primitives, {
attributes = {
POSITION = Scene.accessor(pb, "f32", 3, n),
NORMAL = Scene.accessor(nb, "f32", 3, n),
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n),
},
indices = Scene.accessor(ib, "u32", 1, n),
mode = "triangles" :: any,
material = #scene.materials,
extras = { wad = { kind = b.kind, texture = b.name } },
})
end
end
table.insert(scene.meshes, mesh)
scene.nodes[1] = { name = name, children = {}, mesh = 1 }
scene.roots[1] = 1
-- things, on the floor of the sector under them
for i, th in m.things do
local z = th.z or 0
for sec, ls in secLoops do
local inside = false
for _, loop in ls do
if insideLoop(V, loop, th.x, th.y) then
inside = not inside
end
end
if inside then
z += m.sectors[sec].floor
break
end
end
local a = math.rad(th.angle) / 2
table.insert(scene.nodes, {
name = "thing " .. i,
children = {},
translation = { th.x, th.y, z },
rotation = { 0, 0, math.sin(a), math.cos(a) },
extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } },
})
table.insert(scene.nodes[1].children, #scene.nodes)
end
return scene
end
return Map
+109
View File
@@ -0,0 +1,109 @@
--!strict
--!native
-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column
-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of
-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative)
-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip).
-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's
-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end.
local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32
local Picture = {}
-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it)
function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number)
if n < 8 then
return nil, 0, 0, 0
end
local w, h = readu16(b, at), readu16(b, at + 2)
if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then
return nil, 0, 0, 0
end
for x = 0, w - 1 do
local o = readu32(b, at + 8 + x * 4)
if o < 8 + w * 4 or o >= n then
return nil, 0, 0, 0
end
end
return w, h, readi16(b, at + 4), readi16(b, at + 6)
end
-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed)
function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?)
local stop = at + n
for x = 0, w - 1 do
local p = at + readu32(b, at + 8 + x * 4)
local top = -1
while true do
if p >= stop then
return false, "column " .. x .. " runs past the end"
end
local delta = readu8(b, p)
if delta == 255 then
break
end
if p + 3 > stop then
return false, "post header past the end"
end
local len = readu8(b, p + 1)
top = if delta <= top then top + delta else delta
if p + 4 + len > stop then
return false, "post past the end"
end
local src = p + 3
for k = 0, len - 1 do
local y = top + k
if y < h then
writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4))
end
end
p += 4 + len
end
end
return true, nil
end
-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits)
function Picture.flatSize(n: number): (number?, number)
if n == 4096 then
return 64, 64
elseif n == 4160 then
return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding
elseif n == 8192 then
return 64, 128
elseif n == 12800 then
return 64, 200 -- Heretic / Hexen scrolling flats
end
local s = math.floor(math.sqrt(n) + 0.5)
if s * s == n and s > 0 then
return s, s
end
if n > 0 and n % 64 == 0 then
return 64, n // 64
end
return nil, 0
end
-- flat(b, at, w, h, pal, out): raw indexes, row by row
function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer)
for i = 0, w * h - 1 do
writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4))
end
end
-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy),
-- clipped (composite wall textures from patches)
function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number)
local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1
for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do
local so, d = y * sw, (y + oy) * dw + ox
for x = x0, x1 do
local v = readu32(src, (so + x) * 4)
if v ~= 0 then
writeu32(dst, (d + x) * 4, v)
end
end
end
end
return Picture
+474
View File
@@ -0,0 +1,474 @@
--!strict
-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the
-- standard Archive and written from any Archive value, plus the lumps as game data:
-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map
-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer
-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image
-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0)
-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES)
-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts)
-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene
-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map)
-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps
-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again
-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom
-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken.
-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant,
-- big-endian (Jaguar) WADs, compressed Jaguar lumps.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Archive = require("@formats/containers/Archive")
local Pixels = require("@formats/codecs/image/Pixels")
local Picture = require("@formats/archive/wad/Picture")
local Map = require("@formats/archive/wad/Map")
-- ------------------------------------------------------------------------------------------------ contract
local Wad = {
name = "wad",
category = "archive",
extensions = { "wad" },
mime = { "application/x-doom" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD"
export type Lump = {
name: string, -- the lump name as stored (upper case)
entry: string, -- the Archive entry name
index: number, -- 1-based position in the directory
offset: number,
size: number,
namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers)
map: string?, -- the map this lump belongs to
marker: boolean?, -- a zero-size marker (F_START, MAP01, ...)
}
export type MapOptions = {
textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true)
palette: number?, -- PLAYPAL palette index (default 0)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAP_LUMPS: { [string]: boolean } = {
THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true,
SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true,
MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true,
}
-- namespace markers: first letter(s) before _START / _END
local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches",
P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps",
TX = "textures", HI = "hires", A = "acs", V = "voices" }
-- ------------------------------------------------------------------------------------------------ sniff
function Wad.sniff(r: Bytes.Reader): number
if r:remaining() < 12 then
return 0
end
local m = r:peek(4)
if m ~= "IWAD" and m ~= "PWAD" then
return 0
end
return 0.9
end
-- ------------------------------------------------------------------------------------------------ decode
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Wad.encode(archive, opts)
end
local function nameAt(b: buffer, at: number): string
local s = buffer.readstring(b, at, 8)
local z = string.find(s, "\0", 1, true)
return string.upper(if z then string.sub(s, 1, z - 1) else s)
end
function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local kind = r:string(4)
local count, dirOfs = r:i32le(), r:i32le()
if r.err then
return nil, r.err
end
if kind ~= "IWAD" and kind ~= "PWAD" then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local size = r.limit - r.base
if count < 0 or dirOfs < 0 then
return nil, Err.new(Err.CORRUPT, "negative directory field", 4)
end
if count > (opts and opts.maxEntries or 1e6) then
return nil, Err.new(Err.LIMIT, "too many lumps: " .. count)
end
if dirOfs + count * 16 > size then
return nil, Err.new(Err.TRUNCATED, "directory past the end", 8)
end
local a = Archive.new("wad", encode)
local lumps: { Lump } = {}
local seen: { [string]: number } = {}
local b = r.buf
local ns: string? = nil
local map: string? = nil
local udmf = false
for i = 0, count - 1 do
local o = r.base + dirOfs + i * 16
local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4)
local name = nameAt(b, o + 8)
if n < 0 or at < 0 or (n > 0 and at + n > size) then
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16)
end
-- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map
local nextName = if i + 1 < count then nameAt(b, o + 24) else ""
local inMap: string? = nil
if map then
if udmf then
inMap = map
if name == "ENDMAP" then
map = nil
end
elseif MAP_LUMPS[name] then
inMap = map
else
map = nil
end
end
local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP")
if isMapMarker then
map, udmf = name, nextName == "TEXTMAP"
end
-- namespaces
local marker: boolean = false
local pre = string.match(name, "^(%w+)_START$")
local post = string.match(name, "^(%w+)_END$")
if pre and NAMESPACES[pre] then
ns = NAMESPACES[pre]
marker = true
elseif post and NAMESPACES[post] then
ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil
marker = true
end
local entry = if inMap then inMap .. "/" .. name else name
local k = seen[entry]
if k then
k += 1
seen[entry] = k
entry = entry .. "~" .. k
else
seen[entry] = 1
end
local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil }
table.insert(lumps, lump)
Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) })
end
a.meta.source = { format = "wad", type = kind, lumps = count }
a.meta.wad = { lumps = lumps, buf = b, base = r.base }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items, err = Archive.collect(archive)
if not items then
return nil, err
end
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD"
if kind ~= "IWAD" and kind ~= "PWAD" then
return nil, Err.new(Err.ARG, "type must be IWAD or PWAD")
end
local list: { { name: string, data: buffer } } = {}
for _, it in items do
if not it.entry.dir then
local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name
base = string.upper((string.gsub(base, "~%d+$", "")))
if #base > 8 or #base == 0 then
return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name)
end
table.insert(list, { name = base, data = it.data })
end
end
local w = Bytes.writer()
w:string(kind)
w:u32le(#list)
w:u32le(0)
local offs: { number } = {}
for i, l in list do
offs[i] = w:tell()
w:bytes(l.data)
end
local dirOfs = w:tell()
for i, l in list do
w:u32le(offs[i])
w:u32le(buffer.len(l.data))
w:string(l.name)
w:fill(0, 8 - #l.name)
end
w:setU32le(8, dirOfs)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function info(a: any): any
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil
end
-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given
local function find(w: any, name: string, ns: string?): Lump?
local up = string.upper(name)
local best: Lump? = nil
for _, l in w.lumps do
if l.name == up and not l.map then
if ns == nil or l.namespace == ns then
best = l
elseif not best then
best = l
end
end
end
if best and ns and best.namespace ~= ns then
for _, l in w.lumps do
if l.name == up and l.namespace == ns then
best = l
end
end
end
return best
end
-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write()
function Wad.new(kind: ("IWAD" | "PWAD")?): any
local a = Archive.new("wad", encode)
a.meta.source = { format = "wad", type = kind or "PWAD" }
return a
end
-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD)
function Wad.lumps(a: any): { Lump }?
local w = info(a)
return w and w.lumps
end
-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err
function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
end
local l = find(w, "PLAYPAL")
local i = index or 0
if not l or l.size < (i + 1) * 768 then
return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i)
end
return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil
end
-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic)
-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding.
function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
end
local kind = opts and opts.kind
local l = find(w, name, if kind == "flat" then "flats" else nil)
if not l then
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
end
local pal, perr = Wad.palette(a, opts and opts.palette)
if not pal then
return nil, perr
end
local at = w.base + l.offset
local pw, ph, left, top = Picture.header(w.buf, at, l.size)
local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw))
if asFlat then
local fw, fh = Picture.flatSize(l.size)
if not fw then
return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat")
end
local img = Types.Image.new(fw, fh)
Picture.flat(w.buf, at, fw, fh, pal, img.pixels)
img.meta.source = { format = "wad", kind = "flat", lump = l.name }
return img, nil
end
if not pw then
return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture")
end
local img = Types.Image.new(pw, ph)
local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph)
if not ok then
return nil, Err.from(msg, l.offset)
end
img.meta.offset = { left, top }
img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top }
return img, nil
end
-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } }
local function textureDefs(w: any): { [string]: any }
if w.textures then
return w.textures
end
local defs: { [string]: any } = {}
w.textures = defs
local pn = find(w, "PNAMES")
local names: { string } = {}
if pn and pn.size >= 4 then
local at = w.base + pn.offset
local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8)
for i = 0, n - 1 do
names[i + 1] = nameAt(w.buf, at + 4 + i * 8)
end
end
for _, tl in { "TEXTURE1", "TEXTURE2" } do
local l = find(w, tl)
if l and l.size >= 4 then
local r = Bytes.reader(w.buf, w.base + l.offset, l.size)
local n = r:i32le()
if n > 0 and n * 4 <= l.size - 4 then
for i = 0, n - 1 do
r:seek(4 + i * 4)
local o = r:i32le()
if o > 0 and o + 22 <= l.size then
r:seek(o)
local tname = string.upper(r:fixed(8))
r:skip(4)
local tw, th = r:i16le(), r:i16le()
r:skip(4)
local pc = r:i16le()
local patches = {}
for _ = 1, math.max(0, pc) do
local px, py, pi = r:i16le(), r:i16le(), r:i16le()
r:skip(4)
if names[pi + 1] then
table.insert(patches, { x = px, y = py, patch = names[pi + 1] })
end
end
if not r.err and tw > 0 and th > 0 and defs[tname] == nil then
defs[tname] = { width = tw, height = th, patches = patches }
end
r.err = nil
end
end
end
end
end
return defs
end
-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette)
function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
end
local def = textureDefs(w)[string.upper(name)]
if not def then
return nil, Err.new(Err.ARG, "no texture named " .. tostring(name))
end
if def.width * def.height > 4096 * 4096 then
return nil, Err.new(Err.LIMIT, "texture too big")
end
local img = Types.Image.new(def.width, def.height)
for _, p in def.patches do
local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" })
if pimg then
Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y)
end
end
img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches }
return img, nil
end
-- maps(a) -> { map names } in file order
function Wad.maps(a: any): { string }
local w = info(a)
local out: { string } = {}
if w then
local seen: { [string]: boolean } = {}
for _, l in w.lumps do
if l.map and not seen[l.map] then
seen[l.map] = true
table.insert(out, l.map)
end
end
end
return out
end
-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references)
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
end
local up = string.upper(name)
local lumps: { [string]: Map.Lump } = {}
for _, l in w.lumps do
if l.map == up and lumps[l.name] == nil then
lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size }
end
end
if not next(lumps) then
return nil, Err.new(Err.ARG, "no map named " .. tostring(name))
end
if lumps.TEXTMAP then
return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps")
end
local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
if not m then
return nil, Err.from(msg)
end
return m, nil
end
-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and
-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes
-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
local m, err = Wad.mapData(a, name)
if not m then
return nil, err
end
local w = info(a)
local defs = textureDefs(w)
local images = not (opts and opts.textures == false)
local cache: { [string]: any } = {}
local pal = opts and opts.palette
local function image(kind: string, tname: string): Types.Image?
local key = kind .. ":" .. tname
local c = cache[key]
if c == nil then
local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal })
c = img or false
cache[key] = c
end
return if c then c else nil
end
local tex: Map.Textures = {
size = function(kind: string, tname: string): (number?, number?)
if kind == "texture" then
local d = defs[tname]
if d then
return d.width, d.height
end
return nil, nil
end
local l = find(w, tname, "flats")
if l then
local fw, fh = Picture.flatSize(l.size)
return fw, fh
end
return nil, nil
end,
image = if images then image else nil,
}
local scene = Map.scene(m, tex, string.upper(name))
scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
return scene, nil
end
return Wad
+248
View File
@@ -0,0 +1,248 @@
--!strict
-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the
-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the
-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so
-- every input terminates). New in formats-luau, after the classic "ear clipping with hole bridging" method
-- (D. Eberly, Triangulation by Ear Clipping); no code taken.
--
-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } })
-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair
-- -- (1-based), counter-clockwise
--
-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored.
local Polygon = {}
type Pt = { x: number, y: number, loop: number, index: number }
local function area(pts: { Pt }): number
local a = 0
local n = #pts
for i = 1, n do
local p, q = pts[i], pts[i % n + 1]
a += p.x * q.y - q.x * p.y
end
return a / 2
end
local function inside(pts: { Pt }, x: number, y: number): boolean
local c = false
local n = #pts
local j = n
for i = 1, n do
local a, b = pts[i], pts[j]
if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then
c = not c
end
j = i
end
return c
end
local function cross(o: Pt, a: Pt, b: Pt): number
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
end
-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count)
local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean
if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then
return false
end
local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2)
local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2)
return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0))
end
local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean
for _, r in rings do
local n = #r
for i = 1, n do
if crosses(m, v, r[i], r[i % n + 1]) then
return false
end
end
end
return true
end
-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible
-- vertices; others = every ring the bridge must not cross
local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt }
local mi = 1
for i, p in h do
if p.x > h[mi].x then
mi = i
end
end
local m = h[mi]
local best, bestD = 0, math.huge
for pass = 1, 2 do
for i, v in outer do
if pass == 2 or v.x >= m.x then
local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2
if d < bestD and visible(m, v, others) then
best, bestD = i, d
end
end
end
if best > 0 then
break
end
end
if best == 0 then
best = 1
end
local out: { Pt } = {}
for i = 1, best do
table.insert(out, outer[i])
end
local n = #h
for k = 0, n do
table.insert(out, h[(mi - 1 + k) % n + 1])
end
for i = best, #outer do
table.insert(out, outer[i])
end
return out
end
local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
end
-- ear clipping of one counter-clockwise ring
local function clip(ring: { Pt }, out: { number })
local pts = table.clone(ring)
local guard = #pts * #pts + 16
while #pts > 3 and guard > 0 do
guard -= 1
local n = #pts
local found, bestI, bestScore = 0, 1, -math.huge
for i = 1, n do
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
local cr = cross(a, b, c)
if cr > 0 then
local ok = true
for k = 1, n do
local p = pts[k]
if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then
ok = false
break
end
end
if ok then
found = i
break
end
end
if cr > bestScore then
bestI, bestScore = i, cr
end
end
local i = if found > 0 then found else bestI
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
if cross(a, b, c) ~= 0 then
table.insert(out, a.loop)
table.insert(out, a.index)
table.insert(out, b.loop)
table.insert(out, b.index)
table.insert(out, c.loop)
table.insert(out, c.index)
end
table.remove(pts, i)
end
if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then
for k = 1, 3 do
table.insert(out, pts[k].loop)
table.insert(out, pts[k].index)
end
end
end
-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly)
function Polygon.triangulate(loops: { { number } }): { number }
local rings: { { Pt } } = {}
local areas: { number } = {}
for li, l in loops do
local pts: { Pt } = {}
for k = 1, #l - 1, 2 do
local x, y = l[k], l[k + 1]
if type(x) == "number" and type(y) == "number" and x == x and y == y then
table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 })
end
end
local a = if #pts >= 3 then area(pts) else 0
if a ~= 0 then
table.insert(rings, pts)
table.insert(areas, math.abs(a))
if a < 0 then -- counter-clockwise for now; holes are flipped below
local r: { Pt } = {}
for k = #pts, 1, -1 do
table.insert(r, pts[k])
end
rings[#rings] = r
end
end
end
-- nesting: the parent of a ring is the smallest ring containing its first point
local n = #rings
local depth, parent = table.create(n, 0), table.create(n, 0)
for i = 1, n do
local p = rings[i][1]
for j = 1, n do
if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then
depth[i] += 1
if parent[i] == 0 or areas[j] < areas[parent[i]] then
parent[i] = j
end
end
end
end
local holes: { [number]: { number } } = {}
for i = 1, n do
if depth[i] % 2 == 1 and parent[i] > 0 then
local list = holes[parent[i]] or {}
holes[parent[i]] = list
table.insert(list, i)
end
end
local out: { number } = {}
for i = 1, n do
if depth[i] % 2 == 0 then
local ring = rings[i]
local hs = holes[i]
if hs then
table.sort(hs, function(a: number, b: number): boolean
local ma, mb = -math.huge, -math.huge
for _, p in rings[a] do
ma = math.max(ma, p.x)
end
for _, p in rings[b] do
mb = math.max(mb, p.x)
end
return ma > mb
end)
local flipped: { { Pt } } = {}
for _, h in hs do
local r: { Pt } = {}
local src = rings[h]
for k = #src, 1, -1 do
table.insert(r, src[k])
end
table.insert(flipped, r)
end
for k, h in flipped do
local others: { { Pt } } = { ring }
for k2 = k + 1, #flipped do
table.insert(others, flipped[k2])
end
ring = bridge(ring, h, others)
end
end
clip(ring, out)
end
end
return out
end
return Polygon
+247
View File
@@ -0,0 +1,247 @@
-- archive/wad tests: a cut-down Freedoom IWAD (tools/fixtures/wad.py) lists its lumps (names, sizes, data CRCs,
-- namespaces, map lumps as "MAP01/THINGS"); every flat, patch, sprite and graphic decodes to the pixels DeuTex
-- extracts (RGBA CRC, offsets); composed wall textures; MAP01 parses to the counts of an independent parse and its
-- Scene's floor area matches Green's theorem over the sectors' sides; a hand-made room with a pillar (exact areas,
-- walls, things on floors), a UDMF stub, duplicate names, a tall patch; the writer round-trips byte for byte;
-- errors; the fuzz pass. Fixtures: tools/fixtures/wad.py.
local T = require("@tests/T")
local F = require("@formats")
local Wad = require("@formats/archive/wad")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/wad")
local t = T.suite("wad")
t:eq(Wad.name, "wad", "name")
local fd = Fx.freedoom
local a, err = Wad.decode(Bytes.reader(buffer.fromstring(fd.data)))
t:check(a, "freedoom: " .. tostring(err))
t:eq(F.detect(fd.data), "wad", "F.detect")
t:eq(a.meta.source.type, "IWAD", "IWAD")
-- 1. lumps
do
local lumps = Wad.lumps(a) :: { Wad.Lump }
t:eq(#lumps, #fd.lumps, "lump count")
local list = a:list()
for i, w in fd.lumps do
t:eq(lumps[i].name, w.name, "lump " .. i)
t:eq(lumps[i].size, w.size, "size " .. w.name)
t:eq(Crc32.of((a:read(list[i].name))), w.crc, "data " .. w.name)
end
t:eq(list[2].name, "MAP01/THINGS", "map lumps are named after their map")
t:eq(lumps[2].map, "MAP01", "map membership")
t:check(lumps[1].marker, "map marker")
local byName = {}
for _, l in lumps do
byName[l.name] = l
end
t:eq(byName.BLOOD1.namespace, "flats", "flats namespace")
t:eq(byName.BOS2A1.namespace, "sprites", "sprites namespace")
t:eq(byName.AG128_1.namespace, "patches", "patches namespace")
t:eq(byName.PLAYPAL.namespace, nil, "no namespace")
t:eq(#Wad.maps(a), 1, "one map")
end
-- 2. images against DeuTex
do
local n = 0
for _, w in fd.images do
local img, e = Wad.image(a, w.name)
t:check(img, w.name .. ": " .. tostring(e))
t:eq(img.width, w.width, w.name .. ": width")
t:eq(img.height, w.height, w.name .. ": height")
if w.kind == "flats" then
t:eq(Crc32.of(img.pixels), w.crc, w.name .. ": flat pixels against DeuTex")
else
t:eq(Crc32.of(img.pixels), w.crc, w.name .. ": picture pixels against DeuTex")
if w.left then
t:eq(img.meta.offset[1], w.left, w.name .. ": left offset")
t:eq(img.meta.offset[2], w.top, w.name .. ": top offset")
end
end
n += 1
end
t:note("%d graphics match DeuTex", n)
for _, tx in fd.textures do
local img, e = Wad.texture(a, tx.name)
t:check(img, tx.name .. ": " .. tostring(e))
t:check(img.width == tx.width and img.height == tx.height, tx.name .. ": texture size")
t:eq(img.meta.source.patches, #tx.patches, tx.name .. ": patch count")
end
end
-- 3. MAP01
do
local m = Wad.mapData(a, "MAP01") :: any
local r = fd.map
t:eq(#m.things, r.things, "things")
t:eq(#m.linedefs, r.linedefs, "linedefs")
t:eq(#m.sidedefs, r.sidedefs, "sidedefs")
t:eq(#m.vertices // 2, r.vertices, "vertices")
t:eq(#m.sectors, r.sectors, "sectors")
for i, th in r.thingList do
local g = m.things[i]
t:check(g.x == th.x and g.y == th.y and g.type == th.type and g.angle == th.angle, "thing " .. i)
end
local t0 = T.clock()
local s, e = Wad.map(a, "MAP01")
t:check(s, "map scene: " .. tostring(e))
local floor, nprim = 0, 0
for _, p in s.meshes[1].primitives do
nprim += 1
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
for k = 0, p.attributes.POSITION.count - 1, 3 do
if nrm(k, 2) > 0.5 then
local ax, ay, bx, by, cx, cy = pos(k, 0), pos(k, 1), pos(k + 1, 0), pos(k + 1, 1), pos(k + 2, 0), pos(k + 2, 1)
floor += ((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) / 2
end
end
end
t:check(math.abs(floor - r.floorArea) <= r.floorArea * 0.01, string.format("floor area %.0f vs %.0f", floor, r.floorArea))
t:check(#s.nodes == 1 + r.things, "a node per thing")
t:eq(s.meta.up, "z", "z up")
local withImage = 0
for _, tex in s.textures do
if tex.image then
withImage += 1
end
end
t:note("MAP01: %d primitives, %d textures (%d with images in the cut-down WAD), floor area %.0f of %.0f, %.2f s", nprim, #s.textures, withImage, floor, r.floorArea, T.clock() - t0)
local lean = Wad.map(a, "MAP01", { textures = false }) :: any
t:check(lean.textures[1].image == nil and lean.textures[1].uri ~= nil, "textures = false")
end
-- 4. the hand-made room
do
local rm = Wad.decode(Bytes.reader(buffer.fromstring(Fx.room.data)))
t:check(rm, "room decodes")
local names = {}
for _, e in rm:list() do
table.insert(names, e.name)
end
t:eq(names[2], "E1M1/THINGS", "E1M1 lumps")
t:eq(names[16], "E1M2/TEXTMAP", "UDMF lumps belong to their map")
t:eq(names[17], "E1M2/ENDMAP", "up to ENDMAP")
t:eq(names[18], "DEMO1", "after the map")
t:eq(names[19], "DEMO1~2", "duplicate names get ~n")
local _, ue = Wad.map(rm, "E1M2")
t:check(ue and ue.code == Err.UNSUPPORTED, "UDMF unsupported")
local s = Wad.map(rm, "E1M1") :: any
local area = { floor = 0, ceil = 0, wall = 0 }
for _, p in s.meshes[1].primitives do
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
for k = 0, p.attributes.POSITION.count - 1, 3 do
local ux, uy, uz = pos(k + 1, 0) - pos(k, 0), pos(k + 1, 1) - pos(k, 1), pos(k + 1, 2) - pos(k, 2)
local vx, vy, vz = pos(k + 2, 0) - pos(k, 0), pos(k + 2, 1) - pos(k, 1), pos(k + 2, 2) - pos(k, 2)
local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
local ar = math.sqrt(cx * cx + cy * cy + cz * cz) / 2
-- the winding agrees with the normal
t:check(cx * nrm(k, 0) + cy * nrm(k, 1) + cz * nrm(k, 2) > 0, "winding faces the normal")
if nrm(k, 2) > 0.5 then
area.floor += ar
elseif nrm(k, 2) < -0.5 then
area.ceil += ar
else
area.wall += ar
end
end
end
t:eq(area.floor, 256 * 256, "floors: the room around the pillar + the pillar top")
t:eq(area.ceil, 256 * 256, "ceilings")
t:eq(area.wall, 4 * 256 * 128 + 4 * 64 * 32, "outer walls + the pillar's lower walls")
t:eq(s.nodes[2].translation[3], 0, "thing on the room floor")
t:eq(s.nodes[3].translation[3], 32, "thing on the pillar")
t:eq(s.nodes[2].extras.thing.type, 1, "thing type")
local tall = Wad.image(rm, "TALL") :: any
t:eq(tall.height, 300, "tall patch height")
t:eq(buffer.readu32(tall.pixels, 0), 0, "tall patch: transparent above the first post")
t:eq(buffer.readu32(tall.pixels, 100 * 4), buffer.readu32((Wad.palette(rm) :: buffer), 7 * 4), "tall patch: first post")
t:eq(buffer.readu32(tall.pixels, 249 * 4), buffer.readu32((Wad.palette(rm) :: buffer), 9 * 4), "tall patch: relative topdelta 100 + 50")
t:eq(buffer.readu32(tall.pixels, 260 * 4), 0, "tall patch: transparent below")
local flat = Wad.image(rm, "FLOOR") :: any
t:check(flat.width == 64 and flat.height == 64, "flat 64 x 64")
-- writer: lossless for decoded WADs (map lumps and ~n names stripped back)
t:check(buffer.tostring(F.save(rm) :: buffer) == Fx.room.data, "room: decode + save is byte-identical")
end
-- 5. writer
do
t:check(buffer.tostring(F.save(a) :: buffer) == fd.data, "freedoom: decode + save is byte-identical")
local p = Wad.new()
p:add("dir/demo1", "abc")
p:add("MAP02/THINGS", "")
local back = Wad.decode(Bytes.reader(p:write() :: buffer))
t:eq(Wad.lumps(back)[1].name, "DEMO1", "names upper-cased, paths stripped")
t:eq(back.meta.source.type, "PWAD", "PWAD by default")
local long = Wad.new()
long:add("NINECHARS", "x")
local _, e = long:write()
t:check(e and e.code == Err.ARG, "9-byte lump name")
local zip = F.format("zip").create()
zip:add("x.lmp", "1")
t:eq(Wad.lumps(F.load(F.save(zip, nil, { format = "wad" }) :: buffer))[1].name, "X.LMP", "zip -> wad")
end
-- 6. errors
do
local _, e1 = Wad.decode(Bytes.reader(buffer.fromstring(string.sub(fd.data, 1, 100))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local _, e2 = Wad.image(a, "NOPE")
t:check(e2 and e2.code == Err.ARG, "missing lump")
local _, e3 = Wad.image({}, "X")
t:check(e3 and e3.code == Err.ARG, "not a WAD")
local _, e4 = Wad.map(a, "MAP99")
t:check(e4 and e4.code == Err.ARG, "missing map")
end
-- 7. fuzz: the directory, then the lumps of the room (maps, pictures)
t:fuzz("decode", function(b: buffer)
local w = Wad.decode(Bytes.reader(b))
if w then
for _, l in Wad.lumps(w) :: any do
if not l.map and l.size > 0 then
Wad.image(w, l.name)
end
end
for _, m in Wad.maps(w) do
Wad.map(w, m)
end
Wad.texture(w, "X")
end
return w
end, { Fx.room.data }, { mutations = 300 })
do
-- mutate inside the lumps of the real map and pictures (the directory kept intact)
local rand = T.rng(9)
local threw = 0
for i = 1, 60 do
local b = buffer.fromstring(fd.data)
for _ = 1, 1 + rand(20) do
local at = 12 + rand(#fd.data - 12 - (#fd.lumps * 16))
buffer.writeu8(b, at, rand(256))
end
local ok = pcall(function()
local w = Wad.decode(Bytes.reader(b))
if w then
if i % 6 == 0 then
Wad.map(w, "MAP01")
end
for _, im in fd.images do
Wad.image(w, im.name)
end
end
end)
if not ok then
threw += 1
end
end
t:eq(threw, 0, "mutated lumps never throw")
end
t:done()
+69
View File
@@ -0,0 +1,69 @@
-- codecs/model/Polygon tests: convex / concave / holed / nested polygons triangulate to the exact area in
-- counter-clockwise triangles, either input orientation; degenerate loops; a fuzz of random loops never throws.
local T = require("@tests/T")
local Polygon = require("@formats/codecs/model/Polygon")
local t = T.suite("codecs/polygon")
local function area(loops: { { number } }, tris: { number }): (number, boolean)
local a, ccw = 0, true
for k = 1, #tris, 6 do
local p = {}
for c = 0, 2 do
local l = loops[tris[k + c * 2]]
local i = tris[k + c * 2 + 1]
p[c * 2 + 1], p[c * 2 + 2] = l[i * 2 - 1], l[i * 2]
end
local s = ((p[3] - p[1]) * (p[6] - p[2]) - (p[4] - p[2]) * (p[5] - p[1])) / 2
if s <= 0 then
ccw = false
end
a += s
end
return a, ccw
end
local cases = {
{ "square", { { 0, 0, 10, 0, 10, 10, 0, 10 } }, 100 },
{ "clockwise square", { { 0, 0, 0, 10, 10, 10, 10, 0 } }, 100 },
{ "L shape", { { 0, 0, 20, 0, 20, 10, 10, 10, 10, 20, 0, 20 } }, 300 },
{ "comb", { { 0, 0, 50, 0, 50, 10, 40, 10, 40, 2, 30, 2, 30, 10, 20, 10, 20, 2, 10, 2, 10, 10, 0, 10 } }, 50 * 2 + 3 * 10 * 8 },
{ "square with a hole", { { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 2, 4, 4, 4, 4, 2 } }, 96 },
{ "two holes", { { 0, 0, 30, 0, 30, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 }, { 20, 2, 28, 2, 28, 8, 20, 8 } }, 300 - 4 - 48 },
{ "island in a hole", { { 0, 0, 30, 0, 30, 30, 0, 30 }, { 5, 5, 25, 5, 25, 25, 5, 25 }, { 10, 10, 20, 10, 20, 20, 10, 20 } }, 900 - 400 + 100 },
{ "degenerate loops ignored", { { 0, 0, 1, 1 }, { 0, 0, 5, 5, 10, 10 }, { 0, 0, 4, 0, 4, 4, 0, 4 } }, 16 },
}
for _, c in cases do
local tris = Polygon.triangulate(c[2])
local a, ccw = area(c[2], tris)
t:check(math.abs(a - c[3]) < 1e-9, c[1] .. ": area " .. a .. " want " .. c[3])
t:check(ccw, c[1] .. ": counter-clockwise triangles")
end
-- random star polygons with a random hole: area preserved, never throws
local rand = T.rng(3)
local threw = 0
for i = 1, 200 do
local n = 3 + rand(30)
local outer = {}
for k = 0, n - 1 do
local ang = k / n * math.pi * 2
local r = 50 + rand(50)
table.insert(outer, math.floor(math.cos(ang) * r))
table.insert(outer, math.floor(math.sin(ang) * r))
end
local hole = { -5, -5, 5, -5, 5, 5, -5, 5 }
local ok = pcall(Polygon.triangulate, if i % 2 == 0 then { outer, hole } else { outer })
if not ok then
threw += 1
end
local garbage = {}
for _ = 1, rand(40) do
table.insert(garbage, rand(20) - 10)
end
if not pcall(Polygon.triangulate, { garbage, { 0 / 0, 1, 2 } }) then
threw += 1
end
end
t:eq(threw, 0, "random and garbage loops never throw")
t:done()
+190
View File
@@ -0,0 +1,190 @@
# Doom WAD fixtures (tools/fixtures.py). Freedoom (BSD licence, licenses/freedoom-COPYING.txt; the nix freedoom
# package, never committed) is cut down to a small IWAD here: MAP01's lumps, PLAYPAL, COLORMAP, PNAMES, TEXTURE1,
# TITLEPIC, and the first sprites / patches / flats of each namespace (the WAD writer below keeps Freedoom's layout:
# lumps in order, the directory at the end). References:
# - DeuTex (nix deutex) extracts every graphic of the cut-down WAD as PNG; Pillow turns them into RGBA (DeuTex's
# transparent index -> 0, 0, 0, 0; flats compared as RGB, all opaque) -> CRC-32 per lump;
# - an independent Python parse of the map lumps: counts, the things, and each sector's floor area by Green's
# theorem over its directed sides (no outline chaining), for the triangulation;
# - a hand-made PWAD: a square room with a square pillar sector inside (exact areas and walls), a UDMF map stub,
# tall-patch and namespace cases.
# tests/gen/wad.luau { freedoom = { data, lumps = { { name, entry, size, crc, namespace? } }, images = { { name,
# kind, width, height, left, top, crc } }, map = { name, things, linedefs, sidedefs,
# vertices, sectors, floorArea, thingList = { { x, y, type, angle } } }, textures = { ... } },
# room = { data, ... } }
import glob, os, shutil, struct, subprocess, tempfile, zlib
FREEDOOM = "share/games/doom/freedoom2.wad"
TO_RGBA = r"""
import json, sys, zlib
from PIL import Image
out = {}
for path in json.loads(sys.stdin.read()):
im = Image.open(path)
t = im.info.get("transparency")
idx = im.load()
rgba = im.convert("RGBA")
px = bytearray(rgba.tobytes())
if t is not None and "/flats/" not in path:
w, h = im.size
for y in range(h):
for x in range(w):
if idx[x, y] == t:
o = (y * w + x) * 4
px[o:o + 4] = b"\0\0\0\0"
else:
for o in range(3, len(px), 4):
px[o] = 255
out[path] = {"w": im.size[0], "h": im.size[1], "crc": zlib.crc32(bytes(px))}
print(json.dumps(out))
"""
def lumps_of(data):
n, ofs = struct.unpack_from("<ii", data, 4)
out = []
for i in range(n):
p, s, nm = struct.unpack_from("<ii8s", data, ofs + 16 * i)
out.append((nm.split(b"\0")[0].decode("latin1").upper(), data[p:p + s]))
return out
def write(kind, lumps):
out = bytearray(kind + b"\0" * 8)
dirs = []
for nm, b in lumps:
dirs.append((len(out), len(b), nm))
out += b
o = len(out)
for p, s, nm in dirs:
out += struct.pack("<ii8s", p, s, nm.encode())
struct.pack_into("<ii", out, 4, len(lumps), o)
return bytes(out)
def cut(full):
lumps = lumps_of(full)
names = [l[0] for l in lumps]
sel = list(lumps[0:11])
for m in ["PLAYPAL", "COLORMAP", "PNAMES", "TEXTURE1", "TITLEPIC"]:
sel.append(lumps[names.index(m)])
# the patches TEXTURE1's first textures use, so composed textures can be checked
def rng(a, b, k, want=()):
i, j = names.index(a), names.index(b)
inner = [l for l in lumps[i + 1:j] if l[1]]
pick = inner[:k] + [l for l in inner[k:] if l[0] in want]
return [lumps[i]] + pick + [lumps[j]]
return sel, rng
def map_ref(lumps):
d = dict(lumps[1:11])
verts = [struct.unpack_from("<hh", d["VERTEXES"], i) for i in range(0, len(d["VERTEXES"]), 4)]
sides = [struct.unpack_from("<hh8s8s8sH", d["SIDEDEFS"], i) for i in range(0, len(d["SIDEDEFS"]), 30)]
secs = [struct.unpack_from("<hh8s8sHHH", d["SECTORS"], i) for i in range(0, len(d["SECTORS"]), 26)]
lines = [struct.unpack_from("<HHHHHHH", d["LINEDEFS"], i) for i in range(0, len(d["LINEDEFS"]), 14)]
things = [struct.unpack_from("<hhHHH", d["THINGS"], i) for i in range(0, len(d["THINGS"]), 10)]
area = [0.0] * len(secs)
for v1, v2, flags, special, tag, fr, bk in lines:
fs = sides[fr][5] if fr != 0xFFFF else None
bs = sides[bk][5] if bk != 0xFFFF else None
if fs == bs:
continue
(ax, ay), (bx, by) = verts[v1], verts[v2]
c = ax * by - bx * ay
if fs is not None:
area[fs] -= c / 2
if bs is not None:
area[bs] += c / 2
return {"things": len(things), "linedefs": len(lines), "sidedefs": len(sides), "vertices": len(verts),
"sectors": len(secs), "floorArea": sum(area), "sectorAreas": area,
"thingList": [{"x": t[0], "y": t[1], "angle": t[2], "type": t[3]} for t in things[:20]]}
def room():
# a 256 x 256 room (sector 0) with a 64 x 64 pillar sector (1) in the middle, floor 0 / ceiling 128, pillar floor 32
v = [(0, 0), (256, 0), (256, 256), (0, 256), (96, 96), (160, 96), (160, 160), (96, 160)]
verts = b"".join(struct.pack("<hh", *p) for p in v)
sides = b""
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"-", b"WALL", 0) for _ in range(4)) # 0..3 room walls
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"STEP", b"-", 0) for _ in range(4)) # 4..7 room side of pillar
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"-", b"-", 1) for _ in range(4)) # 8..11 pillar side
# outer walls: room on the right of v1 -> v2 (clockwise); pillar lines: front = room (outside), back = pillar
lines = b""
for i, (a, b) in enumerate([(0, 3), (3, 2), (2, 1), (1, 0)]):
lines += struct.pack("<HHHHHHH", a, b, 1, 0, 0, i, 0xFFFF)
for i, (a, b) in enumerate([(4, 5), (5, 6), (6, 7), (7, 4)]):
lines += struct.pack("<HHHHHHH", a, b, 4, 0, 0, 4 + i, 8 + i)
secs = struct.pack("<hh8s8sHHH", 0, 128, b"FLOOR", b"CEIL", 160, 0, 0) + struct.pack("<hh8s8sHHH", 32, 128, b"FLOOR", b"CEIL", 160, 0, 0)
things = struct.pack("<hhHHH", 32, 32, 90, 1, 7) + struct.pack("<hhHHH", 128, 128, 0, 2014, 7)
flat = bytes((x ^ y) & 255 for y in range(64) for x in range(64))
pal = bytes(c for i in range(256) for c in (i, 255 - i, (i * 3) & 255)) * 14
# a tall patch (DeePsea): 1 x 300, a post at 100 (50 rows), then topdelta 50 <= 100: relative, rows 150..249
col = bytes([100, 50, 0]) + bytes([7] * 50) + b"\0" + bytes([50, 100, 0]) + bytes([9] * 100) + b"\0" + b"\xff"
tall = struct.pack("<HHhhI", 1, 300, 0, 0, 12) + col
lumps = [("E1M1", b""), ("THINGS", things), ("LINEDEFS", lines), ("SIDEDEFS", sides), ("VERTEXES", verts),
("SECTORS", secs), ("PLAYPAL", pal), ("F_START", b""), ("FLOOR", flat), ("CEIL", flat), ("F_END", b""),
("P_START", b""), ("TALL", tall), ("P_END", b""), ("E1M2", b""), ("TEXTMAP", b'namespace = "zdoom";'),
("ENDMAP", b""), ("DEMO1", b"x"), ("DEMO1", b"yy")]
return write(b"PWAD", lumps), lumps
def generate(ctx):
root = ctx.nix("freedoom", ["sh", "-c", "dirname $(dirname $(readlink -f $(command -v freedoom2)))"]).decode().strip()
full = open(os.path.join(root, FREEDOOM), "rb").read()
sel, rng = cut(full)
tex1 = dict(lumps_of(full))["TEXTURE1"]
pn = dict(lumps_of(full))["PNAMES"]
pnames = [pn[4 + 8 * i:12 + 8 * i].split(b"\0")[0].decode("latin1").upper() for i in range(struct.unpack_from("<i", pn)[0])]
# the first three textures and their patches
n = struct.unpack_from("<i", tex1)[0]
textures, want = [], set()
for i in range(3):
o = struct.unpack_from("<i", tex1, 4 + 4 * i)[0]
name = tex1[o:o + 8].split(b"\0")[0].decode("latin1").upper()
w, h = struct.unpack_from("<hh", tex1, o + 12)
pc = struct.unpack_from("<h", tex1, o + 20)[0]
pats = []
for k in range(pc):
x, y, p = struct.unpack_from("<hhh", tex1, o + 22 + 10 * k)
pats.append(pnames[p])
want.add(pnames[p])
textures.append({"name": name, "width": w, "height": h, "patches": pats})
sel += rng("S_START", "S_END", 6) + rng("P_START", "P_END", 6, want) + rng("F_START", "F_END", 6)
data = write(b"IWAD", sel)
tmp = tempfile.mkdtemp(prefix="formats-wad-")
try:
open(os.path.join(tmp, "doom2.wad"), "wb").write(data)
os.makedirs(os.path.join(tmp, "x"))
ctx.nix("deutex", ["deutex", "-doom2", tmp, "-dir", os.path.join(tmp, "x"), "-xtract"])
pngs = sorted(glob.glob(os.path.join(tmp, "x", "*", "*.png")))
import json
ref = json.loads(ctx.python(["pillow"], TO_RGBA, input=json.dumps(pngs).encode()))
offsets = {}
info = open(os.path.join(tmp, "x", "wadinfo.txt")).read().split("\n")
for line in info:
parts = line.split()
if len(parts) == 3 and parts[1].lstrip("-").isdigit():
offsets[parts[0].upper()] = (int(parts[1]), int(parts[2]))
images = []
for p in pngs:
name = os.path.basename(p)[:-4].upper()
kind = os.path.basename(os.path.dirname(p))
e = {"name": name, "kind": kind, "width": ref[p]["w"], "height": ref[p]["h"], "crc": ref[p]["crc"]}
if name in offsets and kind != "flats":
e["left"], e["top"] = offsets[name]
images.append(e)
finally:
shutil.rmtree(tmp)
lumps = []
seen = {}
for nm, b in sel:
lumps.append({"name": nm, "size": len(b), "crc": zlib.crc32(b)})
mp = map_ref(sel)
mp["name"] = "MAP01"
rdata, rlumps = room()
ctx.emit("wad", {
"freedoom": {"data": data, "lumps": lumps, "images": images, "map": mp, "textures": textures},
"room": {"data": rdata, "lumps": [{"name": n, "size": len(b)} for n, b in rlumps]},
})