model/buildmap: Build engine .map v7-9 (sectors, walls, sprites as raw tables; Scene with sloped floors / ceilings, upper / lower / masked walls, sprites as nodes; v9 room-over-room fields), read + write; tested against an independent Python reader and Ken Silverman's map2stl
This commit is contained in:
1 parent
75984be212
commit
aacc78fac2
7 files changed
+1112
-1
No files matched your search
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
|
||||
## Formats
|
||||
|
||||
<!-- formats:begin -->
|
||||
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
adds each format's capabilities.
|
||||
|
||||
| Category | Format | Extensions | Read | Write |
|
||||
@@ -111,6 +111,7 @@ adds each format's capabilities.
|
||||
| 3D models | 3mf | .3mf | yes | yes |
|
||||
| 3D models | b3d | .b3d | yes | - |
|
||||
| 3D models | bsp | .bsp | yes | - |
|
||||
| 3D models | buildmap | .map | yes | yes |
|
||||
| 3D models | dae | .dae .zae | yes | yes |
|
||||
| 3D models | fbx | .fbx | yes | yes |
|
||||
| 3D models | gltf | .gltf .glb | yes | yes |
|
||||
|
||||
@@ -67,6 +67,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
|
||||
| model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` |
|
||||
| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` |
|
||||
| model | buildmap | .map | yes | yes | sprites: true, slopes: true | `tests/model/buildmap.luau` |
|
||||
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` |
|
||||
|
||||
@@ -758,6 +758,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/bsp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "buildmap",
|
||||
category = "model",
|
||||
path = "model/buildmap",
|
||||
extensions = { "map" },
|
||||
mime = { "application/x-build-map" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, sprites = true, slopes = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/buildmap")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dae",
|
||||
category = "model",
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
--!strict
|
||||
-- model/buildmap/Geometry: Build map tables to a Scene. Slopes after BUILDINF.TXT (heinum: z rises heinum / 4096 per
|
||||
-- unit across the first wall, z units 16 to an xy unit); walls split at red walls into upper / lower parts and clipped
|
||||
-- where they cross, as Ken Silverman's map2stl does; texture coordinates approximate the engine's (xrepeat * 8 pixels
|
||||
-- across a wall, 128 z units per pixel at yrepeat 8, 16 units per floor pixel). New code.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Polygon = require("@rosetta/codecs/model/Polygon")
|
||||
|
||||
local Geometry = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
|
||||
export type Sector = { [string]: number }
|
||||
export type Wall = { [string]: number }
|
||||
export type Map = {
|
||||
version: number,
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
ang: number, -- 2048 = a full turn, 0 = +x, 512 = +y
|
||||
cursectnum: number,
|
||||
sectors: { Sector }, -- raw fields, indices 0-based as in the file
|
||||
walls: { Wall },
|
||||
sprites: { { [string]: number } },
|
||||
trailing: buffer?, -- bytes after the sprites (kept for the writer)
|
||||
}
|
||||
export type Options = {
|
||||
scale: number?, -- world units per Build xy unit, default 1 (z is divided by 16 first)
|
||||
tiles: { [number]: any }?, -- tile number -> Image or { width, height }: texture sizes for the UVs, images attached
|
||||
skyWalls: boolean?, -- keep upper / lower walls between two parallaxed ceilings / floors; default false
|
||||
}
|
||||
|
||||
local PARALLAX, SLOPED, SWAP_XY, SMOOSH, FLIP_X, FLIP_Y, RELATIVE = 1, 2, 4, 8, 16, 32, 64
|
||||
local W_BOTTOM_SWAP, W_ALIGN_BOTTOM, W_FLIP_X, W_MASKED, W_FLIP_Y = 2, 4, 8, 16, 256
|
||||
local YAX_BIT = 1024
|
||||
local band = bit32.band
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ queries
|
||||
function Geometry.slopeZ(map: Map, sector: number, floor: boolean, x: number, y: number): number
|
||||
local s = map.sectors[sector + 1]
|
||||
if not s then
|
||||
return 0
|
||||
end
|
||||
local z = if floor then s.floorz else s.ceilingz
|
||||
local stat = if floor then s.floorstat else s.ceilingstat
|
||||
local heinum = if floor then s.floorheinum else s.ceilingheinum
|
||||
if band(stat, SLOPED) == 0 or heinum == 0 then
|
||||
return z
|
||||
end
|
||||
local w0 = map.walls[s.wallptr + 1]
|
||||
local w1 = w0 and map.walls[w0.point2 + 1]
|
||||
if not w1 then
|
||||
return z
|
||||
end
|
||||
local dx, dy = w1.x - w0.x, w1.y - w0.y
|
||||
local len = math.sqrt(dx * dx + dy * dy)
|
||||
if len == 0 then
|
||||
return z
|
||||
end
|
||||
return z + heinum * (dx * (y - w0.y) - dy * (x - w0.x)) / (len * 256)
|
||||
end
|
||||
|
||||
-- the sector's wall loops (0-based wall indices, following point2); loops that leave the sector or do not close are dropped
|
||||
function Geometry.loops(map: Map, sector: number): { { number } }
|
||||
local s = map.sectors[sector + 1]
|
||||
local out: { { number } } = {}
|
||||
if not s then
|
||||
return out
|
||||
end
|
||||
local first, last = s.wallptr, s.wallptr + s.wallnum - 1
|
||||
local seen: { [number]: boolean } = {}
|
||||
for start = first, last do
|
||||
if not seen[start] then
|
||||
local loop: { number } = {}
|
||||
local w = start
|
||||
local ok = false
|
||||
for _ = 0, s.wallnum do
|
||||
if w < first or w > last or seen[w] then
|
||||
break
|
||||
end
|
||||
local wall = map.walls[w + 1]
|
||||
if not wall then
|
||||
break
|
||||
end
|
||||
seen[w] = true
|
||||
table.insert(loop, w)
|
||||
w = wall.point2
|
||||
if w == start then
|
||||
ok = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok and #loop >= 3 then
|
||||
table.insert(out, loop)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- v9 room over room (eduke32 YAX): bunch numbers in the x panning of a ceiling / floor flagged 1024; walls flagged
|
||||
-- 1024 / 2048 keep the linked wall in lotag (ceiling) / extra (floor)
|
||||
function Geometry.yax(map: Map)
|
||||
for _, s in map.sectors do
|
||||
if band(s.ceilingstat, YAX_BIT) ~= 0 then
|
||||
s.ceilingbunch = s.ceilingxpanning
|
||||
end
|
||||
if band(s.floorstat, YAX_BIT) ~= 0 then
|
||||
s.floorbunch = s.floorxpanning
|
||||
end
|
||||
end
|
||||
for _, w in map.walls do
|
||||
if band(w.cstat, YAX_BIT) ~= 0 then
|
||||
w.yaxceilingwall = w.lotag
|
||||
end
|
||||
if band(w.cstat, YAX_BIT * 2) ~= 0 then
|
||||
w.yaxfloorwall = w.extra
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
type Batch = { kind: string, tile: number, data: { number }, n: number } -- data: x y z nx ny nz u v per vertex
|
||||
|
||||
function Geometry.scene(map: Map, opts: Options): Types.Scene
|
||||
local scale = tonumber(opts.scale) or 1
|
||||
local tiles = if type(opts.tiles) == "table" then opts.tiles else nil
|
||||
local skyWalls = opts.skyWalls == true
|
||||
local walls, sectors = map.walls, map.sectors
|
||||
local batches: { [string]: Batch } = {}
|
||||
local order: { Batch } = {}
|
||||
local function tileSize(tile: number): (number, number)
|
||||
local t = tiles and tiles[tile]
|
||||
local w, h = if type(t) == "table" then tonumber(t.width) else nil, if type(t) == "table" then tonumber(t.height) else nil
|
||||
return if w and w > 0 then w else 64, if h and h > 0 then h else 64
|
||||
end
|
||||
local function batch(kind: string, tile: number): Batch
|
||||
local key = kind .. ":" .. tile
|
||||
local b = batches[key]
|
||||
if not b then
|
||||
b = { kind = kind, tile = tile, data = {}, n = 0 }
|
||||
batches[key] = b
|
||||
table.insert(order, b)
|
||||
end
|
||||
return b
|
||||
end
|
||||
local function emit(b: Batch, v: { number })
|
||||
local d = b.data
|
||||
local k = #d
|
||||
for i = 1, 8 do
|
||||
d[k + i] = v[i]
|
||||
end
|
||||
b.n += 1
|
||||
end
|
||||
local function world(x: number, y: number, z: number): (number, number, number)
|
||||
return x * scale, -y * scale, -z / 16 * scale
|
||||
end
|
||||
local function tri(b: Batch, a: { number }, c: { number }, d: { number })
|
||||
-- a / c / d: Build x, y, z, u, v
|
||||
local ax, ay, az = world(a[1], a[2], a[3])
|
||||
local cx, cy, cz = world(c[1], c[2], c[3])
|
||||
local dx, dy, dz = world(d[1], d[2], d[3])
|
||||
local ux, uy, uz = cx - ax, cy - ay, cz - az
|
||||
local vx, vy, vz = dx - ax, dy - ay, dz - az
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
if l == 0 then
|
||||
return
|
||||
end
|
||||
nx, ny, nz = nx / l, ny / l, nz / l
|
||||
emit(b, { ax, ay, az, nx, ny, nz, a[4], a[5] })
|
||||
emit(b, { cx, cy, cz, nx, ny, nz, c[4], c[5] })
|
||||
emit(b, { dx, dy, dz, nx, ny, nz, d[4], d[5] })
|
||||
end
|
||||
|
||||
-- floors and ceilings
|
||||
local secLoops: { { { number } } } = {}
|
||||
for si, s in sectors do
|
||||
local ls = Geometry.loops(map, si - 1)
|
||||
secLoops[si] = ls
|
||||
local flat: { { number } } = {}
|
||||
for li, loop in ls do
|
||||
local f: { number } = {}
|
||||
for _, w in loop do
|
||||
table.insert(f, walls[w + 1].x)
|
||||
table.insert(f, -walls[w + 1].y)
|
||||
end
|
||||
flat[li] = f
|
||||
end
|
||||
local tris = Polygon.triangulate(flat)
|
||||
for pass = 1, 2 do
|
||||
local isFloor = pass == 1
|
||||
local stat = if isFloor then s.floorstat else s.ceilingstat
|
||||
if not (map.version == 9 and band(stat, YAX_BIT) ~= 0) then
|
||||
local tile = if isFloor then s.floorpicnum else s.ceilingpicnum
|
||||
local tw, th = tileSize(tile)
|
||||
local texel = if band(stat, SMOOSH) ~= 0 then 8 else 16
|
||||
local xpan = (if isFloor then s.floorxpanning else s.ceilingxpanning) * tw / 256
|
||||
local ypan = (if isFloor then s.floorypanning else s.ceilingypanning) * th / 256
|
||||
local ox, oy, ex, ey = 0, 0, 1, 0
|
||||
if band(stat, RELATIVE) ~= 0 then
|
||||
local w0 = walls[s.wallptr + 1]
|
||||
local w1 = w0 and walls[w0.point2 + 1]
|
||||
if w1 then
|
||||
local dx, dy = w1.x - w0.x, w1.y - w0.y
|
||||
local len = math.sqrt(dx * dx + dy * dy)
|
||||
if len > 0 then
|
||||
ox, oy, ex, ey = w0.x, w0.y, dx / len, dy / len
|
||||
end
|
||||
end
|
||||
end
|
||||
local b = batch(if isFloor then "floor" else "ceiling", tile)
|
||||
local function corner(li: number, vi: number): { number }
|
||||
local w = walls[ls[li][vi] + 1]
|
||||
local x, y = w.x, w.y
|
||||
local lx, ly = (x - ox) * ex + (y - oy) * ey, (y - oy) * ex - (x - ox) * ey
|
||||
if band(stat, SWAP_XY) ~= 0 then
|
||||
lx, ly = ly, lx
|
||||
end
|
||||
if band(stat, FLIP_X) ~= 0 then
|
||||
lx = -lx
|
||||
end
|
||||
if band(stat, FLIP_Y) ~= 0 then
|
||||
ly = -ly
|
||||
end
|
||||
return { x, y, Geometry.slopeZ(map, si - 1, isFloor, x, y), (lx / texel + xpan) / tw, (ly / texel + ypan) / th }
|
||||
end
|
||||
for k = 1, #tris, 6 do
|
||||
local a, c, d = corner(tris[k], tris[k + 1]), corner(tris[k + 2], tris[k + 3]), corner(tris[k + 4], tris[k + 5])
|
||||
if isFloor then
|
||||
tri(b, a, c, d)
|
||||
else
|
||||
tri(b, a, d, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- walls: (x1, y1) -> (x2, y2) with the sector on the right; top / bottom z at both ends, z down
|
||||
local function part(kind: string, tile: number, w: Wall, x1: number, y1: number, x2: number, y2: number, t1: number, t2: number, b1: number, b2: number, anchor: number, fromBottom: boolean)
|
||||
local h1, h2 = b1 - t1, b2 - t2
|
||||
if h1 <= 0 and h2 <= 0 then
|
||||
return
|
||||
end
|
||||
local tw, th = tileSize(tile)
|
||||
local flipX, flipY = band(w.cstat, W_FLIP_X) ~= 0, band(w.cstat, W_FLIP_Y) ~= 0
|
||||
local span = w.xrepeat * 8
|
||||
local function v(t: number, z: number): { number }
|
||||
local u = (w.xpanning + (if flipX then 1 - t else t) * span) / tw
|
||||
local px = (z - anchor) * w.yrepeat / 1024 + w.ypanning * th / 256 + (if fromBottom then th else 0)
|
||||
local vv = px / th
|
||||
return { x1 + (x2 - x1) * t, y1 + (y2 - y1) * t, z, u, if flipY then -vv else vv }
|
||||
end
|
||||
local b = batch(kind, tile)
|
||||
if h1 > 0 and h2 > 0 then
|
||||
local p1b, p2b, p2t, p1t = v(0, b1), v(1, b2), v(1, t2), v(0, t1)
|
||||
tri(b, p1b, p2b, p2t)
|
||||
tri(b, p1b, p2t, p1t)
|
||||
elseif h1 > 0 then
|
||||
local f = h1 / (h1 - h2)
|
||||
tri(b, v(0, b1), v(f, t1 + (t2 - t1) * f), v(0, t1))
|
||||
else
|
||||
local f = h1 / (h1 - h2)
|
||||
tri(b, v(f, t1 + (t2 - t1) * f), v(1, b2), v(1, t2))
|
||||
end
|
||||
end
|
||||
for si, s in sectors do
|
||||
local me = si - 1
|
||||
for _, loop in secLoops[si] do
|
||||
for _, wi in loop do
|
||||
local w = walls[wi + 1]
|
||||
local w2 = walls[w.point2 + 1]
|
||||
local x1, y1, x2, y2 = w.x, w.y, w2.x, w2.y
|
||||
local c1, c2 = Geometry.slopeZ(map, me, false, x1, y1), Geometry.slopeZ(map, me, false, x2, y2)
|
||||
local f1, f2 = Geometry.slopeZ(map, me, true, x1, y1), Geometry.slopeZ(map, me, true, x2, y2)
|
||||
local ns = w.nextsector
|
||||
local other = if ns >= 0 then sectors[ns + 1] else nil
|
||||
if not other then
|
||||
local fromBottom = band(w.cstat, W_ALIGN_BOTTOM) ~= 0
|
||||
part("wall", w.picnum, w, x1, y1, x2, y2, c1, c2, f1, f2, if fromBottom then s.floorz else s.ceilingz, fromBottom)
|
||||
else
|
||||
local oc1, oc2 = Geometry.slopeZ(map, ns, false, x1, y1), Geometry.slopeZ(map, ns, false, x2, y2)
|
||||
local of1, of2 = Geometry.slopeZ(map, ns, true, x1, y1), Geometry.slopeZ(map, ns, true, x2, y2)
|
||||
local aligned = band(w.cstat, W_ALIGN_BOTTOM) ~= 0
|
||||
if skyWalls or band(s.ceilingstat, PARALLAX) == 0 or band(other.ceilingstat, PARALLAX) == 0 then
|
||||
part("wall", w.picnum, w, x1, y1, x2, y2, c1, c2, oc1, oc2, if aligned then s.ceilingz else other.ceilingz, not aligned)
|
||||
end
|
||||
if skyWalls or band(s.floorstat, PARALLAX) == 0 or band(other.floorstat, PARALLAX) == 0 then
|
||||
local lw = w
|
||||
if band(w.cstat, W_BOTTOM_SWAP) ~= 0 and walls[w.nextwall + 1] then
|
||||
lw = walls[w.nextwall + 1]
|
||||
end
|
||||
part("wall", lw.picnum, lw, x1, y1, x2, y2, of1, of2, f1, f2, if aligned then s.ceilingz else other.floorz, false)
|
||||
end
|
||||
if band(w.cstat, W_MASKED) ~= 0 then
|
||||
local fromBottom = aligned
|
||||
part("masked", w.overpicnum, w, x1, y1, x2, y2, math.max(c1, oc1), math.max(c2, oc2), math.min(f1, of1), math.min(f2, of2),
|
||||
if fromBottom then math.min(s.floorz, other.floorz) else math.max(s.ceilingz, other.ceilingz), fromBottom)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the mesh: a primitive per (kind, tile), a material per tile (masked walls their own, alpha-masked)
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local mesh: Types.Mesh = { name = "map", primitives = {} }
|
||||
local texIndex: { [number]: number } = {}
|
||||
local matIndex: { [string]: number } = {}
|
||||
for _, b in order do
|
||||
local n = b.n
|
||||
if n > 0 then
|
||||
local pos, nrm, uv, idx = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
|
||||
local d = b.data
|
||||
for i = 0, n - 1 do
|
||||
local k = i * 8
|
||||
buffer.writef32(pos, i * 12, d[k + 1])
|
||||
buffer.writef32(pos, i * 12 + 4, d[k + 2])
|
||||
buffer.writef32(pos, i * 12 + 8, d[k + 3])
|
||||
buffer.writef32(nrm, i * 12, d[k + 4])
|
||||
buffer.writef32(nrm, i * 12 + 4, d[k + 5])
|
||||
buffer.writef32(nrm, i * 12 + 8, d[k + 6])
|
||||
buffer.writef32(uv, i * 8, d[k + 7])
|
||||
buffer.writef32(uv, i * 8 + 4, d[k + 8])
|
||||
buffer.writeu32(idx, i * 4, i)
|
||||
end
|
||||
local ti = texIndex[b.tile]
|
||||
if not ti then
|
||||
local t = tiles and tiles[b.tile]
|
||||
table.insert(scene.textures, {
|
||||
name = "tile" .. b.tile,
|
||||
uri = "tile" .. b.tile,
|
||||
image = if type(t) == "table" and t.kind == "image" then t else nil,
|
||||
extras = { build = { tile = b.tile } },
|
||||
})
|
||||
ti = #scene.textures
|
||||
texIndex[b.tile] = ti
|
||||
end
|
||||
local masked = b.kind == "masked"
|
||||
local mkey = (if masked then "m" else "s") .. b.tile
|
||||
local mi = matIndex[mkey]
|
||||
if not mi then
|
||||
local mat = Scene.material("tile" .. b.tile)
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = ti }
|
||||
if masked then
|
||||
mat.alphaMode = "mask"
|
||||
mat.doubleSided = true
|
||||
end
|
||||
mat.extras = { build = { tile = b.tile } }
|
||||
table.insert(scene.materials, mat)
|
||||
mi = #scene.materials
|
||||
matIndex[mkey] = mi
|
||||
end
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(pos, "f32", 3, n),
|
||||
NORMAL = Scene.accessor(nrm, "f32", 3, n),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, n),
|
||||
},
|
||||
indices = Scene.accessor(idx, "u32", 1, n),
|
||||
mode = "triangles" :: any,
|
||||
material = mi,
|
||||
extras = { build = { kind = b.kind, tile = b.tile } },
|
||||
})
|
||||
end
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
local root: Types.Node = { name = "map", children = {}, mesh = 1 }
|
||||
scene.nodes[1] = root
|
||||
scene.roots[1] = 1
|
||||
local function yaw(ang: number): { number }
|
||||
local a = -ang * math.pi / 2048
|
||||
return { 0, 0, math.sin(a), math.cos(a) }
|
||||
end
|
||||
local sx, sy, sz = world(map.x, map.y, map.z)
|
||||
table.insert(scene.nodes, {
|
||||
name = "start",
|
||||
children = {},
|
||||
translation = { sx, sy, sz },
|
||||
rotation = yaw(map.ang),
|
||||
extras = { build = { start = true, sector = map.cursectnum } },
|
||||
})
|
||||
table.insert(root.children, #scene.nodes)
|
||||
for i, sp in map.sprites do
|
||||
local px, py, pz = world(sp.x, sp.y, sp.z)
|
||||
table.insert(scene.nodes, {
|
||||
name = "sprite " .. (i - 1),
|
||||
children = {},
|
||||
translation = { px, py, pz },
|
||||
rotation = yaw(sp.ang),
|
||||
extras = { build = { tile = sp.picnum, sprite = sp } },
|
||||
})
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
return scene
|
||||
end
|
||||
|
||||
return Geometry
|
||||
@@ -0,0 +1,270 @@
|
||||
--!strict
|
||||
-- model/buildmap: Build engine maps (.map versions 7-9: Duke Nukem 3D, Shadow Warrior, eduke32), from Ken Silverman's
|
||||
-- BUILDINF.TXT and the eduke32 wiki ("MAP format"); no code taken. Supports: sectors, walls, sprites as raw tables
|
||||
-- (meta.build), a Scene (sloped floors / ceilings, walls with upper / lower parts at red walls, masked walls, sprites
|
||||
-- as nodes), v9 room-over-room fields, trailing bytes; writes the raw tables back. Not supported: v5 / v6, Blood's
|
||||
-- encrypted BLM maps, the eduke32 text format (v10).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Geometry = require("@rosetta/model/buildmap/Geometry")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local BuildMap = {
|
||||
name = "buildmap",
|
||||
category = "model",
|
||||
extensions = { "map" },
|
||||
mime = { "application/x-build-map" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, sprites = true, slopes = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Sector = Geometry.Sector
|
||||
export type Wall = Geometry.Wall
|
||||
export type Sprite = { [string]: number }
|
||||
export type Map = Geometry.Map
|
||||
export type DecodeOptions = Geometry.Options & {
|
||||
maxBytes: number?, -- default 2^28
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
version: number?, -- 7, 8 or 9; default map.version
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- field name, size (1 / -1 = u8 / i8, 2 / -2 = u16 / i16, -4 = i32), BUILDINF.TXT order
|
||||
local SECTOR = {
|
||||
{ "wallptr", -2 }, { "wallnum", -2 }, { "ceilingz", -4 }, { "floorz", -4 }, { "ceilingstat", -2 }, { "floorstat", -2 },
|
||||
{ "ceilingpicnum", -2 }, { "ceilingheinum", -2 }, { "ceilingshade", -1 }, { "ceilingpal", 1 }, { "ceilingxpanning", 1 },
|
||||
{ "ceilingypanning", 1 }, { "floorpicnum", -2 }, { "floorheinum", -2 }, { "floorshade", -1 }, { "floorpal", 1 },
|
||||
{ "floorxpanning", 1 }, { "floorypanning", 1 }, { "visibility", 1 }, { "filler", 1 }, { "lotag", -2 }, { "hitag", -2 },
|
||||
{ "extra", -2 },
|
||||
}
|
||||
local WALL = {
|
||||
{ "x", -4 }, { "y", -4 }, { "point2", -2 }, { "nextwall", -2 }, { "nextsector", -2 }, { "cstat", -2 }, { "picnum", -2 },
|
||||
{ "overpicnum", -2 }, { "shade", -1 }, { "pal", 1 }, { "xrepeat", 1 }, { "yrepeat", 1 }, { "xpanning", 1 },
|
||||
{ "ypanning", 1 }, { "lotag", -2 }, { "hitag", -2 }, { "extra", -2 },
|
||||
}
|
||||
local SPRITE = {
|
||||
{ "x", -4 }, { "y", -4 }, { "z", -4 }, { "cstat", -2 }, { "picnum", -2 }, { "shade", -1 }, { "pal", 1 }, { "clipdist", 1 },
|
||||
{ "filler", 1 }, { "xrepeat", 1 }, { "yrepeat", 1 }, { "xoffset", -1 }, { "yoffset", -1 }, { "sectnum", -2 },
|
||||
{ "statnum", -2 }, { "ang", -2 }, { "owner", -2 }, { "xvel", -2 }, { "yvel", -2 }, { "zvel", -2 }, { "lotag", -2 },
|
||||
{ "hitag", -2 }, { "extra", -2 },
|
||||
}
|
||||
local SECTOR_SIZE, WALL_SIZE, SPRITE_SIZE = 40, 32, 44
|
||||
local HEADER = 22 -- version, posx, posy, posz, ang, cursectnum, then u16 numsectors at 20
|
||||
local readu16 = buffer.readu16
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function layout(b: buffer, o: number, limit: number): (number?, number?, number?, number?)
|
||||
if limit - o < HEADER then
|
||||
return nil
|
||||
end
|
||||
local ns = readu16(b, o + 20)
|
||||
local p = o + HEADER + ns * SECTOR_SIZE
|
||||
if p + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local nw = readu16(b, p)
|
||||
p += 2 + nw * WALL_SIZE
|
||||
if p + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local nsp = readu16(b, p)
|
||||
p += 2 + nsp * SPRITE_SIZE
|
||||
return ns, nw, nsp, p
|
||||
end
|
||||
|
||||
function BuildMap.sniff(r: Bytes.Reader): number
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < HEADER then
|
||||
return 0
|
||||
end
|
||||
local v = buffer.readu32(b, o)
|
||||
if v ~= 7 and v ~= 8 and v ~= 9 then
|
||||
return 0
|
||||
end
|
||||
local ns, _, _, stop = layout(b, o, limit)
|
||||
if not ns or not stop or stop > limit then
|
||||
return 0
|
||||
end
|
||||
return if stop == limit then 0.9 else 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function readRecord(b: buffer, p: number, fields: { any }): { [string]: number }
|
||||
local rec: { [string]: number } = {}
|
||||
for _, f in fields do
|
||||
local size = f[2]
|
||||
local v
|
||||
if size == 1 then
|
||||
v = buffer.readu8(b, p)
|
||||
elseif size == -1 then
|
||||
v = buffer.readi8(b, p)
|
||||
elseif size == 2 then
|
||||
v = readu16(b, p)
|
||||
elseif size == -2 then
|
||||
v = buffer.readi16(b, p)
|
||||
else
|
||||
v = buffer.readi32(b, p)
|
||||
end
|
||||
rec[f[1]] = v
|
||||
p += math.abs(size)
|
||||
end
|
||||
return rec
|
||||
end
|
||||
|
||||
function BuildMap.parse(r: Bytes.Reader, opts: DecodeOptions?): (Map?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if buffer.readstring(b, o, 4) == "BLM\26" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Blood maps (BLM, encrypted) are not supported", o)
|
||||
end
|
||||
if buffer.readstring(b, o, 4) == "--ED" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "eduke32 text maps (version 10) are not supported", o)
|
||||
end
|
||||
local version = buffer.readu32(b, o)
|
||||
if version == 5 or version == 6 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("map version %d (only 7-9)", version), o)
|
||||
elseif version < 7 or version > 9 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("not a Build map (version %d)", version), o)
|
||||
end
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 28
|
||||
if limit - o > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d bytes is over the %d byte limit", limit - o, maxBytes))
|
||||
end
|
||||
local ns, nw, nsp, stop = layout(b, o, limit)
|
||||
if not ns or not nw or not nsp or not stop or stop > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "sector / wall / sprite tables end early", o)
|
||||
end
|
||||
local map: Map = {
|
||||
version = version,
|
||||
x = buffer.readi32(b, o + 4),
|
||||
y = buffer.readi32(b, o + 8),
|
||||
z = buffer.readi32(b, o + 12),
|
||||
ang = buffer.readi16(b, o + 16),
|
||||
cursectnum = buffer.readi16(b, o + 18),
|
||||
sectors = table.create(ns),
|
||||
walls = table.create(nw),
|
||||
sprites = table.create(nsp),
|
||||
}
|
||||
local p = o + HEADER
|
||||
for i = 1, ns do
|
||||
local s = readRecord(b, p, SECTOR) :: any
|
||||
if s.wallptr < 0 or s.wallnum < 0 or s.wallptr + s.wallnum > nw then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("sector %d: walls %d + %d out of range", i - 1, s.wallptr, s.wallnum), p)
|
||||
end
|
||||
map.sectors[i] = s
|
||||
p += SECTOR_SIZE
|
||||
end
|
||||
p += 2
|
||||
for i = 1, nw do
|
||||
map.walls[i] = readRecord(b, p, WALL) :: any
|
||||
p += WALL_SIZE
|
||||
end
|
||||
p += 2
|
||||
for i = 1, nsp do
|
||||
map.sprites[i] = readRecord(b, p, SPRITE)
|
||||
p += SPRITE_SIZE
|
||||
end
|
||||
if stop < limit then
|
||||
local t = buffer.create(limit - stop)
|
||||
buffer.copy(t, 0, b, stop, limit - stop)
|
||||
map.trailing = t
|
||||
end
|
||||
if version == 9 then
|
||||
Geometry.yax(map)
|
||||
end
|
||||
return map, nil
|
||||
end
|
||||
|
||||
function BuildMap.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local map, err = BuildMap.parse(r, opts)
|
||||
if not map then
|
||||
return nil, err
|
||||
end
|
||||
return BuildMap.scene(map, opts), nil
|
||||
end
|
||||
|
||||
function BuildMap.scene(map: Map, opts: Geometry.Options?): Types.Scene
|
||||
local scene = Geometry.scene(map, opts or {})
|
||||
scene.meta.build = map
|
||||
scene.meta.source = {
|
||||
format = "buildmap",
|
||||
version = map.version,
|
||||
sectors = #map.sectors,
|
||||
walls = #map.walls,
|
||||
sprites = #map.sprites,
|
||||
}
|
||||
return scene
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function writeRecord(out: Bytes.Writer, rec: { [string]: any }, fields: { any }): string?
|
||||
for _, f in fields do
|
||||
local v = rec[f[1]]
|
||||
if type(v) ~= "number" or v ~= v then
|
||||
return f[1]
|
||||
end
|
||||
local size = math.abs(f[2])
|
||||
local n = math.floor(v)
|
||||
if size == 1 then
|
||||
out:u8(n % 256)
|
||||
elseif size == 2 then
|
||||
out:u16le(n % 65536)
|
||||
else
|
||||
out:u32le(n % 4294967296)
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function BuildMap.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local map = if type(value) == "table" and type(value.meta) == "table" and value.meta.build then value.meta.build else value
|
||||
if type(map) ~= "table" or type(map.sectors) ~= "table" or type(map.walls) ~= "table" or type(map.sprites) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene from model/buildmap (meta.build) or a map table")
|
||||
end
|
||||
local version = math.floor(tonumber(opts and opts.version) or tonumber(map.version) or 7)
|
||||
if version < 7 or version > 9 then
|
||||
return nil, Err.new(Err.ARG, "version must be 7, 8 or 9")
|
||||
end
|
||||
local ns, nw, nsp = #map.sectors, #map.walls, #map.sprites
|
||||
if ns > 65535 or nw > 65535 or nsp > 65535 then
|
||||
return nil, Err.new(Err.ARG, "at most 65535 sectors / walls / sprites")
|
||||
end
|
||||
local trailing = if type(map.trailing) == "buffer" then map.trailing else nil
|
||||
local out = Bytes.writer(HEADER + 6 + ns * SECTOR_SIZE + nw * WALL_SIZE + nsp * SPRITE_SIZE + (if trailing then buffer.len(trailing) else 0))
|
||||
out:u32le(version)
|
||||
for _, k in { "x", "y", "z" } do
|
||||
out:u32le(math.floor(tonumber(map[k]) or 0) % 4294967296)
|
||||
end
|
||||
out:u16le(math.floor(tonumber(map.ang) or 0) % 65536)
|
||||
out:u16le(math.floor(tonumber(map.cursectnum) or 0) % 65536)
|
||||
for _, part in { { map.sectors, SECTOR, "sector" }, { map.walls, WALL, "wall" }, { map.sprites, SPRITE, "sprite" } } do
|
||||
local list = part[1] :: { any }
|
||||
out:u16le(#list)
|
||||
for i, rec in list do
|
||||
if type(rec) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, string.format("%s %d is not a table", part[3] :: string, i - 1))
|
||||
end
|
||||
local bad = writeRecord(out, rec, part[2] :: { any })
|
||||
if bad then
|
||||
return nil, Err.new(Err.ARG, string.format("%s %d: field %s is not a number", part[3] :: string, i - 1, bad))
|
||||
end
|
||||
end
|
||||
end
|
||||
if trailing then
|
||||
out:bytes(trailing)
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
BuildMap.slopeZ = Geometry.slopeZ
|
||||
BuildMap.loops = Geometry.loops
|
||||
|
||||
return BuildMap
|
||||
@@ -0,0 +1,203 @@
|
||||
-- model/buildmap tests against an independent Python reading and Ken Silverman's map2stl (tools/fixtures/buildmap.py):
|
||||
-- raw tables, loops, slope heights, floor / wall areas and centroids of the Scene, sprites, v8 / v9, write round trips.
|
||||
local T = require("@tests/T")
|
||||
local BuildMap = require("@rosetta/model/buildmap")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Fx = require("@tests/gen/buildmap")
|
||||
|
||||
local t = T.suite("buildmap")
|
||||
t:eq(BuildMap.name, "buildmap", "name")
|
||||
t:check(BuildMap.caps.decode and BuildMap.caps.encode, "caps")
|
||||
|
||||
local function near(a: number, b: number, tol: number): boolean
|
||||
return math.abs(a - b) <= tol * math.max(1, math.abs(b))
|
||||
end
|
||||
|
||||
-- area and area-weighted centroid of the triangles of the given primitive kinds, in map2stl's frame (x / 512, y / 512,
|
||||
-- z / 8192, z down)
|
||||
local function stats(scene: Types.Scene, kinds: { [string]: boolean }): (number, { number })
|
||||
local area, cx, cy, cz = 0, 0, 0, 0
|
||||
for _, prim in scene.meshes[1].primitives do
|
||||
if kinds[prim.extras.build.kind] then
|
||||
local get = assert(Types.Scene.reader(prim.attributes.POSITION))
|
||||
for i = 0, prim.attributes.POSITION.count - 1, 3 do
|
||||
local p: { { number } } = {}
|
||||
for k = 0, 2 do
|
||||
p[k + 1] = { get(i + k, 0), -get(i + k, 1), -get(i + k, 2) }
|
||||
end
|
||||
local ux, uy, uz = p[2][1] - p[1][1], p[2][2] - p[1][2], p[2][3] - p[1][3]
|
||||
local vx, vy, vz = p[3][1] - p[1][1], p[3][2] - p[1][2], p[3][3] - p[1][3]
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
local a = 0.5 * math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
area += a
|
||||
cx += a * (p[1][1] + p[2][1] + p[3][1]) / 3
|
||||
cy += a * (p[1][2] + p[2][2] + p[3][2]) / 3
|
||||
cz += a * (p[1][3] + p[2][3] + p[3][3]) / 3
|
||||
end
|
||||
end
|
||||
end
|
||||
return area, if area > 0 then { cx / area, cy / area, cz / area } else { 0, 0, 0 }
|
||||
end
|
||||
|
||||
local SECTOR_FIELDS = { "wallptr", "wallnum", "ceilingz", "floorz", "ceilingstat", "floorstat", "ceilingpicnum", "ceilingheinum", "ceilingshade", "ceilingpal", "ceilingxpanning", "ceilingypanning", "floorpicnum", "floorheinum", "floorshade", "floorpal", "floorxpanning", "floorypanning", "visibility", "filler", "lotag", "hitag", "extra" }
|
||||
local WALL_FIELDS = { "x", "y", "point2", "nextwall", "nextsector", "cstat", "picnum", "overpicnum", "shade", "pal", "xrepeat", "yrepeat", "xpanning", "ypanning", "lotag", "hitag", "extra" }
|
||||
local SPRITE_FIELDS = { "x", "y", "z", "cstat", "picnum", "shade", "pal", "clipdist", "filler", "xrepeat", "yrepeat", "xoffset", "yoffset", "sectnum", "statnum", "ang", "owner", "xvel", "yvel", "zvel", "lotag", "hitag", "extra" }
|
||||
|
||||
for _, m in Fx.maps do
|
||||
local data = buffer.fromstring(m.data)
|
||||
local label = m.name
|
||||
t:check(BuildMap.sniff(Bytes.reader(data)) >= 0.5, label .. ": sniff")
|
||||
local scene, err = BuildMap.decode(Bytes.reader(data), { scale = 1 / 512, skyWalls = true })
|
||||
t:check(scene, label .. ": " .. tostring(err))
|
||||
local s = scene :: Types.Scene
|
||||
local map = s.meta.build
|
||||
t:eq(map.version, m.version, label .. ": version")
|
||||
t:eq(#map.sectors, m.counts.sectors, label .. ": sectors")
|
||||
t:eq(#map.walls, m.counts.walls, label .. ": walls")
|
||||
t:eq(#map.sprites, m.counts.sprites, label .. ": sprites")
|
||||
for _, part in { { map.sectors, SECTOR_FIELDS, "sector" }, { map.walls, WALL_FIELDS, "wall" }, { map.sprites, SPRITE_FIELDS, "sprite" } } do
|
||||
for _, f in part[2] :: { string } do
|
||||
local sum = 0
|
||||
for _, rec in part[1] :: { any } do
|
||||
sum += rec[f]
|
||||
end
|
||||
t:eq(sum, m.sums[part[3]][f], label .. ": " .. part[3] .. "." .. f .. " sum")
|
||||
end
|
||||
end
|
||||
for si, want in m.loops do
|
||||
local got = BuildMap.loops(map, si - 1)
|
||||
t:eq(#got, #want, label .. ": sector " .. (si - 1) .. " loops")
|
||||
for li, l in want do
|
||||
t:eq(table.concat(got[li], ","), table.concat(l, ","), label .. ": sector " .. (si - 1) .. " loop " .. li)
|
||||
end
|
||||
end
|
||||
for _, z in m.z do
|
||||
t:check(near(BuildMap.slopeZ(map, z.sector, true, z.x, z.y), z.floor, 1e-9), label .. ": floor z")
|
||||
t:check(near(BuildMap.slopeZ(map, z.sector, false, z.x, z.y), z.ceiling, 1e-9), label .. ": ceiling z")
|
||||
end
|
||||
if m.stl then
|
||||
local fa, fc = stats(s, { floor = true, ceiling = true })
|
||||
local wa, wc = stats(s, { wall = true })
|
||||
t:check(near(fa, m.stl.floorArea, 1e-4), string.format("%s: floor area %.5f vs map2stl %.5f", label, fa, m.stl.floorArea))
|
||||
t:check(near(wa, m.stl.wallArea, 1e-4), string.format("%s: wall area %.5f vs map2stl %.5f", label, wa, m.stl.wallArea))
|
||||
for k = 1, 3 do
|
||||
t:check(near(fc[k], m.stl.floorCentroid[k], 1e-4), label .. ": floor centroid " .. k)
|
||||
t:check(near(wc[k], m.stl.wallCentroid[k], 1e-4), label .. ": wall centroid " .. k)
|
||||
end
|
||||
end
|
||||
-- sprites: nodes with their tile, in world units
|
||||
local sprites = 0
|
||||
for _, node in s.nodes do
|
||||
local b = node.extras and node.extras.build
|
||||
if b and b.sprite then
|
||||
sprites += 1
|
||||
t:eq(b.tile, b.sprite.picnum, label .. ": sprite tile")
|
||||
local tr = node.translation :: { number }
|
||||
t:check(near(tr[1], b.sprite.x / 512, 1e-9) and near(tr[2], -b.sprite.y / 512, 1e-9) and near(tr[3], -b.sprite.z / 8192, 1e-9), label .. ": sprite position")
|
||||
end
|
||||
end
|
||||
t:eq(sprites, m.counts.sprites, label .. ": sprite nodes")
|
||||
-- write back
|
||||
local again = assert(BuildMap.encode(s))
|
||||
t:eq(buffer.tostring(again), m.data, label .. ": round trip")
|
||||
t:eq(buffer.tostring(assert(BuildMap.encode(map))), m.data, label .. ": round trip from the map table")
|
||||
end
|
||||
|
||||
-- details
|
||||
do
|
||||
local rooms = assert(BuildMap.decode(Bytes.reader(buffer.fromstring(Fx.maps[1].data))))
|
||||
local kinds: { [string]: number } = {}
|
||||
for _, prim in rooms.meshes[1].primitives do
|
||||
local k = prim.extras.build.kind
|
||||
kinds[k] = (kinds[k] or 0) + prim.attributes.POSITION.count
|
||||
t:check(rooms.materials[prim.material :: number].baseColorTexture ~= nil, "material texture")
|
||||
end
|
||||
t:check(kinds.floor and kinds.ceiling and kinds.wall and kinds.masked, "floor, ceiling, wall and masked parts")
|
||||
t:eq(rooms.meta.up, "z", "z up")
|
||||
-- facing: floors up, ceilings down, the hall's north wall (Build y = 0) towards the hall (world -y)
|
||||
local facing = 0
|
||||
for _, prim in rooms.meshes[1].primitives do
|
||||
local kind = prim.extras.build.kind
|
||||
local pos = assert(Types.Scene.reader(prim.attributes.POSITION))
|
||||
local nrm = assert(Types.Scene.reader(prim.attributes.NORMAL))
|
||||
for i = 0, prim.attributes.POSITION.count - 1 do
|
||||
if kind == "floor" and nrm(i, 2) <= 0 or kind == "ceiling" and nrm(i, 2) >= 0 then
|
||||
facing += 1
|
||||
elseif kind == "wall" and pos(i, 1) == 0 and math.abs(nrm(i, 0)) < 1e-6 and math.abs(nrm(i, 1) + 1) > 1e-6 then
|
||||
facing += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(facing, 0, "faces point into the sectors")
|
||||
t:eq(rooms.nodes[2].name, "start", "start node")
|
||||
-- tile sizes and images from opts.tiles
|
||||
local img = Types.Image.new(32, 16)
|
||||
local withTiles = assert(BuildMap.decode(Bytes.reader(buffer.fromstring(Fx.maps[1].data)), { tiles = { [77] = img } }))
|
||||
local found = false
|
||||
for _, tex in withTiles.textures do
|
||||
if tex.extras and tex.extras.build.tile == 77 then
|
||||
found = tex.image == img
|
||||
end
|
||||
end
|
||||
t:check(found, "tile image attached")
|
||||
-- parallax: walls between two sky ceilings left out unless skyWalls
|
||||
local skyData = buffer.fromstring(Fx.maps[2].data)
|
||||
local a = assert(BuildMap.decode(Bytes.reader(skyData)))
|
||||
local b = assert(BuildMap.decode(Bytes.reader(skyData), { skyWalls = true }))
|
||||
local function wallVerts(sc: Types.Scene): number
|
||||
local n = 0
|
||||
for _, prim in sc.meshes[1].primitives do
|
||||
if prim.extras.build.kind == "wall" then
|
||||
n += prim.attributes.POSITION.count
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
t:check(wallVerts(a) < wallVerts(b), "sky walls dropped")
|
||||
-- v9: room over room fields; linked floors / ceilings not drawn
|
||||
local yax = assert(BuildMap.decode(Bytes.reader(buffer.fromstring(Fx.maps[3].data))))
|
||||
local ym = yax.meta.build
|
||||
t:eq(ym.sectors[1].ceilingbunch, 3, "yax ceiling bunch")
|
||||
t:eq(ym.sectors[2].floorbunch, 3, "yax floor bunch")
|
||||
t:eq(ym.walls[1].yaxceilingwall, 4, "yax ceiling wall")
|
||||
t:eq(ym.walls[6].yaxfloorwall, 0, "yax floor wall")
|
||||
local flats = 0
|
||||
for _, prim in yax.meshes[1].primitives do
|
||||
if prim.extras.build.kind == "floor" or prim.extras.build.kind == "ceiling" then
|
||||
flats += prim.attributes.POSITION.count
|
||||
end
|
||||
end
|
||||
t:eq(flats, 12, "yax-linked ceiling / floor skipped (two squares of two triangles left)")
|
||||
t:check(Fx.maps[4].name == "trailing" and buffer.len(assert(BuildMap.parse(Bytes.reader(buffer.fromstring(Fx.maps[4].data)))).trailing :: buffer) == 12, "trailing bytes kept")
|
||||
-- version override
|
||||
local v8 = assert(BuildMap.encode(rooms, { version = 8 }))
|
||||
t:eq(buffer.readu32(v8, 0), 8, "version override")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local function code(s: string): string?
|
||||
local _, e = BuildMap.decode(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("BLM\26" .. string.rep("\0", 40)), Err.UNSUPPORTED, "Blood map")
|
||||
t:eq(code("\6\0\0\0" .. string.rep("\0", 40)), Err.UNSUPPORTED, "version 6")
|
||||
t:eq(code("// Game: Quake\n{\n\"classname\" \"worldspawn\"\n}\n"), Err.CORRUPT, "Quake map")
|
||||
t:eq(BuildMap.sniff(Bytes.reader(buffer.fromstring("// Game: Quake\n{\n\"classname\" \"worldspawn\"\n}\n"))), 0, "sniff Quake map")
|
||||
t:eq(code(string.sub(Fx.maps[1].data, 1, 100)), Err.TRUNCATED, "truncated")
|
||||
local _, e = BuildMap.encode({ sectors = {}, walls = { { x = 1 } }, sprites = {} })
|
||||
t:check(e and e.code == Err.ARG, "encode: missing field")
|
||||
local _, e2 = BuildMap.encode(42)
|
||||
t:check(e2 and e2.code == Err.ARG, "encode: not a map")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, m in Fx.maps do
|
||||
table.insert(samples, m.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return BuildMap.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 200 })
|
||||
t:done()
|
||||
@@ -0,0 +1,223 @@
|
||||
# Build .map fixtures (tools/fixtures.py). No Duke 3D / Shadow Warrior maps (proprietary): maps are written here from
|
||||
# BUILDINF.TXT (v7 layout; v8 / v9 share it), red walls linked by matching reversed wall segments. References:
|
||||
# - an independent Python reading of each map: field sums per table, every sector's loops, and the floor / ceiling
|
||||
# z of every sector at each of its wall points by the BUILDINF slope formula;
|
||||
# - Ken Silverman's map2stl (eduke32 source, tools/fixtures/_build_ref.py) turns the v7 bytes of each map into an
|
||||
# STL: total area and area-weighted centroid of its floor / ceiling triangles and of its wall triangles.
|
||||
# tests/gen/buildmap.luau { maps = { { name, data, version, counts = { sectors, walls, sprites }, sums = { sector =
|
||||
# { field = sum }, wall, sprite }, loops = { { { wall } } }, z = { { sector, x, y, floor,
|
||||
# ceiling } }, stl = { floorArea, wallArea, floorCentroid = { x, y, z }, wallCentroid } } } }
|
||||
import os, struct, subprocess, tempfile, shutil, importlib.util
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_build_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_build_ref.py"))
|
||||
B = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(B)
|
||||
|
||||
INPUTS = ["tools/fixtures/_build_ref.py"]
|
||||
|
||||
SECTOR = [("wallptr", "h"), ("wallnum", "h"), ("ceilingz", "i"), ("floorz", "i"), ("ceilingstat", "h"), ("floorstat", "h"),
|
||||
("ceilingpicnum", "h"), ("ceilingheinum", "h"), ("ceilingshade", "b"), ("ceilingpal", "B"), ("ceilingxpanning", "B"),
|
||||
("ceilingypanning", "B"), ("floorpicnum", "h"), ("floorheinum", "h"), ("floorshade", "b"), ("floorpal", "B"),
|
||||
("floorxpanning", "B"), ("floorypanning", "B"), ("visibility", "B"), ("filler", "B"), ("lotag", "h"), ("hitag", "h"),
|
||||
("extra", "h")]
|
||||
WALL = [("x", "i"), ("y", "i"), ("point2", "h"), ("nextwall", "h"), ("nextsector", "h"), ("cstat", "h"), ("picnum", "h"),
|
||||
("overpicnum", "h"), ("shade", "b"), ("pal", "B"), ("xrepeat", "B"), ("yrepeat", "B"), ("xpanning", "B"),
|
||||
("ypanning", "B"), ("lotag", "h"), ("hitag", "h"), ("extra", "h")]
|
||||
SPRITE = [("x", "i"), ("y", "i"), ("z", "i"), ("cstat", "h"), ("picnum", "h"), ("shade", "b"), ("pal", "B"), ("clipdist", "B"),
|
||||
("filler", "B"), ("xrepeat", "B"), ("yrepeat", "B"), ("xoffset", "b"), ("yoffset", "b"), ("sectnum", "h"),
|
||||
("statnum", "h"), ("ang", "h"), ("owner", "h"), ("xvel", "h"), ("yvel", "h"), ("zvel", "h"), ("lotag", "h"),
|
||||
("hitag", "h"), ("extra", "h")]
|
||||
FMT = {name: "<" + "".join(t for _, t in fields) for name, fields in (("sector", SECTOR), ("wall", WALL), ("sprite", SPRITE))}
|
||||
assert [struct.calcsize(FMT[k]) for k in ("sector", "wall", "sprite")] == [40, 32, 44]
|
||||
|
||||
|
||||
class MapBuilder:
|
||||
def __init__(self, rng):
|
||||
self.rng = rng
|
||||
self.sectors, self.walls, self.sprites = [], [], []
|
||||
|
||||
def sector(self, loops, **f):
|
||||
"""loops: outer loop first (positive shoelace in Build's y-down coordinates), then holes (negative)"""
|
||||
start = len(self.walls)
|
||||
for li, loop in enumerate(loops):
|
||||
area = sum(loop[i][0] * loop[(i + 1) % len(loop)][1] - loop[(i + 1) % len(loop)][0] * loop[i][1] for i in range(len(loop)))
|
||||
assert (area > 0) == (li == 0), "loop orientation"
|
||||
base = len(self.walls)
|
||||
for i, (x, y) in enumerate(loop):
|
||||
self.walls.append({"x": x, "y": y, "point2": base + (i + 1) % len(loop), "nextwall": -1, "nextsector": -1,
|
||||
"cstat": 0, "picnum": self.rng.randrange(1, 40), "overpicnum": 0, "shade": self.rng.randrange(-8, 20),
|
||||
"pal": 0, "xrepeat": 8, "yrepeat": 8, "xpanning": self.rng.randrange(256),
|
||||
"ypanning": self.rng.randrange(256), "lotag": 0, "hitag": 0, "extra": -1})
|
||||
s = {k: 0 for k, _ in SECTOR}
|
||||
s.update({"wallptr": start, "wallnum": len(self.walls) - start, "extra": -1, "ceilingpicnum": self.rng.randrange(1, 40),
|
||||
"floorpicnum": self.rng.randrange(1, 40), "visibility": self.rng.randrange(256)})
|
||||
s.update(f)
|
||||
self.sectors.append(s)
|
||||
return len(self.sectors) - 1
|
||||
|
||||
def link(self):
|
||||
"""red walls: a wall a -> b of one sector and b -> a of another"""
|
||||
seg = {}
|
||||
for si, s in enumerate(self.sectors):
|
||||
for w in range(s["wallptr"], s["wallptr"] + s["wallnum"]):
|
||||
a, b = self.walls[w], self.walls[self.walls[w]["point2"]]
|
||||
seg[(a["x"], a["y"], b["x"], b["y"])] = (si, w)
|
||||
for si, s in enumerate(self.sectors):
|
||||
for w in range(s["wallptr"], s["wallptr"] + s["wallnum"]):
|
||||
a, b = self.walls[w], self.walls[self.walls[w]["point2"]]
|
||||
o = seg.get((b["x"], b["y"], a["x"], a["y"]))
|
||||
if o:
|
||||
a["nextsector"], a["nextwall"] = o
|
||||
|
||||
def sprite(self, **f):
|
||||
sp = {k: 0 for k, _ in SPRITE}
|
||||
sp.update({"xrepeat": 64, "yrepeat": 64, "clipdist": 32, "owner": -1, "picnum": self.rng.randrange(1000, 2000),
|
||||
"ang": self.rng.randrange(2048), "lotag": self.rng.randrange(100)})
|
||||
sp.update(f)
|
||||
self.sprites.append(sp)
|
||||
|
||||
def write(self, version, pos=(512, 512, -4096), ang=512, cursect=0, trailing=b""):
|
||||
out = bytearray(struct.pack("<iiiihh", version, *pos, ang, cursect))
|
||||
for name, rows, fields in (("sector", self.sectors, SECTOR), ("wall", self.walls, WALL), ("sprite", self.sprites, SPRITE)):
|
||||
out += struct.pack("<H", len(rows))
|
||||
for r in rows:
|
||||
out += struct.pack(FMT[name], *[r[k] for k, _ in fields])
|
||||
return bytes(out) + trailing
|
||||
|
||||
|
||||
def parse(data):
|
||||
"""independent reading: (version, {"sector": [...], "wall": [...], "sprite": [...]})"""
|
||||
version = struct.unpack_from("<i", data, 0)[0]
|
||||
p, tables = 20, {}
|
||||
for name, fields in (("sector", SECTOR), ("wall", WALL), ("sprite", SPRITE)):
|
||||
n = struct.unpack_from("<H", data, p)[0]
|
||||
p += 2
|
||||
size = struct.calcsize(FMT[name])
|
||||
tables[name] = [dict(zip([k for k, _ in fields], struct.unpack_from(FMT[name], data, p + i * size))) for i in range(n)]
|
||||
p += n * size
|
||||
return version, tables
|
||||
|
||||
|
||||
def slope_z(t, si, floor, x, y):
|
||||
s = t["sector"][si]
|
||||
pre = "floor" if floor else "ceiling"
|
||||
z = s[pre + "z"]
|
||||
if not s[pre + "stat"] & 2 or s[pre + "heinum"] == 0:
|
||||
return z
|
||||
w0 = t["wall"][s["wallptr"]]
|
||||
w1 = t["wall"][w0["point2"]]
|
||||
dx, dy = w1["x"] - w0["x"], w1["y"] - w0["y"]
|
||||
ln = (dx * dx + dy * dy) ** 0.5
|
||||
return z + s[pre + "heinum"] * (dx * (y - w0["y"]) - dy * (x - w0["x"])) / (ln * 256)
|
||||
|
||||
|
||||
def loops_of(t, si):
|
||||
s, out, seen = t["sector"][si], [], set()
|
||||
for start in range(s["wallptr"], s["wallptr"] + s["wallnum"]):
|
||||
if start in seen:
|
||||
continue
|
||||
loop, w = [], start
|
||||
while w not in seen:
|
||||
seen.add(w)
|
||||
loop.append(w)
|
||||
w = t["wall"][w]["point2"]
|
||||
out.append(loop)
|
||||
return out
|
||||
|
||||
|
||||
def stl_stats(stl):
|
||||
n = struct.unpack_from("<I", stl, 80)[0]
|
||||
acc = {"floor": [0.0, 0.0, 0.0, 0.0], "wall": [0.0, 0.0, 0.0, 0.0]}
|
||||
for i in range(n):
|
||||
v = struct.unpack_from("<12f", stl, 84 + i * 50)
|
||||
nz, a, b, c = v[2], v[3:6], v[6:9], v[9:12]
|
||||
ux, uy, uz = b[0] - a[0], b[1] - a[1], b[2] - a[2]
|
||||
vx, vy, vz = c[0] - a[0], c[1] - a[1], c[2] - a[2]
|
||||
cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
area = 0.5 * (cx * cx + cy * cy + cz * cz) ** 0.5
|
||||
k = acc["wall" if abs(nz) < 1e-6 else "floor"]
|
||||
k[0] += area
|
||||
for d in range(3):
|
||||
k[d + 1] += area * (a[d] + b[d] + c[d]) / 3
|
||||
res = {}
|
||||
for k, (area, sx, sy, sz) in acc.items():
|
||||
res[k + "Area"] = area
|
||||
res[k + "Centroid"] = [sx / area, sy / area, sz / area] if area > 0 else [0.0, 0.0, 0.0]
|
||||
return res
|
||||
|
||||
|
||||
def rooms(rng):
|
||||
m = MapBuilder(rng)
|
||||
# a hall with a sloped platform sector inside (the hall's hole) and a red-wall opening to a sloped east room
|
||||
m.sector([[(0, 0), (4096, 0), (4096, 1024), (4096, 3072), (4096, 4096), (0, 4096)],
|
||||
[(1024, 1024), (1024, 2048), (2048, 2048), (2048, 1024)]], floorz=0, ceilingz=-32768)
|
||||
m.sector([[(4096, 1024), (6144, 1024), (6144, 3072), (4096, 3072)]], floorz=-4096, ceilingz=-24576,
|
||||
floorstat=2, floorheinum=-1024, ceilingstat=2 | 64, ceilingheinum=512, floorxpanning=17)
|
||||
m.sector([[(1024, 1024), (2048, 1024), (2048, 2048), (1024, 2048)]], floorz=-8192, ceilingz=-28672,
|
||||
floorstat=2 | 4 | 16, floorheinum=4096, ceilingstat=8 | 32)
|
||||
m.link()
|
||||
for w in m.walls:
|
||||
if (w["x"], w["y"]) == (4096, 1024) and w["nextsector"] == 1:
|
||||
w["cstat"] |= 16 | 4
|
||||
w["overpicnum"] = 77
|
||||
if w["nextsector"] == 2:
|
||||
w["cstat"] |= 2 | 8
|
||||
m.walls[0]["cstat"] |= 256
|
||||
m.sprite(x=300, y=400, z=0, sectnum=0, cstat=1)
|
||||
m.sprite(x=5000, y=2000, z=-4096, sectnum=1, cstat=16, ang=0)
|
||||
m.sprite(x=1500, y=1500, z=-8192, sectnum=2, cstat=32 | 4, ang=1024)
|
||||
return m
|
||||
|
||||
|
||||
def sky(rng):
|
||||
m = MapBuilder(rng)
|
||||
m.sector([[(0, 0), (2048, 0), (2048, 2048), (0, 2048)]], floorz=0, ceilingz=-16384, ceilingstat=1)
|
||||
m.sector([[(2048, 0), (4096, 0), (4096, 2048), (2048, 2048)]], floorz=1024, ceilingz=-20480, ceilingstat=1)
|
||||
m.link()
|
||||
m.sprite(x=1000, y=1000, z=0, sectnum=0)
|
||||
return m
|
||||
|
||||
|
||||
def yax(rng):
|
||||
m = MapBuilder(rng)
|
||||
m.sector([[(0, 0), (1024, 0), (1024, 1024), (0, 1024)]], floorz=0, ceilingz=-8192, ceilingstat=1024, ceilingxpanning=3)
|
||||
m.sector([[(0, 0), (1024, 0), (1024, 1024), (0, 1024)]], floorz=-8192, ceilingz=-16384, floorstat=1024, floorxpanning=3)
|
||||
m.walls[0]["cstat"] |= 1024
|
||||
m.walls[0]["lotag"] = 4
|
||||
m.walls[5]["cstat"] |= 2048
|
||||
m.walls[5]["extra"] = 0
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(1996)
|
||||
tools = B.tools(ctx)
|
||||
specs = [("rooms", rooms(rng), 7, b""), ("sky", sky(rng), 8, b""), ("yax", yax(rng), 9, b""),
|
||||
("trailing", rooms(rng), 7, b"EXTRA DATA\x00\x01")]
|
||||
maps = []
|
||||
tmp = tempfile.mkdtemp(prefix="rosetta-buildmap-")
|
||||
try:
|
||||
for name, m, version, trailing in specs:
|
||||
data = m.write(version, trailing=trailing)
|
||||
v, t = parse(data)
|
||||
assert v == version
|
||||
e = {"name": name, "data": data, "version": version,
|
||||
"counts": {"sectors": len(t["sector"]), "walls": len(t["wall"]), "sprites": len(t["sprite"])},
|
||||
"sums": {k: {f: sum(r[f] for r in rows) for f, _ in fields} for k, rows, fields in
|
||||
(("sector", t["sector"], SECTOR), ("wall", t["wall"], WALL), ("sprite", t["sprite"], SPRITE))},
|
||||
"loops": [loops_of(t, si) for si in range(len(t["sector"]))], "z": []}
|
||||
for si, s in enumerate(t["sector"]):
|
||||
for w in range(s["wallptr"], s["wallptr"] + s["wallnum"]):
|
||||
x, y = t["wall"][w]["x"], t["wall"][w]["y"]
|
||||
e["z"].append({"sector": si, "x": x, "y": y, "floor": float(slope_z(t, si, True, x, y)),
|
||||
"ceiling": float(slope_z(t, si, False, x, y))})
|
||||
if name != "yax":
|
||||
src, dst = os.path.join(tmp, name + ".map"), os.path.join(tmp, name + ".stl")
|
||||
with open(src, "wb") as f:
|
||||
f.write(m.write(7))
|
||||
subprocess.run([tools["map2stl"], src, dst], capture_output=True, check=True)
|
||||
e["stl"] = stl_stats(open(dst, "rb").read())
|
||||
maps.append(e)
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("buildmap", {"maps": maps})
|
||||
Reference in new issue
Block a user