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

+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