model/vmf: Hammer VMF read and write (Brush solids with Valve 220 axes, displacements, entities, cameras, visgroups, byte-exact write back, document builders); KeyValues: escapes = "quotes", bare / flat block layout for writing

This commit is contained in:
4DBug committed 2026-11-01 19:15:54 -06:00
1 parent c30e8618fc
commit e4840b719b
17 files changed
+4075 -1443

No files matched your search

+2 -1
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
177 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
178 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 |
@@ -136,6 +136,7 @@ adds each format's capabilities.
| 3D models | stl | .stl | yes | yes |
| 3D models | usda | .usda .usd .usdz | yes | yes |
| 3D models | vbsp | .bsp | yes | - |
| 3D models | vmf | .vmf .vmx | yes | yes |
| 3D models | vox | .vox | yes | yes |
| 3D models | vrml | .wrl .wrz .vrml | yes | yes |
| 3D models | x | .x | yes | - |
+863 -142
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+869 -148
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -92,6 +92,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vbsp | .bsp | yes | - | versions: 19, 20, 21, displacements: true, staticProps: true, pak: true | `tests/model/vbsp.luau` |
| model | vmf | .vmf .vmx | yes | yes | displacements: true, roundTrip: true | `tests/model/vmf.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` |
| model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` |
+27
View File
@@ -471,6 +471,7 @@ Game model formats load as Scenes too, with what games need: skins (joints + inv
| SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames |
| BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - |
| VBSP (Source 19 / 20 / 21) | each model a mesh, a primitive per material, displacements; static props as nodes; lights; entities; the pak lump | - |
| VMF (Hammer, read + write) | a mesh per entity with solids, displacements; point entities as nodes; cameras; visgroups | - |
```luau
local tank = assert(F.model.load(md2Bytes))
@@ -533,6 +534,31 @@ assert(room.meta.entities[1].classname == "worldspawn")
assert(room.meta.pak:read("materials/custom/note.txt"))
```
### Hammer maps (VMF)
`.vmf` sources load like `.map` files: a mesh per entity with solids (Valve 220 texture axes through
`codecs/model/Brush`), displacements tessellated as the compiler does (a brush with a displaced side keeps only its
displaced sides), point entities as nodes (`extras.model` for props), Hammer cameras as cameras. `tools/*` materials
are left out unless `tools = true`; texture sizes come from `textureSizes`, or `materials/<name>.vtf` through
`resolve` and `decodeImage`, else 512 x 512. `meta.entities` holds the keys (outputs under `connections`),
`meta.visgroups`, `meta.groups` and `meta.solids` the editor data, and `meta.vmf` the parsed document, which `F.save`
writes back exactly as Hammer lays it out. `F.format("vmf")` builds documents: `document`, `world`, `box`, `solid`,
`entity`.
```luau
local hammer = assert(F.model.load(vmfText, { format = "vmf" }))
assert(hammer.meta.entities[1].classname == "worldspawn" and hammer.meta.visgroups[1].name == "Walls")
assert(#hammer.cameras == 2)
assert(F.saveString(hammer, { format = "vmf" }) == vmfText) -- unchanged documents write back byte for byte
local Vmf = F.format("vmf")
local doc = Vmf.document({ skyname = "sky_day01_01" })
table.insert(Vmf.world(doc), Vmf.box({ -128, -128, -16 }, { 128, 128, 0 }, "DEV/DEV_MEASUREGENERIC01B"))
Vmf.entity(doc, { { "classname", "info_player_start" }, { "origin", "0 0 8" } })
local built = assert(F.model.load(assert(F.saveString(doc, { format = "vmf" })), { format = "vmf" }))
assert(#built.meshes[1].primitives == 1 and built.meta.entities[2].classname == "info_player_start")
```
## Blitz3D (B3D)
`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS;
@@ -771,6 +797,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` |
| STEP | via the CAD plug-in | | see [cad.md](cad.md) |
| MD2, MD3, MDL, MD5, BSP, VBSP | yes | - | game models and maps: see "Game models" above |
| VMF | yes | yes (round trip, builders) | Hammer maps: see "Hammer maps (VMF)" above |
| SMD | yes | yes | Valve studiomdl data |
| Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) |
| Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) |
+12
View File
@@ -1058,6 +1058,18 @@ local list: { Entry } = {
return require("@rosetta/model/vbsp")
end,
},
{
name = "vmf",
category = "model",
path = "model/vmf",
extensions = { "vmf", "vmx" },
mime = { "model/x-vmf" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" },
caps = { decode = true, encode = true, displacements = true, roundTrip = true },
load = function()
return require("@rosetta/model/vmf")
end,
},
{
name = "vox",
category = "model",
@@ -3,6 +3,8 @@
-- CCoreDispInfo::GenerateDispSurf of the Source SDK 2013 (no code taken): corner 0 is the base face corner nearest the
-- start position, rows run along corner 0 -> 1, columns along 0 -> 3 (the face's own, clockwise, winding), each vertex
-- moved by its offset; the 2^power quads split along alternating diagonals. Normals come from the grid.
local Types = require("@rosetta/Types")
local Displacement = {}
local sqrt = math.sqrt
@@ -102,4 +104,44 @@ function Displacement.surface(corners: { number }, start: { number }, power: num
return { n = n, flat = flat, pos = pos, nrm = nrm, idx = idx }, nil
end
export type Arrays = {
pos: { number },
nrm: { number },
uv: { number },
idx: { number }, -- 0-based
blend: { number }?, -- per vertex 0..1: the _BLEND attribute (displacement alpha)
}
-- flat arrays -> an indexed triangle primitive (POSITION, NORMAL, TEXCOORD_0, _BLEND)
function Displacement.primitive(a: Arrays): Types.Primitive
local writef32, writeu32 = buffer.writef32, buffer.writeu32
local nv, ni = #a.pos // 3, #a.idx
local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4)
for k = 1, nv * 3 do
writef32(pb, (k - 1) * 4, a.pos[k])
writef32(nb, (k - 1) * 4, a.nrm[k])
end
for k = 1, nv * 2 do
writef32(ub, (k - 1) * 4, a.uv[k])
end
for k = 1, ni do
writeu32(ib, (k - 1) * 4, a.idx[k])
end
local S = Types.Scene
local attrs: { [string]: Types.Accessor } = {
POSITION = S.accessor(pb, "f32", 3, nv),
NORMAL = S.accessor(nb, "f32", 3, nv),
TEXCOORD_0 = S.accessor(ub, "f32", 2, nv),
}
local blend = a.blend
if blend then
local bb = buffer.create(nv * 4)
for k = 1, nv do
writef32(bb, (k - 1) * 4, blend[k] or 0)
end
attrs._BLEND = S.accessor(bb, "f32", 1, nv)
end
return { attributes = attrs, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" }
end
return Displacement
@@ -11,6 +11,7 @@ export type Pair = {
key: string,
value: any, -- string | number | Block
cond: string?, -- text: the [$CONDITION] kept when not evaluated
bare: boolean?, -- text: a block whose name was unquoted (written back so with bareBlocks)
type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block)
}
export type Block = { Pair }
+29 -16
View File
@@ -11,7 +11,7 @@ local KeyValues = {}
export type Pair = Binary.Pair
export type Block = Binary.Block
export type ParseOptions = {
escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true
escapes: (boolean | "quotes")?, -- \n \t \\ \" ... in quoted strings, default true; "quotes": only \"
-- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the
-- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with
-- its cond
@@ -20,8 +20,11 @@ export type ParseOptions = {
maxDepth: number?, -- default 256
}
export type WriteOptions = {
escapes: boolean?, -- default true
escapes: (boolean | "quotes")?, -- default true; "quotes": only " is escaped
indent: string?, -- default "\t"
separator: string?, -- between a key and its value, default "\t" (Hammer: " ")
bareBlocks: boolean?, -- block names unquoted when they are plain words (Hammer), default false
flatBlocks: { [string]: boolean }?, -- blocks whose pairs keep the block's own indent (Hammer's dispinfo rows)
}
export type ObjectOptions = {
duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array
@@ -31,7 +34,7 @@ local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true }
local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' }
type Lexer = { s: string, i: number, n: number, escapes: boolean }
type Lexer = { s: string, i: number, n: number, escapes: boolean, quotesOnly: boolean?, quoted: boolean? }
-- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string
local function token(lx: Lexer): (string?, string?, number, string?)
@@ -60,6 +63,7 @@ local function token(lx: Lexer): (string?, string?, number, string?)
lx.i = i + 1
return c, nil, i - 1, nil
elseif c == '"' then
lx.quoted = true
local start = i
i += 1
if not lx.escapes then
@@ -84,7 +88,7 @@ local function token(lx: Lexer): (string?, string?, number, string?)
return "s", table.concat(parts), start - 1, nil
end
local x = string.sub(s, e + 1, e + 1)
local r = ESCAPE[x]
local r = if lx.quotesOnly and x ~= '"' then nil else ESCAPE[x]
if r then
table.insert(parts, r)
i = e + 2
@@ -101,6 +105,7 @@ local function token(lx: Lexer): (string?, string?, number, string?)
return "[", string.sub(s, i + 1, e - 1), i - 1, nil
end
end
lx.quoted = false
local e = string.find(s, '[ \t\r\n\f\v"{}]', i)
local stop = if e then e - 1 else n
lx.i = stop + 1
@@ -145,7 +150,7 @@ end
local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?)
local o: ParseOptions = opts or {}
local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false }
local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false, quotesOnly = o.escapes == "quotes" }
if string.sub(text, 1, 3) == "\239\187\191" then
lx.i = 4
end
@@ -185,6 +190,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl
return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at)
else
local key = v :: string
local keyQuoted = lx.quoted
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
@@ -208,7 +214,7 @@ local function parseText(text: string, opts: ParseOptions?, depth0: number): (Bl
if not pass then
skipping += 1
else
local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond }
local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond, bare = not keyQuoted }
local last = cur[#cur]
if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then
cur[#cur] = pair
@@ -311,7 +317,7 @@ function KeyValues.copy(b: Block): Block
local out: Block = table.create(#b) :: any
for i, p in b do
local v: any = p.value
out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type }
out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type, bare = p.bare }
end
return out
end
@@ -354,18 +360,23 @@ function KeyValues.all(b: Block, key: string): { Pair }
return out
end
local function quote(s: string, escapes: boolean): string
if escapes then
local function quote(s: string, escapes: boolean | string): string
if escapes == "quotes" then
s = string.gsub(s, '"', '\\"')
elseif escapes then
s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" })
end
return '"' .. s .. '"'
end
local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string?
if depth > 256 then
type WriteState = { indent: string, escapes: boolean | string, sep: string, bare: boolean, flat: { [string]: boolean } }
local function writeBlock(b: Block, out: { string }, w: WriteState, level: number, depth: number?): string?
local dp = depth or 0
if dp > 256 then
return "nesting deeper than 256"
end
local pad = string.rep(indent, level)
local pad = string.rep(w.indent, level)
for _, p in b do
if type(p) ~= "table" or type(p.key) ~= "string" then
return "a pair needs a string key"
@@ -373,15 +384,16 @@ local function writeBlock(b: Block, out: { string }, indent: string, level: numb
local v: any = p.value
local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else ""
if type(v) == "table" then
table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n")
local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1)
local name = if w.bare and (p.bare or (p.bare == nil and string.match(p.key, "^[%w_]+$"))) then p.key else quote(p.key, w.escapes)
table.insert(out, pad .. name .. cond .. "\n" .. pad .. "{\n")
local err = writeBlock(v, out, w, if w.flat[p.key] then level else level + 1, dp + 1)
if err then
return err
end
table.insert(out, pad .. "}\n")
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v)
table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n")
table.insert(out, pad .. quote(p.key, w.escapes) .. w.sep .. quote(s, w.escapes) .. cond .. "\n")
else
return "unwritable value for key " .. p.key
end
@@ -394,7 +406,8 @@ function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?)
return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0)
local o: WriteOptions = opts or {}
local err = writeBlock(b, out, { indent = o.indent or "\t", escapes = if o.escapes == nil then true else o.escapes, sep = o.separator or "\t", bare = o.bareBlocks == true, flat = o.flatBlocks or {} }, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
+3 -34
View File
@@ -6,9 +6,7 @@ local Displacement = require("@rosetta/codecs/model/Displacement")
local Faces = {}
local Scene = Types.Scene
local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { buf: buffer, at: number, size: number }
export type Input = {
@@ -216,38 +214,9 @@ function Faces.build(I: Input): ({ Group }?, string?, number?)
end
function Faces.primitive(g: Group, material: number?): Types.Primitive
local nv = #g.pos // 3
local pb, nb, ub = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
for k = 1, nv * 3 do
writef32(pb, (k - 1) * 4, g.pos[k])
writef32(nb, (k - 1) * 4, g.nrm[k])
end
for k = 1, nv * 2 do
writef32(ub, (k - 1) * 4, g.uv[k])
end
local ni = #g.idx
local ib = buffer.create(ni * 4)
for k = 1, ni do
writeu32(ib, (k - 1) * 4, g.idx[k])
end
local attrs: { [string]: Types.Accessor } = {
POSITION = Scene.accessor(pb, "f32", 3, nv),
NORMAL = Scene.accessor(nb, "f32", 3, nv),
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv),
}
if g.blend then
local bb = buffer.create(nv * 4)
for k = 1, nv do
writef32(bb, (k - 1) * 4, g.blend[k] or 0)
end
attrs._BLEND = Scene.accessor(bb, "f32", 1, nv)
end
return {
attributes = attrs,
indices = Scene.accessor(ib, "u32", 1, ni),
mode = "triangles",
material = material,
}
local prim = Displacement.primitive(g)
prim.material = material
return prim
end
return Faces
+422
View File
@@ -0,0 +1,422 @@
--!strict
-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes
-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one
-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras.
local Types = require("@rosetta/Types")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Brush = require("@rosetta/codecs/model/Brush")
local Displacement = require("@rosetta/codecs/model/Displacement")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Build = {}
type Block = KeyValues.Block
export type Side = {
id: number?,
points: { number }, -- 9: the plane's three points
material: string,
uaxis: { number }, -- x, y, z, shift, scale
vaxis: { number },
disp: Block?,
}
export type Solid = { id: number?, sides: { Side }, editor: any, entity: number }
export type Options = {
tools: boolean,
size: (name: string) -> (number, number, boolean),
maxPolygons: number?,
}
local function nums(s: any): { number }
local out: { number } = {}
if type(s) ~= "string" then
return out
end
for w in string.gmatch(s, "[^%s%(%)%[%]]+") do
local n = tonumber(w)
if n then
table.insert(out, n)
end
end
return out
end
Build.nums = nums
local function get(b: Block, key: string): any
return KeyValues.get(b, key)
end
local function editor(b: Block): any
local e = KeyValues.find(b, "editor")
return if e and type(e.value) == "table" then KeyValues.toObject(e.value) else nil
end
function Build.solid(b: Block, entity: number): (Solid?, string?)
local sides: { Side } = {}
for _, p in KeyValues.all(b, "side") do
if type(p.value) == "table" then
local sb = p.value :: Block
local pts = nums(get(sb, "plane"))
if #pts ~= 9 then
return nil, "side without a 3-point plane"
end
local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis"))
local d = KeyValues.find(sb, "dispinfo")
table.insert(sides, {
id = tonumber(get(sb, "id")),
points = pts,
material = tostring(get(sb, "material") or ""),
uaxis = if #u >= 5 then u else { 1, 0, 0, 0, 1 },
vaxis = if #v >= 5 then v else { 0, -1, 0, 0, 1 },
disp = if d and type(d.value) == "table" then d.value :: Block else nil,
})
end
end
return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil
end
function Build.face(s: Side): Brush.Face?
local p = s.points
local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] })
if not plane then
return nil
end
return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) }
end
local function rows(d: Block, name: string, per: number, n: number): { number }?
local blk = KeyValues.get(d, name)
if type(blk) ~= "table" then
return nil
end
local out: { number } = table.create(n * n * per, 0) :: any
for i = 0, n - 1 do
local r = nums(KeyValues.get(blk, "row" .. i))
for k = 1, math.min(#r, n * per) do
out[i * n * per + k] = r[k]
end
end
return out
end
type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number }, blend: { number } }
-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp)
local function displace(s: Side, face: Brush.Face, poly: Brush.Polygon, acc: Acc, w: number, h: number): string?
local d = s.disp :: Block
local power = tonumber(KeyValues.get(d, "power")) or 0
if power < 1 or power > 4 or power % 1 ~= 0 then
return "displacement power " .. tostring(power)
end
local n = 2 ^ power + 1
local start = nums(KeyValues.get(d, "startposition"))
if #start < 3 then
return "displacement without a start position"
end
local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n)
local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n)
local elev = tonumber(KeyValues.get(d, "elevation")) or 0
local pn = face.plane
local offsets: { number } = table.create(n * n * 3, 0) :: any
for k = 0, n * n - 1 do
for c = 1, 3 do
local v = elev * pn[c]
if normals and dists then
v += normals[k * 3 + c] * dists[k + 1]
end
if offs then
v += offs[k * 3 + c]
end
offsets[k * 3 + c] = v
end
end
-- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise
local pts = poly.points
local cw: { number } = {}
for k = #pts // 3 - 1, 0, -1 do
table.insert(cw, pts[k * 3 + 1])
table.insert(cw, pts[k * 3 + 2])
table.insert(cw, pts[k * 3 + 3])
end
local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] })
if not surf then
return err
end
local base = #acc.pos // 3
for k = 0, n * n - 1 do
local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3]
for c = 1, 3 do
table.insert(acc.pos, surf.pos[k * 3 + c])
table.insert(acc.nrm, surf.nrm[k * 3 + c])
end
local u, v = Brush.uv(face, x, y, z, w, h)
table.insert(acc.uv, u)
table.insert(acc.uv, v)
table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1))
end
for _, i in surf.idx do
table.insert(acc.idx, base + i)
end
return nil
end
local function isTool(name: string): boolean
return string.sub(string.lower(name), 1, 6) == "tools/"
end
-- the solids of one entity -> its primitives (material indices by name through matOf)
function Build.mesh(solids: { Solid }, o: Options, matOf: (string) -> number, name: string): (Types.Mesh?, string?)
local brushes: { { Brush.Face } } = {}
local sideOf: { { Side } } = {}
local hasDisp: { boolean } = {}
for _, s in solids do
local faces: { Brush.Face } = {}
local sides: { Side } = {}
local disp = false
for _, sd in s.sides do
local f = Build.face(sd)
if f then
table.insert(faces, f)
table.insert(sides, sd)
disp = disp or sd.disp ~= nil
end
end
if #faces >= 4 then
table.insert(brushes, faces)
table.insert(sideOf, sides)
table.insert(hasDisp, disp)
end
end
local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons })
if not polys then
return nil, perr
end
local keep: { Brush.Polygon } = {}
local disps: { [string]: Acc } = {}
local dispOrder: { string } = {}
for _, p in polys do
local sd = sideOf[p.brush][p.face]
if o.tools or not isTool(sd.material) then
if sd.disp then
local acc = disps[sd.material]
if not acc then
acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} }
disps[sd.material] = acc
table.insert(dispOrder, sd.material)
end
local w, h = o.size(sd.material)
local err = displace(sd, brushes[p.brush][p.face], p, acc :: Acc, w, h)
if err then
return nil, err
end
elseif not hasDisp[p.brush] then
table.insert(keep, p)
end
end
end
local mesh: Types.Mesh = { name = name, primitives = {} }
local function size(n: string): (number, number)
local w, h = o.size(n)
return w, h
end
for _, b in Brush.primitives(keep, brushes, size) do
b.primitive.material = matOf(b.texture)
table.insert(mesh.primitives, b.primitive)
end
for _, m in dispOrder do
local prim = Displacement.primitive(disps[m] :: any)
prim.material = matOf(m)
table.insert(mesh.primitives, prim)
end
return mesh, nil
end
local function quat(p: number, y: number, r: number): { number }
return Mat4.quat(Mat4.euler(r, p, y, "xyz"))
end
-- a camera at position looking at look, z up: glTF cameras look along -z with +y up
local function lookAt(pos: { number }, look: { number }): { number }
local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3]
local l = math.sqrt(fx * fx + fy * fy + fz * fz)
if l < 1e-9 then
return { 0, 0, 0, 1 }
end
fx, fy, fz = fx / l, fy / l, fz / l
local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1)
local rl = math.sqrt(rx * rx + ry * ry)
if rl < 1e-9 then
rx, ry, rl = 1, 0, 1
end
rx, ry = rx / rl, ry / rl
local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f
return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 })
end
local function visgroups(b: Block): { any }
local out = {}
for _, p in KeyValues.all(b, "visgroup") do
if type(p.value) == "table" then
local v = p.value :: Block
table.insert(out, {
name = KeyValues.get(v, "name"),
id = tonumber(KeyValues.get(v, "visgroupid")),
color = KeyValues.get(v, "color"),
children = visgroups(v),
})
end
end
return out
end
-- solids of a block, including those inside its hidden { } blocks
local function solidsOf(b: Block, entity: number, out: { Solid }): string?
for _, p in b do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "solid" then
local s, err = Build.solid(p.value :: Block, entity)
if not s then
return err
end
table.insert(out, s)
elseif k == "hidden" then
local err = solidsOf(p.value :: Block, entity, out)
if err then
return err
end
end
end
end
return nil
end
function Build.scene(doc: Block, o: Options): (Types.Scene?, string?)
local scene = Types.Scene.new()
scene.meta.up = "z"
scene.meta.unit = 0.0254
local mats: { [string]: number } = {}
local function matOf(name: string): number
local m = mats[name]
if m then
return m
end
local w, h, known = o.size(name)
local path = "materials/" .. string.lower((string.gsub(name, "\\", "/")))
table.insert(scene.textures, { name = name, uri = path .. ".vtf" })
local mat = Types.Scene.material(name)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } }
table.insert(scene.materials, mat)
mats[name] = #scene.materials
return #scene.materials
end
local root: Types.Node = { name = "vmf", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local ents: { any } = {}
local solidsMeta: { any } = {}
local groups: { any } = {}
-- world and entities, hidden ones included
local blocks: { { key: string, block: Block } } = {}
for _, p in doc do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "world" or k == "entity" then
table.insert(blocks, { key = k, block = p.value :: Block })
elseif k == "hidden" then
for _, q in KeyValues.all(p.value :: Block, "entity") do
if type(q.value) == "table" then
table.insert(blocks, { key = "entity", block = q.value :: Block })
end
end
end
end
end
for _, item in blocks do
local b = item.block
local keys: Block = {}
local conns: any = nil
for _, p in b do
if type(p.value) == "string" then
table.insert(keys, p)
elseif string.lower(p.key) == "connections" then
conns = KeyValues.toObject(p.value :: Block)
elseif item.key == "world" and string.lower(p.key) == "group" then
local g = p.value :: Block
table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) })
end
end
local e = KeyValues.toObject(keys)
if conns then
e.connections = conns
end
table.insert(ents, e)
local ei = #ents
local solids: { Solid } = {}
local serr = solidsOf(b, ei, solids)
if serr then
return nil, serr
end
local class = if type(e.classname) == "string" then e.classname else item.key
local name = if item.key == "world" then "world" elseif type(e.targetname) == "string" then e.targetname else class
local node: Types.Node = { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } }
if #solids > 0 then
local mesh, merr = Build.mesh(solids, o, matOf, name)
if not mesh then
return nil, merr
end
if #mesh.primitives > 0 then
table.insert(scene.meshes, mesh)
node.mesh = #scene.meshes
end
for _, s in solids do
table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor })
end
else
local org = nums(e.origin)
if #org >= 3 then
node.translation = { org[1], org[2], org[3] }
end
local ang = nums(e.angles)
if #ang >= 3 then
node.rotation = quat(ang[1], ang[2], ang[3])
end
if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then
(node.extras :: any).model = e.model
end
end
if node.mesh or item.key ~= "world" then
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
end
-- cameras
local cams = KeyValues.get(doc, "cameras")
local camMeta: any = nil
if type(cams) == "table" then
camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} }
for _, p in KeyValues.all(cams, "camera") do
if type(p.value) == "table" then
local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look"))
if #pos >= 3 and #look >= 3 then
local cam: Types.Camera = { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 }
table.insert(scene.cameras, cam)
table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) })
table.insert(root.children, #scene.nodes)
table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } })
end
end
end
end
local vg = KeyValues.get(doc, "visgroups")
scene.meta.entities = ents
scene.meta.solids = solidsMeta
scene.meta.groups = groups
scene.meta.visgroups = if type(vg) == "table" then visgroups(vg) else {}
scene.meta.cameras = camMeta
return scene, nil
end
return Build
+323
View File
@@ -0,0 +1,323 @@
--!strict
-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush
-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement,
-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in
-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from
-- opts.textureSizes, materials/<name>.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances
-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Build = require("@rosetta/model/vmf/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Vmf = {
name = "vmf",
category = "model",
extensions = { "vmf", "vmx" },
mime = { "model/x-vmf" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" },
caps = { decode = true, encode = true, displacements = true, roundTrip = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
tools: boolean?, -- keep tools/* materials (nodraw, clip, trigger, skybox, ...), default false
textureSizes: { [string]: { number } }?, -- material name -> { width, height }
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
decodeImage: ((buf: buffer) -> any)?,
maxPolygons: number?, -- default 2^20
}
export type EncodeOptions = {}
export type SideSpec = {
points: { { number } }, -- three points, clockwise seen from outside (Hammer)
material: string?,
uaxis: { number }?, -- x, y, z, shift, scale; default from the face's dominant axis
vaxis: { number }?,
rotation: number?,
lightmapscale: number?,
}
-- ------------------------------------------------------------------------------------------------ sniff
function Vmf.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 512, true)
if string.find(head, "%z") then
return 0
end
if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then
return 0.9
end
if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function sizer(opts: DecodeOptions?): (string) -> (number, number, boolean)
local cache: { [string]: { number } } = {}
return function(name: string): (number, number, boolean)
local c = cache[name]
if c then
return c[1], c[2], c[3] == 1
end
local w, h, known = 512, 512, false
local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)])
if given and type(given[1]) == "number" and type(given[2]) == "number" then
w, h, known = given[1], given[2], true
elseif opts and opts.decodeImage then
local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf")
if data then
local ok, img = pcall(opts.decodeImage :: any, data)
if ok and type(img) == "table" and type(img.width) == "number" then
w, h, known = img.width, img.height, true
end
end
end
cache[name] = { w, h, if known then 1 else 0 }
return w, h, known
end
end
function Vmf.parse(src: buffer | string): (KeyValues.Block?, Err.Err?)
return KeyValues.parse(src, { escapes = "quotes", defines = false })
end
function Vmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base))
if not doc then
return nil, err
end
local scene, msg = Build.scene(doc, {
tools = opts ~= nil and opts.tools == true,
size = sizer(opts),
maxPolygons = opts and opts.maxPolygons,
})
if not scene then
return nil, Err.from(msg)
end
local vi = KeyValues.get(doc, "versioninfo")
local info: any = if type(vi) == "table" then KeyValues.toObject(vi) else {}
scene.meta.vmf = doc
scene.meta.source = {
format = "vmf",
editorVersion = tonumber(info.editorversion),
editorBuild = tonumber(info.editorbuild),
mapVersion = tonumber(info.mapversion),
formatVersion = tonumber(info.formatversion),
prefab = info.prefab == "1",
}
return scene, nil
end
-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world)
function Vmf.brushes(doc: KeyValues.Block): ({ { id: number?, entity: number, faces: { any }, materials: { string } } }?, Err.Err?)
local out = {}
local entity = 0
local function walk(b: KeyValues.Block): string?
for _, p in b do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "solid" then
local s, err = Build.solid(p.value :: KeyValues.Block, entity)
if not s then
return err
end
local faces, mats = {}, {}
for _, sd in s.sides do
local f = Build.face(sd)
if f then
table.insert(faces, f)
table.insert(mats, sd.material)
end
end
table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats })
elseif k == "hidden" then
local err = walk(p.value :: KeyValues.Block)
if err then
return err
end
end
end
end
return nil
end
for _, p in doc do
local k = string.lower(p.key)
if type(p.value) == "table" and (k == "world" or k == "entity") then
entity += 1
local err = walk(p.value :: KeyValues.Block)
if err then
return nil, Err.new(Err.CORRUPT, err)
end
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- Hammer writes dispinfo rows at their block's own indent
local FLAT: { [string]: boolean } = {}
for _, k in { "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" } do
FLAT[k] = true
end
function Vmf.encode(value: any, _opts: EncodeOptions?): (buffer?, Err.Err?)
local doc = value
if type(value) == "table" and value.kind == "scene" then
doc = value.meta and value.meta.vmf
if type(doc) ~= "table" then
return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written")
end
end
if type(doc) ~= "table" then
return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document")
end
local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT })
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function fmt(x: number): string
if x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("%d", x)
end
return (string.gsub(string.format("%.6f", x), "%.?0+$", ""))
end
local function kv(k: string, v: string): KeyValues.Pair
return { key = k, value = v }
end
-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls)
local function defaultAxes(points: { { number } }): ({ number }, { number })
local a, b, c = points[1], points[2], points[3]
local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3]
local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3]
local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx)
if nz >= nx and nz >= ny then
return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 }
elseif nx >= ny then
return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 }
end
return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 }
end
local function id(given: number?, default: number): string
return fmt(given or default)
end
function Vmf.side(s: SideSpec, sideId: number?): KeyValues.Pair
local p = s.points
local du, dv = defaultAxes(p)
local u, v = s.uaxis or du, s.vaxis or dv
local function axis(x: { number }): string
return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25)
end
local function pt(x: { number }): string
return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")"
end
return { key = "side", value = {
kv("id", id(sideId, 1)),
kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])),
kv("material", s.material or "TOOLS/TOOLSNODRAW"),
kv("uaxis", axis(u)),
kv("vaxis", axis(v)),
kv("rotation", fmt(s.rotation or 0)),
kv("lightmapscale", fmt(s.lightmapscale or 16)),
kv("smoothing_groups", "0"),
} }
end
function Vmf.solid(sides: { SideSpec }, solidId: number?): KeyValues.Pair
local blk: KeyValues.Block = { kv("id", id(solidId, 1)) }
for i, s in sides do
table.insert(blk, Vmf.side(s, i))
end
table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } })
return { key = "solid", value = blk }
end
-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north,
-- south)
function Vmf.box(lo: { number }, hi: { number }, material: string | { string }, solidId: number?): KeyValues.Pair
local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]
local function m(i: number): string
return if type(material) == "table" then material[i] or material[1] else material
end
return Vmf.solid({
{ points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) },
{ points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) },
{ points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) },
{ points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) },
{ points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) },
{ points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) },
}, solidId)
end
-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons
function Vmf.document(worldKeys: { [string]: string }?): KeyValues.Block
local world: KeyValues.Block = { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") }
if worldKeys then
local keys = {}
for k in worldKeys do
table.insert(keys, k)
end
table.sort(keys)
for _, k in keys do
table.insert(world, kv(k, worldKeys[k]))
end
end
return {
{ key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } },
{ key = "visgroups", value = {} },
{ key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } },
{ key = "world", value = world },
{ key = "cameras", value = { kv("activecamera", "-1") } },
{ key = "cordons", value = { kv("active", "0") } },
}
end
-- an entity block (keys in the given order, then its solids) appended to doc before cameras
function Vmf.entity(doc: KeyValues.Block, keys: { { string } }, solids: { KeyValues.Pair }?): KeyValues.Pair
local count = 1
for _, p in doc do
if string.lower(p.key) == "entity" then
count += 1
end
end
local blk: KeyValues.Block = { kv("id", id(nil, count + 1)) }
for _, k in keys do
table.insert(blk, kv(k[1], k[2]))
end
for _, s in solids or {} do
table.insert(blk, s)
end
local pair = { key = "entity", value = blk }
local at = #doc + 1
for i, p in doc do
if string.lower(p.key) == "cameras" then
at = i
break
end
end
table.insert(doc, at, pair)
return pair
end
-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...)))
function Vmf.world(doc: KeyValues.Block): KeyValues.Block?
local w = KeyValues.get(doc, "world")
return if type(w) == "table" then w else nil
end
return Vmf
+223
View File
@@ -0,0 +1,223 @@
-- model/vmf tests: srctools' Hammer-written test VMFs (solid polygons against srctools.geometry, byte-exact write
-- back), a generated room (displacement floor equal to tools/fixtures/vbsp.py's, outputs, visgroups, cameras, hidden
-- solids, a prop_static), the document builders, errors and the fuzz pass. Fixtures: tools/fixtures/vmf.py.
local T = require("@tests/T")
local Vmf = require("@rosetta/model/vmf")
local Vbsp = require("@rosetta/model/vbsp")
local Brush = require("@rosetta/codecs/model/Brush")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/vmf")
local VbspFx = require("@tests/gen/vbsp")
local t = T.suite("vmf")
t:eq(Vmf.name, "vmf", "name")
t:check(Vmf.caps.decode and Vmf.caps.encode, "caps")
local function f2(x: number): string
local s = string.format("%.2f", x)
return if s == "-0.00" then "0.00" else s
end
local function canonOf(faces: { any }): string
local polys = Brush.polygons({ faces }) :: { Brush.Polygon }
local out = {}
for _, p in polys do
local pts = {}
for k = 0, #p.points // 3 - 1 do
table.insert(pts, f2(p.points[k * 3 + 1]) .. " " .. f2(p.points[k * 3 + 2]) .. " " .. f2(p.points[k * 3 + 3]))
end
table.sort(pts)
table.insert(out, table.concat(pts, ";"))
end
table.sort(out)
return table.concat(out, "|")
end
local function solidCanons(doc: any): { string }
local list = {}
for _, s in Vmf.brushes(doc) :: { any } do
table.insert(list, canonOf(s.faces))
end
table.sort(list)
return list
end
local function dec(data: string, opts: any?): (Types.Scene?, Err.Err?)
return Vmf.decode(Bytes.reader(buffer.fromstring(data)), opts)
end
for _, c in Fx.files do
local scene, err = dec(c.data, { tools = true })
t:check(scene ~= nil, c.name .. ": " .. tostring(err))
if scene then
local want = table.clone(c.solids)
table.sort(want)
t:eq(table.concat(solidCanons(scene.meta.vmf), "\n"), table.concat(want, "\n"), c.name .. ": solids as srctools.geometry")
t:eq(buffer.tostring(Vmf.encode(scene) :: buffer), c.data, c.name .. ": written back byte for byte")
local tris, polys = 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
tris += (p.indices :: Types.Accessor).count // 3
end
end
for _, s in c.solids do
for poly in string.gmatch(s, "[^|]+") do
local _, corners = string.gsub(poly, ";", "")
polys += corners - 1
end
end
if not string.find(c.data, "dispinfo", 1, true) then
t:eq(tris, polys, c.name .. ": triangles = corners - 2 per polygon")
else
t:eq(tris, 128, c.name .. ": a power-3 displacement replaces its brush")
end
end
end
do
local R = Fx.room
local scene = dec(R.data) :: Types.Scene
t:check(scene ~= nil, "room decodes")
t:eq(#scene.meta.entities, R.entities, "room: entities as srctools")
local outputs = 0
for _, e in scene.meta.entities do
if e.connections then
for _, k in Types.keys(e.connections) do
local v = e.connections[k]
outputs += if type(v) == "table" then #v else 1
end
end
end
t:eq(outputs, R.outputs, "room: outputs as srctools")
local names = {}
local function walk(list: { any })
for _, v in list do
table.insert(names, v.name)
walk(v.children)
end
end
walk(scene.meta.visgroups)
table.sort(names)
t:eq(table.concat(names, ","), table.concat(R.visgroups, ","), "room: nested visgroups")
t:eq(#scene.cameras, R.cameras, "room: cameras")
t:eq(scene.meta.cameras.active, 0, "room: active camera")
t:eq(#scene.meta.groups, 1, "room: group")
local want = table.clone(R.solids)
table.sort(want)
t:eq(table.concat(solidCanons(scene.meta.vmf), "\n"), table.concat(want, "\n"), "room: solids (hidden one included) as srctools")
t:eq(buffer.tostring(Vmf.encode(scene) :: buffer), R.data, "room: written back byte for byte")
-- the displacement floor
local disp: Types.Primitive? = nil
local nodraw = false
for _, m in scene.meshes do
for _, p in m.primitives do
if p.attributes._BLEND then
disp = p
end
if string.find(scene.materials[p.material :: number].name :: string, "TOOLS", 1, true) then
nodraw = true
end
end
end
t:check(not nodraw, "room: tool materials left out")
t:check(disp ~= nil, "room: displacement")
local function positions(p: Types.Primitive): string
local P = p.attributes.POSITION
local out = {}
for i = 0, P.count - 1 do
table.insert(out, f2(buffer.readf32(P.data, i * 12)) .. " " .. f2(buffer.readf32(P.data, i * 12 + 4)) .. " " .. f2(buffer.readf32(P.data, i * 12 + 8)))
end
table.sort(out)
return table.concat(out, "\n")
end
if disp then
t:eq(positions(disp), R.disp, "room: displacement grid")
local b = Vbsp.decode(Bytes.reader(buffer.fromstring(VbspFx.cases[1].data))) :: Types.Scene
for _, m in b.meshes do
for _, p in m.primitives do
if p.attributes._BLEND then
t:eq(positions(p), positions(disp), "room: the same surface as the compiled map's displacement")
end
end
end
end
local prop, cam
for _, n in scene.nodes do
if n.extras and (n.extras :: any).model then
prop = n
end
if n.camera == 1 then
cam = n
end
end
t:check(prop and prop.translation and prop.translation[1] == 64 and (prop.extras :: any).vmf.classname == "prop_static", "room: prop_static node")
t:check(cam ~= nil and cam.rotation ~= nil, "room: camera node")
if cam then
-- the camera's -z looks at [0 0 64]
local q = cam.rotation :: { number }
local x, y, z, w = q[1], q[2], q[3], q[4]
local fx = -(2 * (x * z + w * y))
local fy = -(2 * (y * z - w * x))
local fz = -(1 - 2 * (x * x + y * y))
local dx, dy, dz = 200, 200, -64
local l = math.sqrt(dx * dx + dy * dy + dz * dz)
t:check(math.abs(fx - dx / l) + math.abs(fy - dy / l) + math.abs(fz - dz / l) < 1e-6, "room: camera looks at its target")
end
t:eq(scene.meta.source.editorBuild, 8864, "versioninfo")
end
do
-- builders
local doc = Vmf.document({ skyname = "sky_day01_01" })
table.insert(Vmf.world(doc) :: any, Vmf.box({ -64, -64, 0 }, { 64, 64, 16 }, "DEV/DEV_MEASUREGENERIC01B"))
Vmf.entity(doc, { { "classname", "func_detail" } }, { Vmf.box({ 0, 0, 16 }, { 32, 32, 48 }, "BRICK/BRICKWALL001A") })
Vmf.entity(doc, { { "classname", "info_player_start" }, { "origin", "0 0 17" } })
local text = buffer.tostring(Vmf.encode(doc) :: buffer)
local scene = dec(text, { textureSizes = { ["DEV/DEV_MEASUREGENERIC01B"] = { 128, 128 } } }) :: Types.Scene
t:check(scene ~= nil, "built document decodes")
t:eq(#scene.meta.entities, 3, "world + 2 entities")
t:eq(string.sub(text, 1, 12), "versioninfo\n", "Hammer layout")
local ok = true
for _, s in Vmf.brushes(scene.meta.vmf) :: { any } do
local polys = Brush.polygons({ s.faces }) :: { Brush.Polygon }
ok = ok and #polys == 6
for _, p in polys do
-- outward: the normal points away from the brush centre
local cx, cy, cz = 0, 0, 0
for _, q in polys do
cx += q.points[1]
cy += q.points[2]
cz += q.points[3]
end
cx, cy, cz = cx / 6, cy / 6, cz / 6
ok = ok and (p.points[1] - cx) * p.normal[1] + (p.points[2] - cy) * p.normal[2] + (p.points[3] - cz) * p.normal[3] > -1e-9
end
end
t:check(ok, "boxes: 6 outward faces")
local mat = scene.materials[1]
t:eq((mat.extras :: any).vmf.width, 128, "textureSizes")
local P = scene.meshes[1].primitives[1].attributes.TEXCOORD_0
local maxU = 0
for i = 0, P.count - 1 do
maxU = math.max(maxU, math.abs(buffer.readf32(P.data, i * 8)))
end
t:check(math.abs(maxU - 2) < 1e-6, "Valve 220 UVs: 64 units / 0.25 scale / 128 texels")
local _, e1 = dec('world\n{\n\tsolid\n\t{\n\t\tside\n\t\t{\n\t\t\t"plane" "(0 0 0) (1 1)"\n\t\t}\n\t}\n}\n')
t:eq(e1 and e1.code, Err.CORRUPT, "bad plane")
local _, e2 = dec("world\n{\n")
t:eq(e2 and e2.code, Err.TRUNCATED, "truncated")
local _, e3 = Vmf.encode({ kind = "scene", meta = {} })
t:eq(e3 and e3.code, Err.ARG, "a Scene without meta.vmf")
t:check(Vmf.sniff(Bytes.reader(buffer.fromstring(Fx.room.data))) > 0.5, "sniff")
end
local samples = { Fx.room.data }
for i = 1, 3 do
table.insert(samples, Fx.files[i].data)
end
t:fuzz("decode", function(b: buffer)
return Vmf.decode(Bytes.reader(b))
end, samples)
t:done()
+6 -4
View File
@@ -1,9 +1,10 @@
# Docs inputs for the Source engine sections of the scene page (tools/fixtures.py; tools/docs_check.py explains the
# inputs): the CS:GO-style VBSP of tools/fixtures/vbsp.py (srctools-saved, static props v11).
# tests/gen/docs_source.luau { files = { [name] = bytes }, vars = { vbspBytes = "room.bsp", ... } }
# inputs): the CS:GO-style VBSP of tools/fixtures/vbsp.py (srctools-saved, static props v11) and the Hammer VMF of
# tools/fixtures/vmf.py.
# tests/gen/docs_source.luau { files = { [name] = bytes }, vars = { vbspBytes = "room.bsp", vmfText = "room.vmf" } }
import importlib.util, json, os
INPUTS = ["tools/docs_check.py", "tools/fixtures/vbsp.py"]
INPUTS = ["tools/docs_check.py", "tools/fixtures/vbsp.py", "tools/fixtures/vmf.py"]
def mod(ctx, name):
@@ -16,4 +17,5 @@ def mod(ctx, name):
def generate(ctx):
res = json.loads(ctx.python(["srctools"], mod(ctx, "vbsp").CODE))
files = {"room.bsp": next(bytes.fromhex(c["data"]) for c in res["cases"] if c["name"] == "csgo")}
mod(ctx, "docs_check").emit_inputs(ctx, files, {"vbspBytes": "room.bsp"})
files["room.vmf"] = mod(ctx, "vmf").room().encode()
mod(ctx, "docs_check").emit_inputs(ctx, files, {"vbspBytes": "room.bsp", "vmfText": "room.vmf"})
+150
View File
@@ -0,0 +1,150 @@
# model/vmf fixtures: the Hammer-written VMFs of srctools' test suite (MIT; read from the nix srctools source, not
# committed) with every solid's polygons as srctools.geometry clips them, and a VMF written here in Hammer's layout
# (a room whose floor is the power-3 displacement of tools/fixtures/vbsp.py, a func_detail, a prop_static, outputs,
# nested visgroups, a group, cameras, hidden objects) with what srctools.vmf reads from it.
# tests/gen/vmf.luau { files = { { name, data, solids = { canon } } }, room = { data, entities, outputs, visgroups,
# cameras, solids, disp } }
# canon: a solid's polygons, each its corners "%.2f %.2f %.2f" sorted and joined by ";", sorted and joined by "|".
import json, math, os, subprocess, tarfile
CODE = r'''
import json, sys
from srctools.vmf import VMF
from srctools.keyvalues import Keyvalues
from srctools.geometry import Geometry
_out, sys.stdout = sys.stdout, sys.stderr
inp = json.loads(sys.stdin.read())
def f2(x):
s = "%.2f" % x
return "0.00" if s == "-0.00" else s
def canon(solid):
polys = []
for p in Geometry.from_brush(solid).polys:
polys.append(";".join(sorted("%s %s %s" % (f2(v.x), f2(v.y), f2(v.z)) for v in p.vertices)))
return "|".join(sorted(polys))
res = {"files": [], "room": None}
for name, text in inp["files"]:
vmf = VMF.parse(Keyvalues.parse(text))
solids = [canon(s) for s in vmf.brushes] + [canon(s) for e in vmf.entities for s in e.solids]
res["files"].append({"name": name, "solids": solids})
vmf = VMF.parse(Keyvalues.parse(inp["room"]))
ents = [vmf.spawn] + list(vmf.entities)
def visnames(tree):
out = []
for v in tree:
out.append(v.name)
out += visnames(v.child_groups)
return out
res["room"] = {
"entities": len(ents),
"outputs": sum(len(e.outputs) for e in ents),
"visgroups": sorted(visnames(vmf.vis_tree)),
"cameras": len(vmf.cameras),
"solids": sorted(canon(s) for s in list(vmf.brushes) + [s for e in vmf.entities for s in e.solids]),
}
_out.write(json.dumps(res))
'''
S, H = 256, 256
def side(i, a, b, c, mat, u, v, extra=""):
return ('\t\tside\n\t\t{\n\t\t\t"id" "%d"\n\t\t\t"plane" "(%g %g %g) (%g %g %g) (%g %g %g)"\n\t\t\t"material" "%s"\n'
'\t\t\t"uaxis" "[%g %g %g 0] 0.25"\n\t\t\t"vaxis" "[%g %g %g 0] 0.25"\n\t\t\t"rotation" "0"\n'
'\t\t\t"lightmapscale" "16"\n\t\t\t"smoothing_groups" "0"\n%s\t\t}\n') % (i, *a, *b, *c, mat, *u, *v, extra)
def box(sid, lo, hi, mat, top=None, extra_top=""):
(x0, y0, z0), (x1, y1, z1) = lo, hi
m = lambda k: top if (k == 0 and top) else mat
sides = [
side(sid + 1, (x0, y1, z1), (x1, y1, z1), (x1, y0, z1), m(0), (1, 0, 0), (0, -1, 0), extra_top),
side(sid + 2, (x0, y0, z0), (x1, y0, z0), (x1, y1, z0), mat, (1, 0, 0), (0, -1, 0)),
side(sid + 3, (x0, y1, z0), (x0, y1, z1), (x0, y0, z1), mat, (0, 1, 0), (0, 0, -1)),
side(sid + 4, (x1, y0, z0), (x1, y0, z1), (x1, y1, z1), mat, (0, 1, 0), (0, 0, -1)),
side(sid + 5, (x1, y1, z0), (x1, y1, z1), (x0, y1, z1), mat, (1, 0, 0), (0, 0, -1)),
side(sid + 6, (x0, y0, z0), (x0, y0, z1), (x1, y0, z1), mat, (1, 0, 0), (0, 0, -1)),
]
return '\tsolid\n\t{\n\t\t"id" "%d"\n%s\t\teditor\n\t\t{\n\t\t\t"color" "0 180 0"\n\t\t\t"visgroupid" "2"\n\t\t\t"groupid" "40"\n\t\t\t"visgroupshown" "1"\n\t\t\t"visgroupautoshown" "1"\n\t\t}\n\t}\n' % (sid, "".join(sides))
def dispinfo():
power = 3
n = 2 ** power + 1
rows = lambda f, ind="\t\t\t\t": "".join('%s"row%d" "%s"\n' % (ind, i, " ".join(f(i, j) for j in range(n))) for i in range(n))
dist = lambda i, j: 24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8
out = ('\t\t\tdispinfo\n\t\t\t{\n\t\t\t\t"power" "3"\n\t\t\t\t"startposition" "[%g %g 0]"\n\t\t\t\t"flags" "0"\n'
'\t\t\t\t"elevation" "0"\n\t\t\t\t"subdiv" "0"\n') % (-S, S)
out += "\t\t\t\tnormals\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 1" if dist(i, j) >= 0 else "0 0 -1", "\t\t\t\t") + "\t\t\t\t}\n"
out += "\t\t\t\tdistances\n\t\t\t\t{\n" + rows(lambda i, j: "%.9g" % abs(dist(i, j)), "\t\t\t\t") + "\t\t\t\t}\n"
out += "\t\t\t\toffsets\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 0", "\t\t\t\t") + "\t\t\t\t}\n"
out += "\t\t\t\toffset_normals\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 1", "\t\t\t\t") + "\t\t\t\t}\n"
out += "\t\t\t\talphas\n\t\t\t\t{\n" + rows(lambda i, j: "%d" % ((i * 31 + j * 7) % 256), "\t\t\t\t") + "\t\t\t\t}\n"
out += '\t\t\t\tallowed_verts\n\t\t\t\t{\n\t\t\t\t"10" "-1 -1 -1 -1 -1 -1 -1 -1 -1 -1"\n\t\t\t\t}\n\t\t\t}\n'
return out
def room():
world = ""
world += box(10, (-S, -S, -16), (S, S, 0), "TOOLS/TOOLSNODRAW", top="NATURE/BLENDGRASSDIRT", extra_top=dispinfo())
world += box(20, (-S, -S - 16, 0), (S, -S, H), "BRICK/BRICKWALL001A")
world += box(30, (-S, S, 0), (S, S + 16, H), "BRICK/BRICKWALL001A")
hidden = box(40, (S, -S, 0), (S + 16, S, H), "BRICK/BRICKWALL001A")
hidden = "\thidden\n\t{\n" + "\n".join("\t" + l if l else l for l in hidden.split("\n")) + "\t}\n"
detail = box(50, (-16, -16, 0), (16, 16, 32), "BRICK/BRICKWALL001A").replace("\n\t", "\n").replace("\tsolid", "solid", 1)
detail = "\n".join("\t" + l if l else l for l in detail.split("\n"))
text = ('versioninfo\n{\n\t"editorversion" "400"\n\t"editorbuild" "8864"\n\t"mapversion" "3"\n\t"formatversion" "100"\n\t"prefab" "0"\n}\n'
'visgroups\n{\n\tvisgroup\n\t{\n\t\t"name" "Walls"\n\t\t"visgroupid" "1"\n\t\t"color" "200 100 0"\n\t\tvisgroup\n\t\t{\n'
'\t\t\t"name" "North"\n\t\t\t"visgroupid" "2"\n\t\t\t"color" "0 100 200"\n\t\t}\n\t}\n}\n'
'viewsettings\n{\n\t"bSnapToGrid" "1"\n\t"bShowGrid" "1"\n\t"nGridSpacing" "16"\n}\n'
'world\n{\n\t"id" "1"\n\t"mapversion" "3"\n\t"classname" "worldspawn"\n\t"skyname" "sky_day01_01"\n'
+ world + hidden +
'\tgroup\n\t{\n\t\t"id" "40"\n\t\teditor\n\t\t{\n\t\t\t"color" "0 180 0"\n\t\t\t"visgroupshown" "1"\n\t\t\t"visgroupautoshown" "1"\n\t\t}\n\t}\n}\n'
'entity\n{\n\t"id" "60"\n\t"classname" "func_detail"\n' + detail + '}\n'
'entity\n{\n\t"id" "70"\n\t"classname" "prop_static"\n\t"angles" "0 45 0"\n\t"model" "models/props_junk/wood_crate001a.mdl"\n'
'\t"skin" "0"\n\t"origin" "64 32 0"\n\teditor\n\t{\n\t\t"color" "255 255 0"\n\t\t"visgroupshown" "1"\n\t\t"visgroupautoshown" "1"\n'
'\t\t"logicalpos" "[0 0]"\n\t}\n}\n'
'entity\n{\n\t"id" "80"\n\t"classname" "logic_relay"\n\t"targetname" "relay"\n\tconnections\n\t{\n'
'\t\t"OnTrigger" "door,Open,,0,-1"\n\t\t"OnTrigger" "door,Close,,5,-1"\n\t\t"OnSpawn" "relay,Trigger,,1,1"\n\t}\n'
'\t"origin" "0 0 128"\n}\n'
'entity\n{\n\t"id" "90"\n\t"classname" "info_player_start"\n\t"angles" "0 90 0"\n\t"origin" "-128 0 8"\n}\n'
'cameras\n{\n\t"activecamera" "0"\n\tcamera\n\t{\n\t\t"position" "[-200 -200 128]"\n\t\t"look" "[0 0 64]"\n\t}\n'
'\tcamera\n\t{\n\t\t"position" "[200 0 64]"\n\t\t"look" "[0 0 64]"\n\t}\n}\n'
'cordons\n{\n\t"active" "0"\n}\n')
return text
def disp_expected():
# tools/fixtures/vbsp.py: the floor corners clockwise from above, corner 0 nearest the start
power, n = 3, 9
p = [(-S, S, 0), (S, S, 0), (S, -S, 0), (-S, -S, 0)]
out = []
for i in range(n):
e0 = [p[0][k] + (p[1][k] - p[0][k]) * i / (n - 1) for k in range(3)]
e1 = [p[3][k] + (p[2][k] - p[3][k]) * i / (n - 1) for k in range(3)]
for j in range(n):
b = [e0[k] + (e1[k] - e0[k]) * j / (n - 1) for k in range(3)]
d = float("%.9g" % (24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8))
out.append("%.2f %.2f %.2f" % (b[0], b[1], b[2] + d))
return "\n".join(sorted(out))
def generate(ctx):
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "--impure", "--expr",
"with import <nixpkgs> {}; python3Packages.srctools.src"], capture_output=True, check=True).stdout.decode().strip()
files = []
with tarfile.open(src) as tf:
for m in tf.getmembers():
base = os.path.basename(m.name)
if m.isfile() and base.endswith(".vmf") and ("/test_geometry/" in m.name or "/test_vmf/" in m.name) and base != "test_merge.vmf":
files.append((base, tf.extractfile(m).read().decode("utf-8")))
files.sort()
text = room()
res = json.loads(ctx.python(["srctools"], CODE, input=json.dumps({"files": files, "room": text}).encode()))
out = [{"name": n, "data": d.encode(), "solids": r["solids"]} for (n, d), r in zip(files, res["files"])]
r = res["room"]
r.update({"data": text.encode(), "disp": disp_expected()})
ctx.emit("vmf", {"files": out, "room": r})