Files
rosetta/src/Rosetta/model/bsp/Lightmap.luau
T
4DBug 67e116a6c6 model/bsp: BSP2 / 2PSB, Quake 1 / 2 / Half-Life lightmap atlas (TEXCOORD_1, .lit), tree / hulls / visibility in meta.bsp
Bsp.leafAt / contents / pvs point queries; tested on ericw-tools qbsp + vis output in all three Quake 1 layouts.
2026-11-01 19:03:55 -06:00

65 lines
1.9 KiB
Luau

--!strict
-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each
-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face).
local Lightmap = {}
export type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border
-- nil, message past maxPixels
function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?)
local area, widest = 0, 1
for _, s in sizes do
area += (s[1] + 2) * (s[2] + 2)
widest = math.max(widest, s[1] + 2)
end
local W = 64
while W * W < area * 1.2 and W < 4096 do
W *= 2
end
W = math.max(W, widest)
local order = table.create(#sizes) :: { number }
for i = 1, #sizes do
order[i] = i
end
table.sort(order, function(a: number, b: number): boolean
local ha, hb = sizes[a][2], sizes[b][2]
if ha ~= hb then
return ha > hb
end
return a < b
end)
local out = table.create(#sizes) :: { Rect }
local x, y, rowH = 0, 0, 0
for _, i in order do
local w, h = sizes[i][1] + 2, sizes[i][2] + 2
if x + w > W then
x, y, rowH = 0, y + rowH, 0
end
out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] }
x += w
rowH = math.max(rowH, h)
end
local H = math.max(1, y + rowH)
if W * H > maxPixels then
return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H
end
return W, H, out, nil
end
-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W)
function Lightmap.border(px: buffer, W: number, r: Rect)
local function copy(dx: number, dy: number, sx: number, sy: number)
buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4))
end
for yy = r.y, r.y + r.h - 1 do
copy(r.x - 1, yy, r.x, yy)
copy(r.x + r.w, yy, r.x + r.w - 1, yy)
end
for xx = r.x - 1, r.x + r.w do
copy(xx, r.y - 1, xx, r.y)
copy(xx, r.y + r.h, xx, r.y + r.h - 1)
end
end
return Lightmap