merge master into ws/arch2 (ws/video2, ws/3d3, ws/game Archive.slice / collect)

This commit is contained in:
4DBug committed 2026-10-31 15:57:05 -05:00
commit 79fd3c05dd
213 files changed
+47945 -1533

No files matched your search

+335
View File
@@ -949,6 +949,19 @@ do
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local Wrl = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local wrl = assert(Wrl.encode(scene))
bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function()
Wrl.decode(Bytes.reader(wrl))
end)
bench("vrml encode", 2, buffer.len(wrl), function()
Wrl.encode(scene)
end)
local x3d = assert(X3d.encode(scene))
bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function()
X3d.decode(Bytes.reader(x3d))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
@@ -1177,6 +1190,26 @@ do
end
end
end
do
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
local Draco = require("@formats/codecs/model/Draco")
local DC = require("@tests/gen/draco_cases")
for _, c in DC do
if c.name == "enc/bunny_norm.obj.cl7" or c.name == "enc/uvsphere.obj.cl10" or c.name == "enc/uvsphere.obj.cl0" then
local data = buffer.fromstring(c.data)
local g = assert(Draco.decode(data))
local n = g.numFaces * 12
for _, a in g.attributes do
n += buffer.len(a.data)
end
local dt = bench("draco " .. string.sub(c.name, 5), 3, n, function()
Draco.decode(data)
end)
print(string.format("%-8s %-30s %8.0f triangles/s", runtime, " (" .. g.numFaces .. " faces)", g.numFaces / dt))
end
end
end
do
-- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds)
-- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file
@@ -1255,3 +1288,305 @@ do
Qb.decode(Bytes.reader(qb))
end)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/image/Jpeg")
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Types = require("@formats/Types")
local MB = require("@tests/gen/mjpeg_bench")
local M1 = require("@tests/gen/mpeg1_bench")
-- best of n runs of f (which handles `frames` frames): ms per frame and frames per second
local function fps(label: string, n: number, frames: number, f: () -> ())
f()
local dt = math.huge
for _ = 1, n do
local t0 = os.clock()
f()
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt))
end
for _, c in MB.frames do
local b = Base64.decode(c.data) :: buffer
local img = assert(Jpeg.decode(b, 0, nil, { yuv = true }))
assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG")
fps("mjpeg decode yuv " .. c.name, 10, 1, function()
Jpeg.decode(b, 0, nil, { yuv = true })
end)
fps("mjpeg decode rgba " .. c.name, 10, 1, function()
Jpeg.decode(b)
end)
end
for _, s in MB.sources do
local img = Types.Image.new(s.width, s.height, "yuv420p")
img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer))
fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function()
Jpeg.encode(img, { quality = 85 })
end)
end
-- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1)
local function mpeg1(tag: string)
for _, s in M1 do
local file = Base64.decode(s.file) :: buffer
for _, rgba in { false, true } do
fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
end
-- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2)
local M2 = require("@tests/gen/mpeg2_bench")
local function mpeg2(tag: string)
for _, s in M2 do
local file = Base64.decode(s.file) :: buffer
fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = false })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
jitTune(false)
mpeg1("")
mpeg2("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
mpeg2(" (jit tuned)")
jitTune(false)
end
end
do
-- ------------------------------------------------------------------------------------- ws-video2-theora: fps
-- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static:
-- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode +
-- image() (the yuv420p copy every VideoDecoder frame makes)
local Theora = require("@formats/codecs/video/Theora")
local Ogg = require("@formats/containers/Ogg")
local Base64 = require("@formats/core/Base64")
local TB = require("@tests/gen/theora_bench")
local function run(tag: string)
for _, c in TB do
local d = Ogg.open(Base64.decode(c.file) :: buffer)
local hdrs, data = {}, {}
for p in d:packets(d:find("theora")) do
table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p))
end
for _, image in { false, true } do
local n = c.width * c.height * 3 // 2 * #data
local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function()
local dec = Theora.new(hdrs) :: any
for _, p in data do
dec:decode(p)
if image then
dec:image()
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps
do
-- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240
-- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks);
-- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second)
local F = require("@formats")
local LB = require("@tests/gen/legacy_bench")
local cases = table.clone(LB)
table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 })
table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 })
for _, c in cases do
local data = buffer.fromstring(c.data)
local frames = 0
local dt = math.huge
for _ = 1, 3 do
local t0 = os.clock()
local v = assert(F.video.open(data, { audio = false }))
frames = 0
while v:nextFrame() do
frames += 1
end
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt))
end
local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data)))
local a = assert(v.audio)
local t0 = os.clock()
local n = 0
while true do
local _, got = a:read(4096)
if got == 0 then
break
end
n += got
end
local dt = os.clock() - t0
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
end
do
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
-- 128^3 noise voxel grid through VOX and greedy meshing
local Types = require("@formats/Types")
local MeshOps = require("@formats/ops/MeshOps")
local Gltf = require("@formats/model/gltf")
local Obj = require("@formats/model/obj")
local Stl = require("@formats/model/stl")
local Ply = require("@formats/model/ply")
local Vox = require("@formats/model/vox")
local N = 400
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
for y = 0, N - 1 do
for x = 0, N - 1 do
local i = y * N + x
buffer.writef32(pos.data, i * 12, x / N)
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
buffer.writef32(pos.data, i * 12 + 8, y / N)
buffer.writef32(uv.data, i * 8, x / N)
buffer.writef32(uv.data, i * 8 + 4, y / N)
end
end
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
local k = 0
for y = 0, N - 2 do
for x = 0, N - 2 do
local a = y * N + x
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
buffer.writeu32(ind.data, k * 4, v)
k += 1
end
end
end
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
MeshOps.computeNormals(prim)
local scene = Types.Scene.fromPrimitive(prim, "grid")
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
MeshOps.computeNormals(prim)
end)
local glb = assert(Gltf.encode(scene, { binary = true }))
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
Gltf.decode(Bytes.reader(glb))
end)
bench("gltf glb encode", 3, buffer.len(glb), function()
Gltf.encode(scene, { binary = true })
end)
local obj = assert(Obj.encode(scene))
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
Obj.decode(Bytes.reader(obj))
end)
bench("obj encode", 2, buffer.len(obj), function()
Obj.encode(scene)
end)
local stl = assert(Stl.encode(scene))
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
Stl.decode(Bytes.reader(stl))
end)
local ply = assert(Ply.encode(scene))
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local Fbx = require("@formats/model/fbx")
local fbx = assert(Fbx.encode(scene))
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
Fbx.decode(Bytes.reader(fbx))
end)
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
Fbx.encode(scene)
end)
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
Fbx.encode(scene, { compress = false })
end)
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local ThreeMf = require("@formats/model/3mf")
local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
ThreeMf.decode(Bytes.reader(tmf))
end)
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
for y = 0, V - 1 do
for x = 0, V - 1 do
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
if z < h then
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
end
end
end
end
local vox = assert(Vox.encode(grid))
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
Vox.decode(Bytes.reader(vox))
end)
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
MeshOps.voxelsToPrimitive(grid)
end)
end
do
-- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode)
-- or input (encode); BC6H of rgbaf32 output
local Bcn = require("@formats/codecs/image/Bcn")
local BB = require("@tests/gen/bcn_bench")
local w, h = BB.w, BB.h
local px = buffer.fromstring(BB.rgba)
for _, kind in { "bc1", "bc3", "bc5" } do
local blocks = Bcn.encode(kind, px, w, h) :: buffer
bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function()
Bcn.decode(kind, blocks, 0, w, h)
end)
bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function()
Bcn.encode(kind, px, w, h)
end)
end
local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h)
bench("bcn decode bc7 256x256", 5, w * h * 4, function()
Bcn.decode("bc7", b7, 0, w, h)
end)
bench("bcn decode bc6h 256x256", 5, w * h * 16, function()
Bcn.decode("bc6h", b6, 0, w, h)
end)
end
do
-- OpenEXR (ws-tex): a 512 x 256 half RGBA image from the OpenEXR bindings (tools/fixtures/exr.py), ZIP and PIZ;
-- MB/s of rgbaf32 output; our ZIP encoder on the decoded floats
local Exr = require("@formats/image/exr")
local EB = require("@tests/gen/exr_bench")
local n = 512 * 256 * 16
for _, k in { "zip", "piz" } do
local data = buffer.fromstring(EB[k])
bench("exr decode " .. k .. " 512x256 half", 3, n, function()
Exr.decode(Bytes.reader(data), { native = true })
end)
end
local img = Exr.decode(Bytes.reader(buffer.fromstring(EB.zip)), { native = true }) :: any
bench("exr encode zip 512x256 half", 2, n, function()
Exr.encode(img)
end)
end
+101
View File
@@ -0,0 +1,101 @@
# 3DS fixtures (tools/fixtures.py): assimp's 3DS test models (test/models/3DS and test/models-nonbsd/3DS: meshes,
# materials, textures, keyframer hierarchies, pivots, rotation / camera / target animation, cameras, lights; read from
# the nixpkgs assimp source, never committed) and files written by assimp's 3DS exporter from glTF sample models, with
# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, cameras, lights,
# nodes; world bounds from its PreTransformVertices export). Then our encoder's output (tools/fixtures/_3ds_encode.luau,
# from every case and the glTF models) read back by assimp. (Blender 5's 3DS importer is an extension that is not
# installed by default, so assimp is the only reference.)
# tests/gen/3ds_cases.luau { name, data, assimp }
# tests/gen/3ds_gltf.luau glTF sample models for the writer round trips: { name, data, files }
# tests/gen/3ds_xcheck.luau { name, case? | gltf?, assimp }
import importlib.util, os
INPUTS = ["src/Formats/model/3ds", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/_3ds_encode.luau"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
GLTF = ("Box", "BoxTextured", "BoxVertexColors", "Cameras", "SimpleMeshes", "RiggedSimple", "SimpleSkin", "MultiUVTest",
"NegativeScaleTest", "PointLightIntensityTest", "AnimatedTriangle", "TextureCoordinateTest", "TextureTransformTest",
"InterpolationTest", "LightVisibility")
def reference(ctx, M, X, paths, tmp):
out = []
for p, a in zip(paths, M.assimp_info(ctx, paths, raw=True)):
a.update(X.assimp_extra(ctx, p))
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(X.ptv_bounds(ctx, p, tmp))
out.append(a)
return out
def generate(ctx):
M = load(ctx, "_model_ref")
X = load(ctx, "fbx")
tmp = M.tempdir()
src = X.assimp_src(ctx)
cases = []
for sub in ("models", "models-nonbsd"):
d = os.path.join(src, "test", sub, "3DS")
for f in sorted(os.listdir(d)):
if f.lower().endswith(".3ds"):
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f)})
# assimp's exporter
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
main = os.path.join(d, mains[0])
picks.append({"name": model + "/" + variant, "data": open(main, "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
out = os.path.join(tmp, model + ".3ds")
try:
ctx.nix("assimp", ["assimp", "export", main, out, "-f3ds"])
cases.append({"name": "assimp-export/" + model + ".3ds", "path": out})
except Exception:
pass
break
refs = reference(ctx, M, X, [c["path"] for c in cases], tmp)
for c, a in zip(cases, refs):
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("3ds_cases", cases)
ctx.emit("3ds_gltf", picks)
# assimp reads our files
ours = M.luau_encode(ctx, "tools/fixtures/_3ds_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".3ds"))
paths = []
for n in names:
p = os.path.join(xtmp, n)
with open(p, "wb") as f:
f.write(ours[n])
paths.append(p)
xs = []
for n, a in zip(names, reference(ctx, M, X, paths, xtmp)):
kind, idx = n[:-4].split("_")
e = {"name": n, "assimp": a}
e["case" if kind == "case" else "gltf"] = int(idx)
xs.append(e)
ctx.emit("3ds_xcheck", xs)
+44
View File
@@ -0,0 +1,44 @@
-- tools/fixtures/_3ds_encode: run by tools/fixtures/3ds.py (luau CLI, repo root): decodes every 3DS case and every
-- glTF sample model with our readers and writes them with our 3DS writer, printing "<file>\t<hex>" lines for assimp
-- to read back. Files: case_<i>.3ds, gltf_<i>.3ds.
local ThreeDs = require("@formats/model/3ds")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/3ds_cases")
local Picks = require("@tests/gen/3ds_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function emit(name: string, scene: any)
local out, err = ThreeDs.encode(scene)
if out then
print(name .. "\t" .. hex(out))
else
print("encode failed " .. name .. ": " .. tostring(err))
end
end
for i, c in Cases do
local scene, err = ThreeDs.decode(Bytes.reader(buffer.fromstring(c.data)))
if scene then
emit(string.format("case_%d.3ds", i), scene)
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
for i, g in Picks do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
if scene then
emit(string.format("gltf_%d.3ds", i), scene)
end
end
+44
View File
@@ -0,0 +1,44 @@
// Dumps a decoded Draco file: points, faces and every attribute's per-point bytes (hex), for the fixture generator.
#include "draco/compression/decode.h"
#include <cstdio>
#include <fstream>
#include <iterator>
#include <vector>
static void hex(const uint8_t* p, size_t n) { for (size_t i = 0; i < n; ++i) printf("%02x", p[i]); }
int main(int argc, char** argv) {
std::ifstream f(argv[1], std::ios::binary);
std::vector<char> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
draco::DecoderBuffer buf;
buf.Init(data.data(), data.size());
auto type = draco::Decoder::GetEncodedGeometryType(&buf);
if (!type.ok()) { printf("ERROR %s\n", type.status().error_msg()); return 0; }
draco::Decoder dec;
std::unique_ptr<draco::PointCloud> pc;
std::unique_ptr<draco::Mesh> mesh;
if (type.value() == draco::TRIANGULAR_MESH) {
auto r = dec.DecodeMeshFromBuffer(&buf);
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
mesh = std::move(r).value();
} else {
auto r = dec.DecodePointCloudFromBuffer(&buf);
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
pc = std::move(r).value();
}
const draco::PointCloud* g = mesh ? mesh.get() : pc.get();
printf("POINTS %u\n", g->num_points());
if (mesh) {
printf("FACES %u ", mesh->num_faces());
for (draco::FaceIndex fi(0); fi < mesh->num_faces(); ++fi) {
const auto& face = mesh->face(fi);
for (int c = 0; c < 3; ++c) { uint32_t v = face[c].value(); hex((const uint8_t*)&v, 4); }
}
printf("\n");
}
for (int i = 0; i < g->num_attributes(); ++i) {
const draco::PointAttribute* a = g->attribute(i);
printf("ATTR %d %d %d %d %u ", (int)a->attribute_type(), (int)a->data_type(), (int)a->num_components(), a->normalized() ? 1 : 0, a->unique_id());
for (draco::PointIndex p(0); p < g->num_points(); ++p) hex(a->GetAddress(a->mapped_index(p)), a->byte_stride());
printf("\n");
}
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our
-- reader and writer, and every glTF pick through our writer, printing "<file>\t<hex>" lines for assimp and the
-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_<name>.iqm.
local Iqm = require("@formats/model/iqm")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/iqm_cases")
local Picks = require("@tests/gen/iqm_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
for _, c in Cases do
local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data))))
print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene))))
end
for _, p in Picks do
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })
if scene then
local out, e2 = Iqm.encode(scene)
if out then
print("gltf_" .. p.name .. ".iqm\t" .. hex(out))
else
print("encode failed " .. p.name .. ": " .. tostring(e2))
end
else
print("skipped " .. p.name .. ": " .. tostring(err))
end
end
+113
View File
@@ -0,0 +1,113 @@
# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its
# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the
# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds
# block, which it returns too for comparison).
import math, struct
HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays "
"num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames "
"num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split()
FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)}
def mat(t, q, s):
x, y, z, w = q
n = math.sqrt(x * x + y * y + z * z + w * w) or 1
x, y, z, w = x / n, y / n, z / n, w / n
r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]
return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]]
def mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
def inv(m):
# general 4x4 inverse (Gauss-Jordan)
a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)]
for c in range(4):
p = max(range(c, 4), key=lambda r: abs(a[r][c]))
a[c], a[p] = a[p], a[c]
d = a[c][c] or 1e-30
a[c] = [v / d for v in a[c]]
for r in range(4):
if r != c:
f = a[r][c]
a[r] = [v - f * w for v, w in zip(a[r], a[c])]
return [row[4:] for row in a]
def read(data):
h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16)))
text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]]
def s(o):
return text[o:text.index(b"\0", o)].decode("latin1")
arrays = {}
for i in range(h["num_vertexarrays"]):
typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20)
c, n = FMT[fmt]
vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs)
arrays[typ] = (fmt, size, vals)
joints = []
for j in range(h["num_joints"]):
v = struct.unpack_from("<Ii10f", data, h["ofs_joints"] + j * 48)
joints.append((s(v[0]), v[1], v[2:5], v[5:9], v[9:12]))
bind = []
for name, parent, t, q, sc in joints:
m = mat(t, q, sc)
bind.append(mul(bind[parent], m) if parent >= 0 else m)
invbind = [inv(m) for m in bind]
poses = []
for p in range(h["num_poses"]):
v = struct.unpack_from("<iI20f", data, h["ofs_poses"] + p * 88)
poses.append((v[0], v[1], v[2:12], v[12:22]))
frames = struct.unpack_from("<%dH" % (h["num_frames"] * h["num_framechannels"]), data, h["ofs_frames"]) if h["num_frames"] else ()
anims = []
for a in range(h["num_anims"]):
v = struct.unpack_from("<3IfI", data, h["ofs_anims"] + a * 20)
anims.append({"name": s(v[0]), "first": v[1], "frames": v[2], "framerate": v[3]})
pos = arrays[0][2]
bi = arrays.get(4)
bw = arrays.get(5)
boxes = []
k = 0
for f in range(h["num_frames"]):
world = []
for i, (parent, mask, off, sc) in enumerate(poses):
ch = list(off)
for c in range(10):
if mask & (1 << c):
ch[c] += frames[k] * sc[c]
k += 1
m = mat(ch[0:3], ch[3:7], ch[7:10])
world.append(mul(world[parent], m) if parent >= 0 else m)
skin = [mul(world[j], invbind[j]) for j in range(len(world))]
lo, hi = [1e30] * 3, [-1e30] * 3
for v in range(h["num_vertexes"]):
x, y, z = pos[v * 3:v * 3 + 3]
if bi and bw:
sx = sy = sz = 0.0
tot = 0.0
for c in range(4):
w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c]
if w > 0:
m = skin[bi[2][v * 4 + c]]
sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3])
sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3])
sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3])
tot += w
if tot > 0:
x, y, z = sx, sy, sz
lo = [min(a, b) for a, b in zip(lo, (x, y, z))]
hi = [max(a, b) for a, b in zip(hi, (x, y, z))]
boxes.append({"min": lo, "max": hi})
stored = []
if h["ofs_bounds"]:
for f in range(h["num_frames"]):
v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32)
stored.append({"min": list(v[0:3]), "max": list(v[3:6])})
return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"],
"jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored}
+375
View File
@@ -0,0 +1,375 @@
# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV
# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot
# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised).
import struct
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def be16(v):
return struct.pack(">H", v & 0xFFFF)
def be32(v):
return struct.pack(">I", v & 0xFFFFFFFF)
# ---------------------------------------------------------------------------------------------------- AVI
def _ck(cid, body):
return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"")
def _lst(kind, body):
return b"LIST" + le32(len(body) + 4) + kind + body
def bitmapinfo(w, h, bits, fourcc, palette=None):
"""BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)"""
n = len(palette) if palette else 0
out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \
le32(0) + le32(0) + le32(n) + le32(0)
for r, g, b in palette or []:
out += bytes([b, g, r, 0])
return out
def avi(w, h, fourcc, strf, frames, keys, fps=10):
"""an AVI file: one video stream, frames = [bytes], keys = [bool]"""
n = len(frames)
avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \
le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16)
strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \
le32(max(len(f) for f in frames)) + struct.pack("<i", -1) + le32(0) + struct.pack("<hhhh", 0, 0, w, h)
hdrl = _lst(b"hdrl", _ck(b"avih", avih) + _lst(b"strl", _ck(b"strh", strh) + _ck(b"strf", strf)))
movi = b""
idx = b""
for f, k in zip(frames, keys):
idx += b"00dc" + le32(0x10 if k else 0) + le32(4 + len(movi)) + le32(len(f))
movi += _ck(b"00dc", f)
body = b"AVI " + hdrl + _lst(b"movi", movi) + _ck(b"idx1", idx)
return b"RIFF" + le32(len(body)) + body
# ---------------------------------------------------------------------------------------------------- MOV
def _box(t, body):
return be32(8 + len(body)) + t + body
def qt_entry(fourcc, w, h, depth, ctab_id=0xFFFF, colors=None):
"""a QuickTime video sample description; colors = [(r, g, b)] makes a colour table (ctab_id 0)"""
body = bytes(6) + be16(1) + be16(0) + be16(0) + b"appl" + be32(0) + be32(512) + be16(w) + be16(h) + \
be32(72 << 16) + be32(72 << 16) + be32(0) + be16(1) + bytes([4]) + b"test" + bytes(27) + be16(depth)
if colors is not None:
body += be16(0) + be32(0) + be16(0x8000) + be16(len(colors) - 1)
for i, (r, g, b) in enumerate(colors):
body += be16(i) + bytes([r, r, g, g, b, b])
else:
body += be16(ctab_id)
return _box(fourcc, body)
def mov(w, h, entry, frames, keys, fps=10):
"""a QuickTime file: one video track with the sample description `entry`"""
scale, delta = fps * 100, 100
n = len(frames)
ftyp = _box(b"ftyp", b"qt " + be32(0x200) + b"qt ")
mdat_off = len(ftyp) + 8
offs, pos = [], mdat_off
for f in frames:
offs.append(pos)
pos += len(f)
mdat = _box(b"mdat", b"".join(frames))
matrix = be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x40000000)
dur = n * delta
mvhd = _box(b"mvhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be32(0x10000) + be16(0x100) +
bytes(10) + matrix + bytes(24) + be32(2))
tkhd = _box(b"tkhd", be32(3) + be32(0) + be32(0) + be32(1) + be32(0) + be32(dur) + bytes(8) + be16(0) + be16(0) +
be16(0) + be16(0) + matrix + be32(w << 16) + be32(h << 16))
mdhd = _box(b"mdhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be16(0) + be16(0))
hdlr = _box(b"hdlr", be32(0) + b"mhlr" + b"vide" + bytes(12) + b"\x05Video")
vmhd = _box(b"vmhd", be32(1) + bytes(8))
dinf = _box(b"dinf", _box(b"dref", be32(0) + be32(1) + _box(b"alis", be32(1))))
stsd = _box(b"stsd", be32(0) + be32(1) + entry)
stts = _box(b"stts", be32(0) + be32(1) + be32(n) + be32(delta))
sync = [i + 1 for i, k in enumerate(keys) if k]
stss = _box(b"stss", be32(0) + be32(len(sync)) + b"".join(be32(i) for i in sync))
stsc = _box(b"stsc", be32(0) + be32(1) + be32(1) + be32(1) + be32(1))
stsz = _box(b"stsz", be32(0) + be32(0) + be32(n) + b"".join(be32(len(f)) for f in frames))
stco = _box(b"stco", be32(0) + be32(n) + b"".join(be32(o) for o in offs))
stbl = _box(b"stbl", stsd + stts + stss + stsc + stsz + stco)
minf = _box(b"minf", vmhd + dinf + stbl)
mdia = _box(b"mdia", mdhd + hdlr + minf)
trak = _box(b"trak", tkhd + mdia)
moov = _box(b"moov", mvhd + trak)
return ftyp + mdat + moov
# ---------------------------------------------------------------------------------------------------- pictures
def index_frames(w, h, n, colors, seed=1):
"""n palettised pictures (rows of indexes < colors): bands, a moving square, a noisy patch; most of each frame
stays the same as the previous one (inter-frame codecs get skips)"""
import random
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[((x // 7 + y // 5) % colors) for x in range(w)] for y in range(h)]
sx, sy = (t * 5) % max(1, w - 12), (t * 3) % max(1, h - 10)
for y in range(sy, min(h, sy + 10)):
for x in range(sx, min(w, sx + 12)):
img[y][x] = (t + 1) % colors
for y in range(h // 2, min(h, h // 2 + 6)):
for x in range(w // 3, min(w, w // 3 + 9)):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def palette(n, seed=7):
import random
rnd = random.Random(seed)
return [(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- QuickTime RLE
def _groups(row, per):
return [tuple(row[i:i + per]) for i in range(0, len(row), per)]
def _pack(group, bits):
out = bytearray()
per = 8 // bits
for i in range(0, len(group), per):
v = 0
for k in range(per):
v = (v << bits) | group[i + k]
out.append(v)
return bytes(out)
def qtrle_frame(img, prev, bits):
"""one 'rle ' frame at 1 / 2 / 4 / 8 bits (prev = the previous picture or None: changed line range only, with
skip codes inside lines)"""
h, w = len(img), len(img[0])
per = 16 if bits == 1 else 32 // bits # pixels per group
pw = (w + per - 1) // per * per
rows = [r + [0] * (pw - w) for r in img]
prow = [r + [0] * (pw - w) for r in prev] if prev else None
changed = [y for y in range(h) if not prow or rows[y] != prow[y]]
if not changed:
return be32(6) + be16(0)
y0, y1 = changed[0], changed[-1] + 1
body = bytearray()
for y in range(y0, y1):
g = _groups(rows[y], per)
pg = _groups(prow[y], per) if prow else None
if bits == 1:
# (skip, code) pairs: the first of a line has bit 7 set
first = True
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 127:
skip += 1
i += 1
if i >= len(g):
if first:
body += bytes([0x80 | skip, 0xFF])
first = False
break
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
sb = (0x80 if first else 0) | skip
first = False
if j > i:
body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1)
i = j + 1
else:
k = i
while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k])
i = k
if first:
body += bytes([0x80, 0xFF])
continue
line = bytearray([1])
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 250:
skip += 1
i += 1
if i >= len(g):
break
if skip:
line += bytes([0, skip + 1])
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
if j > i:
line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits)
i = j + 1
else:
k = i
while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k])
i = k
line += b"\xff"
body += line
if bits == 1:
body += b"\x00\x00"
else:
body += b"\x00"
head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0)
return be32(4 + len(head) + len(body)) + head + bytes(body)
# ---------------------------------------------------------------------------------------------------- MS Video 1
def _block(img, bx, by):
"""the 16 pixels of a block, MS Video 1 order: bottom row first, left to right"""
return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)]
def msvc8_frame(img, prev):
"""one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks"""
h, w = len(img), len(img[0])
bw, bh = w // 4, h // 4
out = bytearray()
skip = 0
def flush():
nonlocal skip
while skip:
k = min(skip, 1023)
out.extend([k & 0xFF, 0x84 + (k >> 8)])
skip -= k
for by in range(bh - 1, -1, -1):
for bx in range(bw):
px = _block(img, bx, by)
if prev and px == _block(prev, bx, by):
skip += 1
continue
flush()
cols = sorted(set(px), key=lambda c: (-px.count(c), c))
if len(cols) == 1:
out.extend([px[0], 0x80])
elif len(cols) == 2:
c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1]
c1 = cols[0] if cols[0] != c0 else cols[1]
flags = sum(1 << i for i in range(16) if px[i] == c1)
out.extend([flags & 0xFF, flags >> 8, c1, c0])
else:
# 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000)
colours = [0] * 8
flags = 0
for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]):
ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)]
vals = [px[i] for i in ids]
key = {2: 12, 3: 15}.get(q)
a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0]
rest = [v for v in vals if v != a]
b = rest[0] if rest else a
base = ((qy & 2) << 1) + (qx & 2)
colours[base], colours[base + 1] = a, b
for i in ids:
if px[i] == a:
flags |= 1 << i
else:
px[i] = b
out.extend([flags & 0xFF, flags >> 8] + colours)
flush()
return bytes(out)
# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit)
def cvid8_frame(img, prev, first):
"""one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per
entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the
codebook of 2x2 squares); inter frames skip unchanged blocks"""
h, w = len(img), len(img[0])
blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)]
v1, v4 = {}, {}
def sq(x, y):
return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1])
plan = []
for (x, y) in blocks:
if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)):
plan.append(None)
continue
q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)]
if all(len(set(s)) == 1 for s in q) and len(v1) < 256:
e = (q[0][0], q[1][0], q[2][0], q[3][0])
v1.setdefault(e, len(v1))
plan.append(("v1", v1[e]))
else:
ids = []
for s in q:
if s not in v4 and len(v4) < 256:
v4[s] = len(v4)
ids.append(v4.get(s, 0))
plan.append(("v4", ids))
def book(cid, entries):
data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1]))
return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data
chunks = b""
if v4:
chunks += book(0x24, v4)
if v1:
chunks += book(0x26, v1)
bits, data = [], bytearray()
inter = prev is not None
# flags (MSB first, 32 per word) are interleaved with the indexes in decode order
words = bytearray()
flagbuf = []
def flag(b):
flagbuf.append(b)
if len(flagbuf) == 1:
words.extend(b"FLAG") # placeholder, patched below
pos_stack.append(len(words) - 4)
if len(flagbuf) == 32:
patch()
pos_stack = []
def patch():
v = 0
for i, b in enumerate(flagbuf):
v |= b << (31 - i)
p = pos_stack.pop()
words[p:p + 4] = v.to_bytes(4, "big")
flagbuf.clear()
for item in plan:
if inter:
flag(0 if item is None else 1)
if item is None:
continue
flag(1 if item[0] == "v4" else 0)
if item[0] == "v1":
words.append(item[1])
else:
words.extend(item[1])
if flagbuf:
patch()
vid = (0x31 if inter else 0x30)
chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words)
strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \
be16(w) + chunks
size = 10 + len(strip)
return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip
+44
View File
@@ -0,0 +1,44 @@
-- tools/fixtures/_ms3d_encode: run by tools/fixtures/ms3d.py (luau CLI, repo root): decodes every MS3D case and every
-- glTF sample model with our readers and writes them with our MS3D writer, printing "<file>\t<hex>" lines for assimp
-- to read back. Files: case_<i>.ms3d, gltf_<i>.ms3d.
local Ms3d = require("@formats/model/ms3d")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/ms3d_cases")
local Picks = require("@tests/gen/ms3d_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function emit(name: string, scene: any)
local out, err = Ms3d.encode(scene)
if out then
print(name .. "\t" .. hex(out))
else
print("encode failed " .. name .. ": " .. tostring(err))
end
end
for i, c in Cases do
local scene, err = Ms3d.decode(Bytes.reader(buffer.fromstring(c.data)))
if scene then
emit(string.format("case_%d.ms3d", i), scene)
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
for i, g in Picks do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
if scene then
emit(string.format("gltf_%d.ms3d", i), scene)
end
end
+265
View File
@@ -0,0 +1,265 @@
# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every
# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs,
# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis
# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes
# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code.
import math, struct
def f32s(*v):
return struct.pack("<%df" % len(v), *v)
class Pmx:
def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0):
self.version, self.utf8, self.uva = version, utf8, uva
self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes
def text(self, s):
b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le")
return struct.pack("<i", len(b)) + b
def idx(self, v, size, vertex=False):
if vertex:
return struct.pack({1: "<B", 2: "<H", 4: "<i"}[size], v)
return struct.pack({1: "<b", 2: "<h", 4: "<i"}[size], v)
def build(self, m):
out = bytearray(b"PMX ")
out += struct.pack("<f", self.version)
out += bytes([8, 1 if self.utf8 else 0, self.uva, self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize])
for s in (m["name"], m["nameEn"], m["comment"], m["commentEn"]):
out += self.text(s)
B = lambda i: self.idx(i, self.bsize)
out += struct.pack("<i", len(m["vertices"]))
for v in m["vertices"]:
out += f32s(*v["pos"], *v["normal"], *v["uv"])
for k in range(self.uva):
out += f32s(*v["uva"][k])
kind = v["deform"]
out += bytes([kind])
b, w = v["bones"], v["weights"]
if kind == 0:
out += B(b[0])
elif kind == 1:
out += B(b[0]) + B(b[1]) + f32s(w[0])
elif kind in (2, 4):
out += B(b[0]) + B(b[1]) + B(b[2]) + B(b[3]) + f32s(*w[:4])
else:
out += B(b[0]) + B(b[1]) + f32s(w[0]) + f32s(*v["sdef"][0], *v["sdef"][1], *v["sdef"][2])
out += f32s(v["edge"])
out += struct.pack("<i", len(m["indices"]))
for i in m["indices"]:
out += self.idx(i, self.vsize, True)
out += struct.pack("<i", len(m["textures"]))
for t in m["textures"]:
out += self.text(t)
out += struct.pack("<i", len(m["materials"]))
T = lambda i: self.idx(i, self.tsize)
for mat in m["materials"]:
out += self.text(mat["name"]) + self.text(mat["nameEn"])
out += f32s(*mat["diffuse"], *mat["specular"], mat["power"], *mat["ambient"])
out += bytes([mat["flags"]]) + f32s(*mat["edgeColor"], mat["edgeSize"])
out += T(mat["texture"]) + T(mat["sphere"]) + bytes([mat["sphereMode"], 1 if mat["toonShared"] is not None else 0])
out += bytes([mat["toonShared"]]) if mat["toonShared"] is not None else T(mat["toon"])
out += self.text(mat["memo"]) + struct.pack("<i", mat["count"])
out += struct.pack("<i", len(m["bones"]))
for bn in m["bones"]:
fl = bn["flags"]
out += self.text(bn["name"]) + self.text(bn["nameEn"]) + f32s(*bn["pos"]) + B(bn["parent"]) + struct.pack("<iH", bn["layer"], fl)
out += B(bn["tail"]) if fl & 1 else f32s(*bn["tail"])
if fl & 0x300:
out += B(bn["inherit"][0]) + f32s(bn["inherit"][1])
if fl & 0x400:
out += f32s(*bn["axis"])
if fl & 0x800:
out += f32s(*bn["localX"], *bn["localZ"])
if fl & 0x2000:
out += struct.pack("<i", bn["key"])
if fl & 0x20:
ik = bn["ik"]
out += B(ik["target"]) + struct.pack("<if", ik["loops"], ik["limit"]) + struct.pack("<i", len(ik["links"]))
for ln in ik["links"]:
out += B(ln["bone"]) + bytes([1 if ln.get("min") else 0])
if ln.get("min"):
out += f32s(*ln["min"], *ln["max"])
out += struct.pack("<i", len(m["morphs"]))
V = lambda i: self.idx(i, self.vsize, True)
Mo = lambda i: self.idx(i, self.morsize)
for mo in m["morphs"]:
out += self.text(mo["name"]) + self.text(mo["nameEn"]) + bytes([mo["panel"], mo["type"]]) + struct.pack("<i", len(mo["offsets"]))
for o in mo["offsets"]:
t = mo["type"]
if t in (0, 9):
out += Mo(o[0]) + f32s(o[1])
elif t == 1:
out += V(o[0]) + f32s(*o[1])
elif t == 2:
out += B(o[0]) + f32s(*o[1], *o[2])
elif 3 <= t <= 7:
out += V(o[0]) + f32s(*o[1])
elif t == 8:
out += self.idx(o[0], self.msize) + bytes([o[1]]) + f32s(*o[2])
elif t == 10:
out += self.idx(o[0], self.rsize) + bytes([o[1]]) + f32s(*o[2], *o[3])
out += struct.pack("<i", len(m["frames"]))
for fr in m["frames"]:
out += self.text(fr["name"]) + self.text(fr["nameEn"]) + bytes([fr["special"]]) + struct.pack("<i", len(fr["items"]))
for kind, i in fr["items"]:
out += bytes([kind]) + (B(i) if kind == 0 else Mo(i))
out += struct.pack("<i", len(m["rigid"]))
for rb in m["rigid"]:
out += self.text(rb["name"]) + self.text(rb["nameEn"]) + B(rb["bone"]) + struct.pack("<BHB", rb["group"], rb["mask"], rb["shape"])
out += f32s(*rb["size"], *rb["pos"], *rb["rot"], rb["mass"], 0.5, 0.5, 0.0, 0.5) + bytes([rb["mode"]])
out += struct.pack("<i", len(m["joints"]))
R = lambda i: self.idx(i, self.rsize)
for jn in m["joints"]:
out += self.text(jn["name"]) + self.text(jn["nameEn"]) + bytes([0]) + R(jn["a"]) + R(jn["b"])
out += f32s(*jn["pos"], 0, 0, 0, -1, -1, -1, 1, 1, 1, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0)
if self.version >= 2.1:
out += struct.pack("<i", 0) # no soft bodies
return bytes(out)
def tube(rings=6, seg=8, nbones=4, nmat=3, version=2.0, uva=0, seed=1, deform=None, name="tube", flips=False):
"""a tube along +y: rings of seg vertices, weighted to a bone chain, faces split over nmat materials"""
import random
rnd = random.Random(seed)
kinds = deform or ([0, 1, 2, 3] + ([4] if version >= 2.1 else []))
verts = []
for r in range(rings):
y = r * 2.0
for s in range(seg):
a = 2 * math.pi * s / seg
x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r
b0 = min(nbones - 1, r * nbones // rings)
b1 = min(nbones - 1, b0 + 1)
k = kinds[(r * seg + s) % len(kinds)]
w = rnd.random()
if k == 0:
bones, weights = [b0], [1.0]
elif k in (1, 3):
bones, weights = [b0, b1], [w]
else:
ws = [rnd.random() + 0.1 for _ in range(4)]
bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws]
verts.append({
"pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)),
"uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)],
"deform": k, "bones": bones, "weights": weights, "edge": 1.0,
"sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)),
})
faces = []
for r in range(rings - 1):
for s in range(seg):
a, b = r * seg + s, r * seg + (s + 1) % seg
c, d = a + seg, b + seg
faces += [a, c, b, b, c, d]
ntri = len(faces) // 3
counts, left = [], ntri
for k in range(nmat):
n = left if k == nmat - 1 else max(1, ntri // nmat)
counts.append(n * 3)
left -= n
mats = []
for k in range(nmat):
mats.append({
"name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5),
"specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3],
"edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1,
"sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k],
})
bones = []
for i in range(nbones):
fl = 0x1A | (1 if i < nbones - 1 else 0)
b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1,
"layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)}
if i == 1:
b["flags"] |= 0x100
b["inherit"] = (0, 0.5)
if i == 2:
b["flags"] |= 0x400 | 0x800
b["axis"] = (0.0, 1.0, 0.0)
b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)
bones.append(b)
# an IK bone at the end targeting the last chain bone
bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0),
"ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}})
morphs = [
{"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]},
{"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]},
{"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]},
{"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]},
{"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]},
{"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]},
]
if uva:
morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]})
if version >= 2.1 and flips: # assimp 6 rejects these morph types
morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]})
morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]})
frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]},
{"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}]
rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3),
"pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)]
joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}]
return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces,
"textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs,
"frames": frames, "rigid": rigid, "joints": joints}
def pmd(m):
"""the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)"""
def name(s, n):
b = s.encode("ascii", "replace")[: n - 1]
return b + b"\0" * (n - len(b))
out = bytearray(b"Pmd") + struct.pack("<f", 1.0) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
out += struct.pack("<I", len(m["vertices"]))
for v in m["vertices"]:
b = v["bones"] + [v["bones"][0]]
w = v["weights"][0] if v["deform"] != 0 else 1.0
out += f32s(*v["pos"], *v["normal"], *v["uv"]) + struct.pack("<HHBB", max(0, b[0]), max(0, b[1]), int(round(w * 100)), 0)
out += struct.pack("<I", len(m["indices"])) + struct.pack("<%dH" % len(m["indices"]), *m["indices"])
out += struct.pack("<I", len(m["materials"]))
for mat in m["materials"]:
tex = m["textures"][mat["texture"]].replace("\\", "/") if mat["texture"] >= 0 else ""
if mat["sphere"] >= 0:
tex += "*" + m["textures"][mat["sphere"]]
out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"])
out += struct.pack("<BBI", mat["toonShared"] if mat["toonShared"] is not None else 255, 1 if mat["flags"] & 0x10 else 0, mat["count"]) + name(tex, 20)
bones = m["bones"]
out += struct.pack("<H", len(bones))
for i, bn in enumerate(bones):
tail = bn["tail"] if bn["flags"] & 1 else 0
out += name(bn["nameEn"], 20) + struct.pack("<hhBh", bn["parent"], tail, 2 if bn["flags"] & 0x20 else 0, 0) + f32s(*bn["pos"])
iks = [(i, bn["ik"]) for i, bn in enumerate(bones) if bn["flags"] & 0x20]
out += struct.pack("<H", len(iks))
for i, ik in iks:
out += struct.pack("<HHBHf", i, ik["target"], len(ik["links"]), ik["loops"], ik["limit"] / 4) + struct.pack("<%dH" % len(ik["links"]), *[ln["bone"] for ln in ik["links"]])
# skins: base (every vertex any morph moves, absolute positions) then the vertex morphs relative to the base list
vm = [mo for mo in m["morphs"] if mo["type"] == 1]
base = sorted({o[0] for mo in vm for o in mo["offsets"]})
pos = {v: k for k, v in enumerate(base)}
out += struct.pack("<H", 1 + len(vm) if vm else 0)
if vm:
out += name("base", 20) + struct.pack("<IB", len(base), 0)
for v in base:
out += struct.pack("<I", v) + f32s(*m["vertices"][v]["pos"])
for mo in vm:
out += name(mo["nameEn"], 20) + struct.pack("<IB", len(mo["offsets"]), mo["panel"])
for v, d in mo["offsets"]:
out += struct.pack("<I", pos[v]) + f32s(*d)
out += struct.pack("<B", 0) # skin display list
out += struct.pack("<B", 1) + name("Root", 50) # bone display groups
out += struct.pack("<I", 1) + struct.pack("<HB", 0, 1)
# English names
out += bytes([1]) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
for bn in bones:
out += name(bn["nameEn"], 20)
for mo in vm:
out += name(mo["nameEn"], 20)
out += name("Root", 50)
for k in range(10):
out += name("toon%02d.bmp" % (k + 1), 100)
out += struct.pack("<I", 0) + struct.pack("<I", 0) # rigid bodies, joints
return bytes(out)
+122
View File
@@ -0,0 +1,122 @@
# Shared by the simple raster fixture generators (pcx, sgi, sunras, xbm, xpm, ilbm, icns, ani): source images, a PNG
# writer, netpbm / ImageMagick runs in one temp dir, and a PNM / PAM reader for their output.
# work = Work(ctx) a temp dir; work.png(name, w, h, rgba); work.sh("netpbm", ["cmd", ...]); work.read(n)
# pnm_rgba(data) -> (w, h, rgba) for P1..P7 (PBM 1 = black; PAM GRAYSCALE[_ALPHA] / RGB[_ALPHA])
import os, random, shutil, struct, subprocess, tempfile, zlib
def png(w, h, rgba):
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
def photo(w, h, seed=1, alpha=False):
rng = random.Random(seed)
out = bytearray()
for y in range(h):
for x in range(w):
r = (x * 255) // max(1, w - 1)
g = (y * 255) // max(1, h - 1)
b = ((x * 7 + y * 3) * 4 + rng.randrange(8)) % 256
a = 255 if not alpha else ((x * 37 + y * 11) % 256)
out += bytes((r, g, b, a))
return bytes(out)
def palette_image(w, h, ncolours, seed=2):
rng = random.Random(seed)
cols = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)]
out = bytearray()
for y in range(h):
for x in range(w):
out += bytes(cols[(x // 3 + y // 2 + (x * y) % 3) % ncolours]) + b"\xff"
return bytes(out)
class Work:
def __init__(self, ctx):
self.ctx = ctx
self.dir = tempfile.mkdtemp(prefix="formats-raster-")
def close(self):
shutil.rmtree(self.dir, ignore_errors=True)
def path(self, n):
return os.path.join(self.dir, n)
def write(self, n, data):
with open(self.path(n), "wb") as f:
f.write(data)
def read(self, n):
with open(self.path(n), "rb") as f:
return f.read()
def png(self, n, w, h, rgba):
self.write(n, png(w, h, rgba))
def sh(self, pkg, cmds):
script = " && ".join(cmds)
res = subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", "cd %s && %s" % (self.dir, script)], capture_output=True)
if res.returncode:
raise RuntimeError("%s failed: %s" % (pkg, res.stderr.decode()[-1500:]))
return res.stdout
def _tokens(data, n, pos):
out = []
while len(out) < n:
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b"#":
while data[pos:pos + 1] not in (b"\n", b""):
pos += 1
continue
s = pos
while not data[pos:pos + 1].isspace():
pos += 1
out.append(int(data[s:pos]))
return out, pos + 1
def pnm_rgba(data):
kind = data[:2]
if kind == b"P7":
end = data.index(b"ENDHDR\n") + 7
hdr = dict(l.split(None, 1) for l in data[3:end - 7].decode().strip().split("\n") if l and not l.startswith("#"))
w, h, d, mx = int(hdr["WIDTH"]), int(hdr["HEIGHT"]), int(hdr["DEPTH"]), int(hdr["MAXVAL"])
raw, pos = data[end:], 0
elif kind in (b"P4",):
(w, h), pos = _tokens(data, 2, 2)
bits = data[pos:]
stride = (w + 7) // 8
out = bytearray()
for y in range(h):
for x in range(w):
v = 0 if (bits[y * stride + x // 8] >> (7 - x % 8)) & 1 else 255
out += bytes((v, v, v, 255))
return w, h, bytes(out)
else:
(w, h, mx), pos = _tokens(data, 3, 2)
d = 1 if kind == b"P5" else 3
raw = data[pos:]
bps = 2 if mx > 255 else 1
out = bytearray()
for i in range(w * h):
vals = []
for k in range(d):
o = (i * d + k) * bps
v = raw[o] if bps == 1 else (raw[o] << 8 | raw[o + 1])
vals.append((v * 255 + mx // 2) // mx)
if d == 1:
out += bytes((vals[0],) * 3 + (255,))
elif d == 2:
out += bytes((vals[0],) * 3 + (vals[1],))
elif d == 3:
out += bytes(vals) + b"\xff"
else:
out += bytes(vals)
return w, h, bytes(out)
+22
View File
@@ -0,0 +1,22 @@
# Shared by the simple raster fixture generators: run our encoder (tools/fixtures/_tex_encode.luau -a <fmt>) and
# decode files with ImageMagick into rgba8 (through PAM).
import os, shutil, subprocess
def ours(ctx, which):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if line.startswith("ours_") and "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
return files
def magick_cases(R, w, names, fmt=None):
"""ImageMagick decodes of the named files in the work dir -> { name: (w, h, rgba) }"""
pre = (fmt + ":") if fmt else ""
w.sh("imagemagick", ["magick %s%s -depth 8 -alpha on pam:%s.pam" % (pre, n, n) for n in names])
return {n: R.pnm_rgba(w.read(n + ".pam")) for n in names}
+193
View File
@@ -0,0 +1,193 @@
-- tools/fixtures/_tex_encode.luau: our texture encoders' output for the reference tools to read (run by
-- tools/fixtures/{dds,ktx,exr}.py as `luau tools/fixtures/_tex_encode.luau -a <format>`). Prints "name\thex" lines.
-- The source images are generated here (tools/fixtures/_tex_reference.py makes the same ones: source()).
local Types = require("@formats/Types")
local which = ({ ... } :: { string })[1] or "dds"
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
-- the test pattern (x, y, channel) -> 0..1, the same formula as _tex_reference.source()
local function value(x: number, y: number, c: number, w: number, h: number, salt: number): number
if c == 0 then
return x / math.max(1, w - 1)
elseif c == 1 then
return y / math.max(1, h - 1)
elseif c == 2 then
return ((x * 7 + y * 13 + salt * 31) % 64) / 63
end
return ((x + y + salt) % 5) / 4
end
local function image(w: number, h: number, fmt: string, salt: number, scale: number?): Types.Image
local img = Types.Image.new(w, h, fmt :: any)
for y = 0, h - 1 do
for x = 0, w - 1 do
for c = 0, 3 do
local v = value(x, y, c, w, h, salt)
local o = (y * w + x) * 4 + c
if fmt == "rgba8" then
buffer.writeu8(img.pixels, o, math.floor(v * 255 + 0.5))
elseif fmt == "rgba16" then
buffer.writeu16(img.pixels, o * 2, math.floor(v * 65535 + 0.5))
else
buffer.writef32(img.pixels, o * 4, if c < 3 then v * (scale or 1) else v)
end
end
end
end
return img
end
local function emit(name: string, b: buffer?, err: any?)
if not b then
error(name .. ": " .. tostring(err))
end
print(name .. "\t" .. hex(b))
end
if which == "dds" then
local Dds = require("@formats/image/dds")
local img = image(37, 23, "rgba8", 0)
for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do
emit("ours_" .. f .. ".dds", Dds.encode(img, { pixelFormat = f :: any }))
emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { pixelFormat = f :: any, mips = true }))
end
emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true }))
emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true }))
emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
local cube = image(16, 16, "rgba8", 0)
cube.frames = {}
for i = 1, 6 do
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
cube.meta.layout = "cube"
emit("ours_cube.dds", Dds.encode(cube, { mips = true }))
cube.meta.layout = "array"
emit("ours_array_bc1.dds", Dds.encode(cube, { pixelFormat = "bc1" }))
end
if which == "ktx" then
local Ktx = require("@formats/image/ktx")
local img = image(37, 23, "rgba8", 0)
emit("ours_rgba8.ktx2", Ktx.encode(img))
emit("ours_rgba8_mips.ktx2", Ktx.encode(img, { mips = true }))
emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 }))
emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true }))
emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
local cube = image(16, 16, "rgba8", 0)
cube.frames = {}
for i = 1, 6 do
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
cube.meta.layout = "cube"
emit("ours_cube.ktx2", Ktx.encode(cube, { mips = true }))
cube.meta.layout = "array"
emit("ours_array.ktx2", Ktx.encode(cube))
end
if which == "exr" then
local Exr = require("@formats/image/exr")
local f = image(37, 23, "rgbaf32", 0, 4)
for _, c in { "none", "zips", "zip" } do
emit("ours_half_" .. c .. ".exr", Exr.encode(f, { compression = c :: any }))
emit("ours_float_" .. c .. ".exr", Exr.encode(f, { compression = c :: any, pixelType = "float" }))
end
local opaque = image(20, 40, "rgbaf32", 1, 2)
for i = 0, 20 * 40 - 1 do
buffer.writef32(opaque.pixels, i * 16 + 12, 1)
end
emit("ours_rgb_zip.exr", Exr.encode(opaque))
emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2)))
end
-- the simple raster writers: a 37 x 23 photo-like image (opaque and with alpha) and a 12-colour one
local function photo(alpha: boolean): Types.Image
local img = image(37, 23, "rgba8", 0)
if not alpha then
for i = 0, 37 * 23 - 1 do
buffer.writeu8(img.pixels, i * 4 + 3, 255)
end
end
return img
end
local function few(): Types.Image
local img = Types.Image.new(30, 20)
for y = 0, 19 do
for x = 0, 29 do
local k = (x // 3 + y // 2) % 12
buffer.writeu32(img.pixels, (y * 30 + x) * 4, (k * 20) + (255 - k * 20) * 256 + ((k * 77) % 256) * 65536 + 0xFF000000)
end
end
return img
end
local function simple(): any
if which == "pcx" then
return require("@formats/image/pcx")
elseif which == "sgi" then
return require("@formats/image/sgi")
elseif which == "sunras" then
return require("@formats/image/sunras")
elseif which == "xbm" then
return require("@formats/image/xbm")
elseif which == "xpm" then
return require("@formats/image/xpm")
elseif which == "ilbm" then
return require("@formats/image/ilbm")
end
return nil
end
local Fmt = simple()
if Fmt then
for name, img in { opaque = photo(false), alpha = photo(true), few = few() } do
local out, err = Fmt.encode(img)
if out then
emit("ours_" .. name .. "." .. which, out)
else
print("skip\t" .. name .. "\t" .. tostring(err))
end
end
end
if which == "icns" then
-- square icons 16 / 32 / 48 / 128 as RLE entries (no encodeImage hook here)
local Icns = require("@formats/image/icns")
local base = image(128, 128, "rgba8", 1)
base.frames = {}
for i, s in { 16, 32, 48, 128 } do
base.frames[i] = { image = image(s, s, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
base.pixels = base.frames[4].image.pixels
emit("ours_legacy.icns", Icns.encode(base))
end
if which == "ora" then
-- a layered document: background, an offset half-opaque multiply layer, a hidden one, a group with a screen layer
local Ora = require("@formats/layered/ora")
local Png = require("@formats/image/png")
local doc = Types.Layered.new(40, 30)
local bg = Types.Layered.layer("background", image(40, 30, "rgba8", 0))
for i = 0, 40 * 30 - 1 do
buffer.writeu8(bg.image.pixels, i * 4 + 3, 255)
end
local mid = Types.Layered.layer("mid", image(20, 10, "rgba8", 1), 5, 7)
mid.opacity, mid.blend = 0.5, "multiply"
local hidden = Types.Layered.layer("hidden", image(8, 8, "rgba8", 2), 1, 1)
hidden.visible = false
local inner = Types.Layered.layer("inner", image(10, 10, "rgba8", 3), 20, 15)
inner.blend = "screen"
local g = Types.Layered.group("group", { inner })
g.opacity = 0.75
doc.layers = { bg, mid, hidden, g }
emit("ours_doc.ora", Ora.encode(doc, { encodeImage = function(img: any, _f: string): (any, any)
return Png.encode(img)
end }))
end
+110
View File
@@ -0,0 +1,110 @@
# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix.
# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is
# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian
# bytes when float is true
# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes)
# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data
import os, shutil, struct, tempfile
# Godot Image.Format numbers (checked against Godot 4.7)
GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25,
"eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31,
"etc2_rgba1": 32}
GD_SCRIPT = r'''extends SceneTree
func _init():
var dir = OS.get_cmdline_user_args()[0]
var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false)
for line in lines:
var a = line.split(" ")
var data = FileAccess.get_file_as_bytes(dir + "/" + a[0])
var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data)
img.decompress()
if a[4] == "1":
img.convert(Image.FORMAT_RGBAF)
else:
img.convert(Image.FORMAT_RGBA8)
var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE)
f.store_buffer(img.get_data())
f.close()
quit()
'''
def godot(ctx, jobs):
work = tempfile.mkdtemp(prefix="formats-godot-")
try:
lines = []
for i, (data, w, h, fmt, flt) in enumerate(jobs):
with open(os.path.join(work, "j%d" % i), "wb") as f:
f.write(data)
lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0))
with open(os.path.join(work, "jobs.txt"), "w") as f:
f.write("\n".join(lines) + "\n")
with open(os.path.join(work, "run.gd"), "w") as f:
f.write(GD_SCRIPT)
ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work])
out = []
for i in range(len(jobs)):
with open(os.path.join(work, "j%d.out" % i), "rb") as f:
out.append(f.read())
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def pillow(ctx, files):
"""files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)"""
work = tempfile.mkdtemp(prefix="formats-pillow-")
try:
for i, data in enumerate(files):
with open(os.path.join(work, "f%d" % i), "wb") as f:
f.write(data)
code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n"
" im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n"
" open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n"
" open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files))
ctx.python(["pillow"], code)
out = []
for i in range(len(files)):
mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split()
out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read()))
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0):
if mips:
flags |= 0x20000
return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf +
struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4)
def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data
def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + data
def rgba_from(mode, raw):
"""Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes"""
if mode == "RGBA":
return raw
out = bytearray()
if mode == "L":
for v in raw:
out += bytes((v, v, v, 255))
elif mode == "LA":
for i in range(0, len(raw), 2):
out += bytes((raw[i], raw[i], raw[i], raw[i + 1]))
elif mode == "RGB":
for i in range(0, len(raw), 3):
out += raw[i:i + 3] + b"\xff"
else:
raise ValueError(mode)
return bytes(out)
+54
View File
@@ -0,0 +1,54 @@
-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML /
-- X3D case and glTF sample with our readers and writes it back with our writers, printing "<file>\t<hex>" lines for
-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_<i>.wrl, gltf_<i>.wrl, xcase_<i>.x3d, xgltf_<i>.x3d.
local Vrml = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function both(scene: any, wrl: string, x3d: string)
local a = Vrml.encode(scene)
if a then
print(wrl .. "\t" .. hex(a))
end
local b = X3d.encode(scene)
if b then
print(x3d .. "\t" .. hex(b))
end
end
for i, c in Cases do
local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i))
end
end
for i, c in GltfCases do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i))
end
end
if ok and type(X3dCases) == "table" then
for i, c in X3dCases do
local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i))
end
end
end
+241
View File
@@ -0,0 +1,241 @@
# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and
# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files.
# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter)
# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes)
# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate
# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture
import json
VTK_READ = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
def read(p):
imp = vtk.vtkVRMLImporter(); imp.SetFileName(p)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw)
imp.Update()
acts = imp.GetRenderer().GetActors(); acts.InitTraversal()
out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0}
lo, hi = [1e30] * 3, [-1e30] * 3
for i in range(acts.GetNumberOfItems()):
a = acts.GetNextActor()
m = a.GetMapper()
if not m:
continue
m.Update()
d = m.GetInput()
if d is None or d.GetNumberOfPoints() == 0:
continue
out["actors"] += 1
out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips()
out["lines"] += d.GetNumberOfLines()
out["verts"] += d.GetNumberOfVerts()
out["points"] += d.GetNumberOfPoints()
# tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds)
mat = a.GetMatrix()
pts = d.GetPoints()
for j in range(d.GetNumberOfPoints()):
p = pts.GetPoint(j)
w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0))
for k in range(3):
lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k])
if out["actors"]:
out["min"], out["max"] = lo, hi
return out
# one child process per file: vtkVRMLImporter crashes on some valid files
res = []
for p in json.loads(sys.stdin.read()):
r, w = os.pipe()
pid = os.fork()
if pid == 0:
os.close(r)
try:
data = json.dumps(read(p))
except Exception:
data = json.dumps({"failed": True})
os.write(w, data.encode())
os._exit(0)
os.close(w)
chunks = []
while True:
b = os.read(r, 65536)
if not b:
break
chunks.append(b)
os.close(r)
_, status = os.waitpid(pid, 0)
try:
res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True})
except ValueError:
res.append({"failed": True})
print("RESULT " + json.dumps(res))
"""
VTK_EXPORT = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
args = json.loads(sys.stdin.read())
out, gltfs = args["out"], args["gltf"]
made = []
def export(ren, name):
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren)
ren.ResetCamera()
w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write()
x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write()
made.append(name)
def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False):
m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort())
if not scalars:
m.ScalarVisibilityOff()
a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale)
a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2])
if color:
a.GetProperty().SetColor(*color)
return a
# 1. primitives as polygon meshes, transformed, coloured, one with point scalars
ren = vtk.vtkRenderer()
s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8)
ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1)))
c = vtk.vtkConeSource(); c.SetResolution(12)
ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3)))
cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5)
ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9)))
keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()]
el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0)
ren.AddActor(actor(el, (4, 4, 0), scalars=True))
light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8)
ren.AddLight(light)
export(ren, "vtk_shapes")
# 2. lines and points
ren = vtk.vtkRenderer()
ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5)
ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0)))
pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0)
ren.AddActor(actor(pts))
ren.AddActor(actor(keep[2], (0, 0, -4)))
export(ren, "vtk_lines_points")
# 3. a textured plane (PixelTexture) and a strip mesh
ren = vtk.vtkRenderer()
pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2)
img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0)
img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update()
tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort())
a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex)
ren.AddActor(a)
strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort())
ren.AddActor(actor(strip, (0, 3, 0)))
export(ren, "vtk_texture_strips")
# 4. glTF sample models through VTK's glTF importer
for g in gltfs:
try:
imp = vtk.vtkGLTFImporter(); imp.SetFileName(g)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update()
name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0]
export(imp.GetRenderer(), name)
except Exception:
pass
print("RESULT " + json.dumps(made))
"""
def vtk_xform_ok(data):
"""False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation"""
import re
return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data)
def _run(ctx, code, arg):
out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace")
for line in out.split("\n"):
if line.startswith("RESULT "):
return json.loads(line[7:])
raise RuntimeError("vtk script printed no result")
def vtk_read(ctx, paths):
return _run(ctx, VTK_READ, paths) if paths else []
def vtk_export(ctx, outdir, gltfs):
return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs})
FEATURES = {
"feat_proto_use.wrl": """#VRML V2.0 utf8
PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] {
Transform { translation IS where children Shape {
appearance Appearance { material Material { diffuseColor IS col } }
geometry Box { size IS size } } }
}
DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 }
Brick { where 3 0 0 }
Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet {
coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] }
Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S }
""",
"feat_indices.wrl": """#VRML V2.0 utf8
# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE
Shape {
appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } }
geometry IndexedFaceSet {
solid FALSE ccw FALSE
coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] }
coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ]
normal Normal { vector [ 0 0 1, 0 -1 0 ] }
normalPerVertex FALSE normalIndex [ 0 1 ]
color Color { color [ 1 0 0, 0 0 1 ] }
colorPerVertex FALSE
texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] }
texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ]
}
}
Shape { geometry IndexedFaceSet {
coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] }
coordIndex [ 0 1 2 -1 0 2 3 ]
color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } }
""",
"feat_primitives.wrl": """#VRML V2.0 utf8
Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } }
Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } }
Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } }
Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } }
""",
"feat_grid_extrusion.wrl": """#VRML V2.0 utf8
Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2
height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } }
Transform { translation 6 0 0 children Shape { geometry Extrusion {
crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } }
""",
"feat_scene.wrl": """#VRML V2.0 utf8
WorldInfo { title "feature scene" info [ "made for formats-luau" ] }
DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" }
DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 }
DEF Bulb PointLight { location 1 2 3 radius 10 }
DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 }
DEF Sw Switch { whichChoice 1 choice [
Shape { geometry Box { } }
Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] }
LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] }
DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [
Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } }
Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] }
DEF Clock TimeSensor { cycleInterval 4 loop TRUE }
DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] }
DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] }
ROUTE Clock.fraction_changed TO Path.set_fraction
ROUTE Clock.fraction_changed TO Turn.set_fraction
ROUTE Path.value_changed TO Mover.set_translation
ROUTE Turn.value_changed TO Mover.set_rotation
Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } }
Inline { url [ "part.wrl" ] }
""",
}
# the Inline target of feat_scene.wrl
INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"}
+66
View File
@@ -0,0 +1,66 @@
# ANI fixtures (tools/fixtures.py): animated cursors assembled here around ICO / CUR frames written by Pillow (32 x 32
# RGBA; the CUR ones patched from Pillow's ICO with hotspots): with seq + rate chunks, with neither, with INFO text, and
# one with AF_ICON clear (UNSUPPORTED). References: Pillow's decode of every frame, the step order and delays here.
# tests/gen/ani.luau { cases = { { name, data, w, h, steps = { { frame, delay } }, frames = { rgba }, hotspot?,
# title?, unsupported? } } }
import importlib.util, os, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, T = _load("_raster_ref"), _load("_tex_reference")
def chunk(cid, data):
return cid + struct.pack("<I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
def riff_list(kind, items):
return chunk(b"LIST", kind + b"".join(chunk(c, d) for c, d in items))
def ani(icons, steps=None, rates=None, disp=10, flags=1, title=None):
n = len(icons)
ns = len(steps) if steps else n
body = b"ACON" + chunk(b"anih", struct.pack("<9I", 36, n, ns, 32, 32, 32, 1, disp, flags | (2 if steps else 0)))
if title:
body += riff_list(b"INFO", [(b"INAM", title.encode() + b"\0")])
if rates:
body += chunk(b"rate", struct.pack("<%dI" % len(rates), *rates))
if steps:
body += chunk(b"seq ", struct.pack("<%dI" % len(steps), *steps))
body += riff_list(b"fram", [(b"icon", d) for d in icons])
return b"RIFF" + struct.pack("<I", len(body)) + body
def generate(ctx):
w = R.Work(ctx)
try:
for i in range(4):
px = bytes(v for p in range(32 * 32) for v in (((p * (i + 3)) % 256, 40 * i, (p // 32) * 8, 255 if (p + i) % 5 else 0)))
w.png("f%d.png" % i, 32, 32, px)
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nfor i in range(4):\n Image.open('f%%d.png' %% i).save('f%%d.ico' %% i, sizes=[(32, 32)])\n" % w.dir)
icos = [w.read("f%d.ico" % i) for i in range(4)]
# CUR: type 2, the planes / bit count fields of the entry become the hotspot
curs = []
for i, d in enumerate(icos):
b = bytearray(d)
b[2:4] = struct.pack("<H", 2)
b[6 + 4:6 + 8] = struct.pack("<HH", 3 + i, 7)
curs.append(bytes(b))
refs = [T.rgba_from(m, raw) for (m, ww, hh, raw) in T.pillow(ctx, icos)]
cases = []
steps, rates = [0, 1, 2, 1, 3], [6, 12, 6, 30, 3]
cases.append({"name": "seq + rate", "data": ani(icos, steps, rates, title="spinner"), "w": 32, "h": 32,
"steps": [{"frame": s + 1, "delay": r / 60} for s, r in zip(steps, rates)], "frames": refs, "title": "spinner"})
cases.append({"name": "plain", "data": ani(icos[:3], disp=4), "w": 32, "h": 32,
"steps": [{"frame": i + 1, "delay": 4 / 60} for i in range(3)], "frames": refs[:3]})
cases.append({"name": "cursor frames", "data": ani(curs[:2], disp=8), "w": 32, "h": 32,
"steps": [{"frame": i + 1, "delay": 8 / 60} for i in range(2)], "frames": refs[:2], "hotspot": [3, 7]})
cases.append({"name": "raw bitmaps", "data": ani(icos[:1], flags=0), "unsupported": True})
ctx.emit("ani", {"cases": cases})
finally:
w.close()
+204
View File
@@ -0,0 +1,204 @@
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
import importlib.util, math, os, re, struct, subprocess
INPUTS = ["tools/fixtures/_model_ref.py"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def assimp_src():
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
# ---------------------------------------------------------------------------------------------------- B3D writer
def chunk(tag, *parts):
body = b"".join(parts)
return tag.encode() + struct.pack("<I", len(body)) + body
def cstr(s):
return s.encode() + b"\0"
def f32(*v):
return struct.pack("<%df" % len(v), *v)
def i32(*v):
return struct.pack("<%di" % len(v), *v)
def quat_axis(ax, ay, az, deg):
# Blitz3D order: w, x, y, z
l = math.sqrt(ax * ax + ay * ay + az * az)
h = math.radians(deg) / 2
s = math.sin(h) / l
return (math.cos(h), ax * s, ay * s, az * s)
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
# 8 corners, 12 triangles; split between the brushes round-robin by face
verts = []
for i in range(8):
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
v = f32(x, y, z)
if flags & 1:
l = math.sqrt(x * x + y * y + z * z)
v += f32(x / l, y / l, z / l)
if flags & 2:
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
for s in range(sets):
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
verts.append(v)
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
tris = []
for a, b, c, d in quads:
tris += [(a, b, c), (a, c, d)]
tchunks = []
for k, br in enumerate(brushes):
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
def textured():
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
brus = chunk("BRUS", i32(2),
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
data = chunk("BB3D", i32(1), texs, brus, root)
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
def pivots():
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
def skinned():
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
verts, tris = [], []
for ring in range(3):
for k in range(4):
a = math.radians(90 * k)
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
for ring in range(2):
for k in range(4):
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
data = chunk("BB3D", i32(1), root)
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
# ---------------------------------------------------------------------------------------------------- references
def info(ctx, path):
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {"failed": True}
out = {}
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
return out
def ptv(ctx, path, tmp):
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
out = os.path.join(tmp, "ptv.obj")
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
vs, area, vol = [], 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) for x in p[1:]]
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
for k in range(1, len(idx) - 1):
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
e1 = [b[j] - a[j] for j in range(3)]
e2 = [c[j] - a[j] for j in range(3)]
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
area += math.sqrt(sum(x * x for x in cr)) / 2
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
os.remove(out)
return {"min": lo, "max": hi, "area": area, "volume": vol}
def generate(ctx):
M = ref_module(ctx)
tmp = M.tempdir()
cases = []
src = assimp_src()
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
p = os.path.join(src, "test", rel)
if not os.path.exists(p):
continue
d = os.path.dirname(p)
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
data, want = fn()
p = os.path.join(tmp, name + ".b3d")
with open(p, "wb") as f:
f.write(data)
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
for c in cases:
a = info(ctx, c["path"])
if not a.get("failed"):
a.update(ptv(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("b3d_cases", cases)
# a 1x1 PNG (texture data for the generated files)
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")
+119
View File
@@ -0,0 +1,119 @@
# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1
# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder
# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them.
# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h,
# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H)
# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau
import importlib.util, math, os, random, struct
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98}
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16}
BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31]
def blocks(rng, kind, n, mode=None):
out = bytearray()
for _ in range(n):
b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind]))
if kind == "bc7" and mode is not None:
b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode)
elif kind.startswith("bc6h") and mode is not None:
bitsn = 2 if mode < 2 else 5
b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode
out += b
return bytes(out)
def test_image(w, h, rng, alpha):
px = bytearray()
for y in range(h):
for x in range(w):
r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0))
g = int(255 * x / (w - 1))
b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40
n = rng.randrange(-12, 13)
r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)]
a = 255
if alpha:
a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255
px += bytes((r, g, b, a))
return bytes(px)
def psnr(a, b, channels):
se, n = 0, 0
for i in range(0, len(a), 4):
for c in channels:
d = a[i + c] - b[i + c]
se += d * d
n += 1
return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se)
def generate(ctx):
rng = random.Random(7)
cases = []
def add(name, kind, w, h, data):
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"):
add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64))
add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8))
for m in range(8):
add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m))
add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12))
for kind in ("bc6h", "bc6hs"):
for m in BC6_HEADERS:
add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m))
# Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit)
files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases]
for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)):
c["pillow"] = R.rgba_from(mode, raw)
# Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats
gj, gi = [], []
for i, c in enumerate(cases):
if c["kind"] in R.GODOT:
gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h")))
gi.append(i)
for i, out in zip(gi, R.godot(ctx, gj)):
cases[i]["godot"] = out
# encoder baselines: Pillow's encoder on the same images, decoded by Pillow
enc = []
for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)):
px = test_image(w, h, rng, alpha)
e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}}
enc.append(e)
import tempfile, shutil
work = tempfile.mkdtemp(prefix="formats-bcn-")
try:
for i, e in enumerate(enc):
open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"])
code = ("import os\nfrom PIL import Image\nw=%r\n"
"for i, (W, H) in enumerate(%r):\n"
" im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n"
" for pf in ('DXT1','DXT5','BC5'):\n"
" p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n"
" (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n"
" back=Image.open(p).convert('RGBA')\n"
" open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc])
ctx.python(["pillow"], code)
for i, e in enumerate(enc):
for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))):
back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read()
e["psnr"][kind] = psnr(e["rgba"], back, ch)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("bcn", {"cases": cases, "enc": enc})
# bench: a 512 x 512 image, and random BC7 blocks of every mode
w = h = 256
px = test_image(w, h, rng, True)
bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)),
"bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)}
ctx.emit("bcn_bench", bench)
+332
View File
@@ -0,0 +1,332 @@
# DDS fixtures (tools/fixtures.py):
# - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H /
# BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by
# ImageMagick (none / DXT1 / DXT5 with mip maps);
# - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed,
# shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold;
# - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo.
# Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow
# (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values.
# tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w,
# h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } }
import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/dds", "src/Formats/codecs/image/Bcn", "src/Formats/codecs/image/Texture.luau"]
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16}
DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4",
80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"}
FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"}
def png(w, h, rgba):
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
def source(w, h, salt=0):
out = bytearray()
for y in range(h):
for x in range(w):
r = x / max(1, w - 1)
g = y / max(1, h - 1)
b = ((x * 7 + y * 13 + salt * 31) % 64) / 63
a = ((x + y + salt) % 5) / 4
out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a))
return bytes(out)
def layout(data):
"""an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])"""
flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32])
pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack("<I4s5I", data[80:108])
caps2 = struct.unpack("<I", data[112:116])[0]
mips = max(1, mips if flags & 0x20000 else 1)
off, layers, fmt, cube = 128, 1, None, False
if pf_flags & 4 and fourcc == b"DX10":
dxgi, dim, misc, arr = struct.unpack("<4I", data[128:144])
off, layers = 148, max(1, arr)
fmt = DXGI_BC.get(dxgi) or ("dxgi%d" % dxgi)
cube = bool(misc & 4)
volume = dim == 4
elif pf_flags & 4:
fmt = FOURCC_BC[fourcc]
volume = bool(caps2 & 0x200000)
cube = bool(caps2 & 0x200)
else:
fmt = "rgb%d" % bits
volume = bool(caps2 & 0x200000)
cube = bool(caps2 & 0x200)
d0 = max(1, depth) if volume else 1
count = layers * (6 if cube else 1)
out = []
for layer in range(count):
lw, lh, ld = w, h, d0
for level in range(mips):
if fmt in BLOCK:
size = ((lw + 3) // 4) * ((lh + 3) // 4) * BLOCK[fmt]
elif fmt.startswith("rgb"):
size = lw * lh * bits // 8
else:
size = lw * lh * 4 # dxgi28 / 87 (the only uncompressed DX10 ones nvassemble writes)
for s in range(ld):
out.append((level, layer, s, lw, lh, fmt, off, size))
off += size
lw, lh, ld = max(1, lw // 2), max(1, lh // 2), max(1, ld // 2)
return {"w": w, "h": h, "mips": mips, "layers": layers, "cube": cube, "volume": volume, "depth": d0, "masks": (rm, gm, bm, am), "bits": bits}, out
def mask_decode(raw, bits, masks):
"""legacy bit-mask pixels -> rgba8 with rounding (the Texel rule)"""
out = bytearray()
nb = bits // 8
for i in range(0, len(raw), nb):
v = int.from_bytes(raw[i:i + nb], "little")
px = []
for k, m in enumerate(masks):
if m == 0:
px.append(255 if k == 3 else 0)
continue
sh = (m & -m).bit_length() - 1
mx = m >> sh
px.append(int(((v & m) >> sh) / mx * 255 + 0.5))
out += bytes(px)
return bytes(out)
def references(ctx, cases):
"""fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H"""
pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], []
for c in cases:
info, surf = layout(c["data"])
c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d"))
c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"]
c["surfaces"] = []
for (level, layer, s, w, h, fmt, off, size) in surf:
if level > 0 and (layer > 0 or s > 0):
continue
sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0}
raw = c["data"][off:off + size]
c["surfaces"].append(sd)
if fmt == "bc6h":
gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True))
gd_targets.append(sd)
elif fmt in BLOCK:
dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt]
pil_files.append(R.dds_dx10(w, h, dx, raw))
pil_targets.append((sd, fmt))
elif fmt.startswith("rgb"):
sd["rgba"] = mask_decode(raw, info["bits"], info["masks"])
elif fmt == "dxgi28":
sd["rgba"] = raw
elif fmt == "dxgi87":
sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3))
for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)):
rgba = R.rgba_from(mode, raw)
if fmt == "bc5":
rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba))
sd["rgba"] = rgba
for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)):
sd["floats"] = out
def hand_cases(rng):
"""uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)"""
W, H = 5, 3
cases = []
def f32(v):
return struct.unpack("<f", struct.pack("<f", v))[0]
def half(v):
return struct.unpack("<e", struct.pack("<e", v))[0]
def q8(v):
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
def add(name, dds, texels):
"""texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules"""
cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t),
"floats": b"".join(struct.pack("<4f", *t) for t in texels)})
# floats
vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)]
data = b"".join(struct.pack("<4f", *v) for v in vals)
add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals])
data = b"".join(struct.pack("<4e", *v) for v in vals)
add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals])
add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("<I", 113), data), [tuple(half(x) for x in v) for v in vals])
data = b"".join(struct.pack("<f", v[0]) for v in vals)
add("dxgi R32_FLOAT (grey)", R.dds_dx10(W, H, 41, data), [(f32(v[0]),) * 3 + (1.0,) for v in vals])
data = b"".join(struct.pack("<2e", v[0], v[1]) for v in vals)
add("dxgi R16G16_FLOAT", R.dds_dx10(W, H, 34, data), [(half(v[0]), half(v[1]), 0.0, 1.0) for v in vals])
data = b"".join(struct.pack("<3f", *v[:3]) for v in vals)
add("dxgi R32G32B32_FLOAT", R.dds_dx10(W, H, 6, data), [tuple(f32(x) for x in v[:3]) + (1.0,) for v in vals])
# unorm / snorm
u16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W * H)]
add("dxgi R16G16B16A16_UNORM", R.dds_dx10(W, H, 11, b"".join(struct.pack("<4H", *v) for v in u16)),
[tuple(x / 65535 for x in v) for v in u16])
add("d3dfmt 36 (A16B16G16R16)", R.dds_fourcc(W, H, struct.pack("<I", 36), b"".join(struct.pack("<4H", *v) for v in u16)),
[tuple(x / 65535 for x in v) for v in u16])
s8 = [tuple(rng.randrange(-128, 128) for _ in range(4)) for _ in range(W * H)]
cases_s8 = [tuple(max(x, -127) / 127 for x in v) for v in s8]
cases.append({"name": "dxgi R8G8B8A8_SNORM", "data": R.dds_dx10(W, H, 31, b"".join(struct.pack("<4b", *v) for v in s8)),
"rgba8": bytes(max(x, -127) + 128 for v in s8 for x in v),
"floats": b"".join(struct.pack("<4f", *v) for v in cases_s8)})
u8 = [tuple(rng.randrange(256) for _ in range(4)) for _ in range(W * H)]
add("dxgi R8_UNORM (grey)", R.dds_dx10(W, H, 61, bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
add("dxgi R8G8_UNORM", R.dds_dx10(W, H, 49, bytes(x for v in u8 for x in v[:2])), [(v[0] / 255, v[1] / 255, 0.0, 1.0) for v in u8])
add("dxgi A8_UNORM", R.dds_dx10(W, H, 65, bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
add("dxgi B8G8R8X8_UNORM", R.dds_dx10(W, H, 88, bytes(x for v in u8 for x in (v[2], v[1], v[0], 7))),
[(v[0] / 255, v[1] / 255, v[2] / 255, 1.0) for v in u8])
add("dxgi R16_UNORM (grey)", R.dds_dx10(W, H, 56, b"".join(struct.pack("<H", v[0]) for v in u16)), [(v[0] / 65535,) * 3 + (1.0,) for v in u16])
# packed
p32 = [rng.getrandbits(32) for _ in range(W * H)]
add("dxgi R10G10B10A2_UNORM", R.dds_dx10(W, H, 24, b"".join(struct.pack("<I", v) for v in p32)),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
def uf(v, mb):
e, m = v >> mb, v & ((1 << mb) - 1)
if e == 0:
return m / (1 << mb) * 2 ** -14
return (1 + m / (1 << mb)) * 2 ** (e - 15)
p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31
add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("<I", v) for v in p11)),
[(uf(v & 2047, 6), uf((v >> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11])
add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("<I", v) for v in p32)),
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
p16 = [rng.getrandbits(16) for _ in range(W * H)]
add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("<H", v) for v in p16)),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
# legacy masks
def legacy(bits, flags, masks, data):
pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks)
return R.dds_header(W, H, pf) + data
add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("<H", v) for v in p16)),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v) for v in p32)),
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v)[:3] for v in p32)),
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("<I", v) for v in p32)),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))),
[(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8])
add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
# YUY2 (BT.601 limited range)
def ycc(y, u, v):
c, d, e = 1.164 * (y - 16), u - 128, v - 128
cl = lambda x: max(0, min(255, int(math.floor(x + 0.5))))
return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255)
W2 = 6
yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2))
exp = []
for y in range(H):
for x in range(W2):
q = y * W2 * 2 + (x // 2) * 4
exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3]))
pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0)
cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)})
return cases
def generate(ctx):
rng = random.Random(5)
work = tempfile.mkdtemp(prefix="formats-dds-")
try:
cases = _tools(ctx, work)
references(ctx, cases)
hand = hand_cases(rng)
ours = _ours(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours})
def _tools(ctx, work):
cases = []
for name, w, h in (("a", 37, 23), ("b", 64, 32)):
with open(os.path.join(work, name + ".png"), "wb") as f:
f.write(png(w, h, source(w, h)))
jobs = []
for src in ("a", "b"):
for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"):
jobs.append((src, fl, []))
jobs.append((src, "-bc1", ["-nomips", "-dds10"]))
jobs.append(("a", "-bc6", ["-nomips"]))
script = []
for src, fl, extra in jobs:
out = "%s%s%s.dds" % (src, fl, "".join(extra))
script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out))
for i in range(6):
with open(os.path.join(work, "f%d.png" % i), "wb") as f:
f.write(png(16, 16, source(16, 16, i + 1)))
faces = " ".join("f%d.png" % i for i in range(6))
script.append("nvassemble -cube %s -o cube.dds" % faces)
script.append("nvassemble -array f0.png f1.png f2.png -o array.dds")
script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds")
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))])
im = []
for comp in ("none", "dxt1", "dxt5"):
im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp))
ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))])
names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")]
for n in names:
cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()})
return cases
def _ours(ctx, work):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "dds"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
out = []
pil, pil_idx = [], []
names = sorted(files)
for n in names:
with open(os.path.join(work, n), "wb") as f:
f.write(files[n])
info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace")
blocks = {}
for part in info.split("== ")[1:]:
n, body = part.split("\n", 1)
blocks[n.strip()] = body
for i, n in enumerate(names):
body = blocks.get(n, "")
def field(key):
for line in body.split("\n"):
if line.strip().startswith(key):
return line.split(":", 1)[1].strip()
return ""
e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0),
"mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"),
"caps2": field("Caps 2")}
out.append(e)
if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")):
pil.append(files[n])
pil_idx.append(i)
for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)):
out[i]["pillow"] = R.rgba_from(mode, raw)
out[i]["pillowMode"] = mode
return out
+7 -3
View File
@@ -1,8 +1,8 @@
# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them):
# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG +
# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of
# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT /
# ASS subtitles.
# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a
# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py
# (song_basic), and SRT / WebVTT / ASS subtitles.
# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } }
import importlib.util, os, struct, tempfile
@@ -91,6 +91,9 @@ def generate(ctx):
"-c:a", "aac", "-b:a", "64k"]),
("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]),
("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]),
("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff",
"-flags", "+ilme+ildct",
"-c:a", "mp2", "-b:a", "64k"]),
):
out = os.path.join(d, name)
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out])
@@ -107,6 +110,7 @@ def generate(ctx):
"mp4Bytes": "clip.mp4",
"aviBytes": "clip.avi",
"webmBytes": "clip.webm",
"tsBytes": "clip.ts",
"midiBytes": "tune.mid",
"sf2Bytes": "bank.sf2",
"modBytes": "song.mod",
+17
View File
@@ -0,0 +1,17 @@
# Docs inputs for the Draco section of docs/guide/scene.md (tools/fixtures.py, tools/docs_check.py): the Khronos Box
# sample (tests/fixtures/gltf) compressed with KHR_draco_mesh_compression by draco_transcoder 1.5.7 (nix).
# tests/gen/docs_draco.luau { files = { [name] = bytes }, vars = { dracoGlbBytes = "Box_draco.glb" } }
import importlib.util, os, subprocess, tempfile
INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf/Box"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
draco = subprocess.run(["nix", "build", "nixpkgs#draco", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip().split("\n")[-1]
out = os.path.join(tempfile.mkdtemp(prefix="formats-docs-draco-"), "Box_draco.glb")
subprocess.run([os.path.join(draco, "bin", "draco_transcoder"), "-i", os.path.join(ctx.root, "tests", "fixtures", "gltf", "Box", "glTF-Binary", "Box.glb"), "-o", out],
capture_output=True, check=True)
dc.emit_inputs(ctx, {"Box_draco.glb": open(out, "rb").read()}, {"dracoGlbBytes": "Box_draco.glb"})
+33
View File
@@ -0,0 +1,33 @@
# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them):
# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track
# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg.
# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } }
import importlib.util, os, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check")
fli = load(ctx, "fixtures/fli")
smk = load(ctx, "fixtures/smk")
v = load(ctx, "fixtures/_video")
files = {}
w, h, n = 64, 48, 10
imgs = fli.idx_frames(w, h, n, 256, 5)
frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])]
frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames)
files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7)
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "cinepak.mov")
v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out])
files["cinepak.mov"] = open(out, "rb").read()
dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"})
+20
View File
@@ -0,0 +1,20 @@
# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a
# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video.
# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "clip.ogv")
subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora",
"-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True)
files = {"clip.ogv": open(out, "rb").read()}
dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"})
+137
View File
@@ -0,0 +1,137 @@
# Draco fixtures (tools/fixtures.py): every .drc file of Google's Draco test data (bitstreams 0.9 - 2.2, read from the
# nixpkgs draco source, never committed) and files made here by draco_encoder 1.5.7 (nix) from the test data meshes
# and generated ones (a UV sphere with seams, a noisy grid, a coloured PLY), at every compression level (sequential,
# Edgebreaker standard / valence; difference, parallelogram, constrained multi-parallelogram, portable tex coords and
# geometric normal predictions), several quantizations (up to 30 bits) and as point clouds. The reference values come
# from libdraco itself: tools/fixtures/_draco_dump.cc, compiled here against nixpkgs#draco, prints the decoded points,
# faces and each attribute's bytes per point.
# tests/gen/draco_cases.luau { { name, data, error? = true, points, faces, indices = crc, attrs = { { type, dataType,
# components, normalized, uniqueId, crc } } } }
import math, os, subprocess, tempfile, zlib
INPUTS = ["tools/fixtures/_draco_dump.cc"]
def store_path(attr):
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def uv_sphere(rings=12, segs=20):
# an OBJ sphere with a UV seam and poles: vertices shared by position, split by UV
v, vt, vn, f = [], [], [], []
for r in range(rings + 1):
th = math.pi * r / rings
for s in range(segs + 1):
ph = 2 * math.pi * s / segs
x, y, z = math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)
v.append((x, y, z))
vn.append((x, y, z))
vt.append((s / segs, r / rings))
w = segs + 1
for r in range(rings):
for s in range(segs):
a, b, c, d = r * w + s + 1, r * w + s + 2, (r + 1) * w + s + 2, (r + 1) * w + s + 1
if r > 0:
f.append((a, b, c))
if r < rings - 1:
f.append((a, c, d))
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt] + ["vn %.6f %.6f %.6f" % p for p in vn]
out += ["f %d/%d/%d %d/%d/%d %d/%d/%d" % (a, a, a, b, b, b, c, c, c) for a, b, c in f]
return "\n".join(out) + "\n"
def noisy_grid(rng, n=24):
# a height field with a hole and per-vertex UVs: boundaries, holes and parallelogram predictions
v, vt, f = [], [], []
for j in range(n):
for i in range(n):
v.append((i * 0.1, rng.uniform(-0.05, 0.05), j * 0.1))
vt.append((i / (n - 1), j / (n - 1)))
for j in range(n - 1):
for i in range(n - 1):
if 8 <= i < 12 and 8 <= j < 12:
continue
a, b, c, d = j * n + i + 1, j * n + i + 2, (j + 1) * n + i + 2, (j + 1) * n + i + 1
f.append((a, b, c))
f.append((a, c, d))
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt]
out += ["f %d/%d %d/%d %d/%d" % (a, a, b, b, c, c) for a, b, c in f]
return "\n".join(out) + "\n"
def colored_ply(rng, n=200):
# an ASCII point set / mesh with colours (u8) and a generic float property
pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
faces = [(i, i + 1, i + 2) for i in range(0, n - 2, 3)]
head = ["ply", "format ascii 1.0", "element vertex %d" % n, "property float x", "property float y", "property float z",
"property uchar red", "property uchar green", "property uchar blue", "property uchar alpha",
"element face %d" % len(faces), "property list uchar int vertex_indices", "end_header"]
body = ["%.5f %.5f %.5f %d %d %d %d" % (p[0], p[1], p[2], rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for p in pts]
body += ["3 %d %d %d" % t for t in faces]
return "\n".join(head + body) + "\n"
def parse_dump(txt):
out = {"attrs": []}
for line in txt.split("\n"):
parts = line.split(" ")
if parts[0] == "ERROR":
return {"error": True}
if parts[0] == "POINTS":
out["points"] = int(parts[1])
elif parts[0] == "FACES":
out["faces"] = int(parts[1])
out["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
elif parts[0] == "ATTR":
out["attrs"].append({"type": int(parts[1]), "dataType": int(parts[2]), "components": int(parts[3]),
"normalized": parts[4] == "1", "uniqueId": int(parts[5]),
"crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))})
return out
def generate(ctx):
draco = store_path("draco")
src = store_path("draco.src")
testdata = os.path.join(src, "testdata")
tmp = tempfile.mkdtemp(prefix="formats-draco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
encoder = os.path.join(draco, "bin", "draco_encoder")
files = [] # (name, path)
for f in sorted(os.listdir(testdata)):
if f.endswith(".drc"):
files.append(("testdata/" + f, os.path.join(testdata, f)))
rng = ctx.rng(31)
gen_inputs = {"uvsphere.obj": uv_sphere(), "grid.obj": noisy_grid(rng), "colored.ply": colored_ply(rng)}
for name, text in gen_inputs.items():
with open(os.path.join(tmp, name), "w") as fh:
fh.write(text)
inputs = [(n, os.path.join(tmp, n)) for n in gen_inputs] + [(n, os.path.join(testdata, n)) for n in
("cube_att.obj", "test_nm.obj", "sphere.obj", "cube_quads.obj", "test_generic.ply", "Box.ply")]
variants = [("cl%d" % cl, ["-cl", str(cl)]) for cl in range(11)]
variants += [("q14", ["-qp", "14", "-qt", "12", "-qn", "10"]), ("q20", ["-qp", "20", "-qt", "16", "-qn", "14", "-qg", "12"]),
("q30", ["-qp", "30", "-qt", "30", "-qn", "30", "-qg", "30"]), ("q30cl10", ["-cl", "10", "-qp", "24", "-qt", "24", "-qn", "24"]),
("raw", ["-qp", "0", "-qt", "0", "-qn", "0", "-qg", "0"]), ("meta", ["--metadata"]), ("poly", ["-preserve_polygons"]),
("pc", ["-point_cloud", "-cl", "0"]), ("pckd", ["-point_cloud"])]
for iname, ipath in inputs:
for vname, args in variants:
out = os.path.join(tmp, "%s.%s.drc" % (iname, vname))
r = subprocess.run([encoder, "-i", ipath, "-o", out] + args, capture_output=True)
if r.returncode == 0 and os.path.exists(out):
files.append(("enc/%s.%s" % (iname, vname), out))
# the large bunny once (Edgebreaker valence + normals)
out = os.path.join(tmp, "bunny.drc")
if subprocess.run([encoder, "-i", os.path.join(testdata, "bunny_norm.obj"), "-o", out, "-cl", "7"], capture_output=True).returncode == 0:
files.append(("enc/bunny_norm.obj.cl7", out))
cases = []
for name, path in files:
ref = parse_dump(subprocess.run([dump, path], capture_output=True).stdout.decode())
case = {"name": name, "data": open(path, "rb").read()}
case.update(ref)
cases.append(case)
ctx.emit("draco_cases", cases)
+128
View File
@@ -0,0 +1,128 @@
# ETC fixtures (tools/fixtures.py): random ETC1 / ETC2 / EAC blocks, sorted by mode so that every ETC2 mode
# (individual, differential, T, H, planar; punch-through opaque and transparent) and every EAC multiplier case is
# covered, decoded by Godot 4 (etcpak's decoder, through Image.decompress).
# tests/gen/etc.luau { { name, kind, w, h, data, godot (rgba8 bytes) } }
import importlib.util, os, random
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
def mode(b, punch):
"""the ETC2 mode of an 8-byte colour block"""
hi = int.from_bytes(b[:4], "big")
if not punch and not (hi >> 1) & 1:
return "individual"
def s3(v):
return v - 8 if v >= 4 else v
r, g, bb = (hi >> 27) & 31, (hi >> 19) & 31, (hi >> 11) & 31
dr, dg, db = s3((hi >> 24) & 7), s3((hi >> 16) & 7), s3((hi >> 8) & 7)
if not 0 <= r + dr <= 31:
return "T"
if not 0 <= g + dg <= 31:
return "H"
if not 0 <= bb + db <= 31:
return "planar"
return "differential"
def colour_blocks(rng, n, want, punch=False, opaque=None):
out = bytearray()
while len(out) < n * 8:
b = bytearray(rng.getrandbits(8) for _ in range(8))
if opaque is not None:
b[3] = (b[3] & 0xFD) | (2 if opaque else 0)
if mode(b, punch) == want:
out += b
return bytes(out)
def eac_blocks(rng, n, zero_mult=False):
out = bytearray()
for _ in range(n):
b = bytearray(rng.getrandbits(8) for _ in range(8))
if zero_mult:
b[1] &= 0x0F
out += b
return bytes(out)
EAC = [[-3, -6, -9, -15, 2, 5, 8, 14], [-3, -7, -10, -13, 2, 6, 9, 12], [-2, -5, -8, -13, 1, 4, 7, 12],
[-2, -4, -6, -13, 1, 3, 5, 12], [-3, -6, -8, -12, 2, 5, 7, 11], [-3, -7, -9, -11, 2, 6, 8, 10],
[-4, -7, -8, -11, 3, 6, 7, 10], [-3, -5, -8, -11, 2, 4, 7, 10], [-2, -6, -8, -10, 1, 5, 7, 9],
[-2, -5, -8, -10, 1, 4, 7, 9], [-2, -4, -8, -10, 1, 3, 7, 9], [-2, -5, -7, -10, 1, 4, 6, 9],
[-3, -4, -7, -10, 2, 3, 6, 9], [-1, -2, -3, -10, 0, 1, 2, 9], [-4, -6, -8, -9, 3, 5, 7, 8],
[-3, -5, -7, -9, 2, 4, 6, 8]]
def s11(c):
"""signed EAC R11 / RG11 -> the 11-bit values (-1023..1023) per pixel and channel, as a flat list"""
two = c["kind"] == "eac_rg11s"
w, h, data = c["w"], c["h"], c["data"]
bw = (w + 3) // 4
out = [0] * (w * h * 2)
step = 16 if two else 8
for bi in range(len(data) // step):
bx, by = bi % bw, bi // bw
for ch in range(2 if two else 1):
b = data[bi * step + ch * 8: bi * step + ch * 8 + 8]
base = b[0] - 256 if b[0] >= 128 else b[0]
base = max(base, -127)
mult, tab = b[1] >> 4, EAC[b[1] & 15]
bits = int.from_bytes(b[2:], "big")
for i in range(16):
m = tab[(bits >> (45 - 3 * i)) & 7]
v = base * 8 + (m * mult * 8 if mult else m)
v = max(-1023, min(1023, v))
x, y = bx * 4 + i // 4, by * 4 + i % 4
if x < w and y < h:
out[(y * w + x) * 2 + ch] = v
return out
def generate(ctx):
rng = random.Random(11)
cases = []
def add(name, kind, w, h, data):
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
add("etc1 individual", "etc1", 16, 16, colour_blocks(rng, 16, "individual"))
add("etc1 differential", "etc1", 16, 16, colour_blocks(rng, 16, "differential"))
add("etc1 random 13x6", "etc1", 13, 6, bytes(rng.getrandbits(8) for _ in range(8 * 8)))
for m in ("individual", "differential", "T", "H", "planar"):
add("etc2_rgb " + m, "etc2_rgb", 16, 16, colour_blocks(rng, 16, m))
for m in ("differential", "T", "H", "planar"):
for op in (True, False):
add("etc2_rgba1 %s %s" % (m, "opaque" if op else "transparent"), "etc2_rgba1", 16, 16,
colour_blocks(rng, 16, m, True, op))
for m in ("individual", "differential", "T", "H", "planar"):
rgba = bytearray()
col = colour_blocks(rng, 16, m)
alpha = eac_blocks(rng, 16, m == "planar")
for i in range(16):
rgba += alpha[i * 8:i * 8 + 8] + col[i * 8:i * 8 + 8]
add("etc2_rgba " + m, "etc2_rgba", 16, 16, bytes(rgba))
for kind in ("eac_r11", "eac_r11s"):
add(kind, kind, 16, 16, eac_blocks(rng, 16))
add(kind + " multiplier 0", kind, 8, 8, eac_blocks(rng, 4, True))
for kind in ("eac_rg11", "eac_rg11s"):
add(kind, kind, 16, 12, eac_blocks(rng, 24))
add("etc2_rgb 10x5", "etc2_rgb", 10, 5, bytes(rng.getrandbits(8) for _ in range(6 * 8)))
# Godot cannot decode RGB A1 or the signed EAC kinds: A1 blocks go through it as ETC2 RGB (the test checks the
# punch-through rules on top; the opaque bit is set for Godot, else ETC2 RGB reads the individual mode), signed EAC is checked against s11() below (the KDFS 1.3 rule, written here)
jobs, idx = [], []
for i, c in enumerate(cases):
k = "etc2_rgb" if c["kind"] == "etc2_rgba1" else c["kind"]
if k in ("eac_r11s", "eac_rg11s"):
c["spec"] = s11(c)
else:
data = c["data"]
if c["kind"] == "etc2_rgba1": # with the opaque bit set: ETC2 RGB's differential / T / H / planar
data = bytes(v | 2 if i % 8 == 3 else v for i, v in enumerate(data))
jobs.append((data, c["w"], c["h"], R.GODOT[k], False))
idx.append(i)
for i, out in zip(idx, R.godot(ctx, jobs)):
cases[i]["godot"] = out
ctx.emit("etc", cases)
+195
View File
@@ -0,0 +1,195 @@
# OpenEXR fixtures (tools/fixtures.py): files written by the OpenEXR 3.5 python bindings (every compression NONE /
# RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, odd sizes, an offset data window, decreasing line order, a
# Y-only image, a layer (diffuse.R ...), subsampled channels, PXR24 / B44 / DWAA for the UNSUPPORTED path), tiled
# versions by exrmaketiled (one level, mip-map with unfiltered levels, rip-map, round up, several compressions),
# multipart files by exrmultipart; our encoder's files (tools/fixtures/_tex_encode.luau -a exr) read back by the
# bindings and exrheader. References: the bindings' read of each file (RGBA as little-endian f32; Y as grey).
# tests/gen/exr.luau { cases = { { name, data, w, h, floats?, unsupported?, opts?, mips? } }, ours = { { name,
# data, floats, compression, header_ok } } }
# tests/gen/exr_bench.luau a 512 x 256 half RGBA image in ZIP and PIZ
import os, shutil, subprocess, tempfile
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/exr"]
WRITE = r'''
import OpenEXR, numpy as np, os, sys, json
w = sys.argv[1]
rng = np.random.default_rng(3)
def win(x0, y0, x1, y1):
return (np.array([x0, y0], dtype=np.int32), np.array([x1, y1], dtype=np.int32))
def img(h, wd, kind="f2"):
y, x = np.mgrid[0:h, 0:wd]
r = (x / max(1, wd - 1)) * 3 - 0.5
g = np.sin(y * 0.7) * 0.5 + 0.5
b = rng.random((h, wd)) * 0.01 + (x * y % 7) * 0.2
a = ((x + y) % 4) / 3.0
return [c.astype(kind) for c in (r, g, b, a)]
def save(name, header, channels):
h = {"type": OpenEXR.scanlineimage}
h.update(header)
OpenEXR.File(h, channels).write(os.path.join(w, name))
C = {"none": OpenEXR.NO_COMPRESSION, "rle": OpenEXR.RLE_COMPRESSION, "zips": OpenEXR.ZIPS_COMPRESSION,
"zip": OpenEXR.ZIP_COMPRESSION, "piz": OpenEXR.PIZ_COMPRESSION}
names = []
for cn, c in C.items():
r, g, b, a = img(23, 37)
save("half_rgba_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b, "A": a})
r, g, b, a = img(19, 41, "f4")
save("float_rgb_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
r, g, b, a = img(37, 70)
u = (rng.random((37, 70)) * 100000).astype("uint32")
save("mixed_%s.exr" % cn, {"compression": c, "lineOrder": OpenEXR.DECREASING_Y}, {"R": r, "G": g.astype("f4"), "B": u})
names += ["half_rgba_%s.exr" % cn, "float_rgb_%s.exr" % cn, "mixed_%s.exr" % cn]
r, g, b, a = img(20, 30)
save("window_zip.exr", {"compression": C["zip"], "dataWindow": win(5, -3, 34, 16), "displayWindow": win(0, 0, 39, 19)}, {"R": r, "G": g, "B": b, "A": a})
save("grey_piz.exr", {"compression": C["piz"]}, {"Y": r})
save("layer_zips.exr", {"compression": C["zips"]}, {"diffuse.R": r, "diffuse.G": g, "diffuse.B": b, "R": a, "G": a, "B": a})
r, g, b, a = img(64, 96)
save("big_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
save("big_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
names += ["window_zip.exr", "grey_piz.exr", "layer_zips.exr", "big_piz.exr", "big_zip.exr"]
y, x = np.mgrid[0:16, 0:24]
Y = (x / 23.0).astype("f2")
sub = (np.mgrid[0:8, 0:12][1] / 11.0).astype("f2")
# subsampled: hand-written (the bindings only write full-resolution channels): NONE, A at 2 x 2, R / G / B full
import struct
def attr(n, t, d):
return n.encode() + b"\0" + t.encode() + b"\0" + struct.pack("<i", len(d)) + d
chl = b""
for n, xs in (("A", 2), ("B", 1), ("G", 1), ("R", 1)):
chl += n.encode() + b"\0" + struct.pack("<iB3xii", 1, 0, xs, xs)
chl += b"\0"
W, H = 24, 16
hdr = (b"\x76\x2f\x31\x01" + struct.pack("<I", 2) + attr("channels", "chlist", chl) + attr("compression", "compression", b"\0") +
attr("dataWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) + attr("displayWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) +
attr("lineOrder", "lineOrder", b"\0") + attr("pixelAspectRatio", "float", struct.pack("<f", 1)) +
attr("screenWindowCenter", "v2f", struct.pack("<2f", 0, 0)) + attr("screenWindowWidth", "float", struct.pack("<f", 1)) + b"\0")
blocks = []
for yy in range(H):
line = b""
if yy % 2 == 0:
line += np.array([(x2 * 2) / 23.0 for x2 in range(W // 2)], dtype="f2").tobytes()
for ch in range(3):
line += Y[yy].tobytes()
blocks.append(struct.pack("<ii", yy, len(line)) + line)
off = len(hdr) + 8 * H
table = b""
for bl in blocks:
table += struct.pack("<Q", off)
off += len(bl)
open(os.path.join(w, "subsampled_none.exr"), "wb").write(hdr + table + b"".join(blocks))
names.append("subsampled_none.exr")
for cn, c in (("pxr24", OpenEXR.PXR24_COMPRESSION), ("b44", OpenEXR.B44_COMPRESSION), ("dwaa", OpenEXR.DWAA_COMPRESSION)):
r, g, b, a = img(8, 8)
save("unsupported_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
r, g, b, a = img(256, 512)
save("bench_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
save("bench_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
print(json.dumps(names))
'''
READ = r'''
import OpenEXR, numpy as np, os, sys, json
w = sys.argv[1]
out = {}
for name in json.loads(sys.argv[2]):
f = OpenEXR.File(os.path.join(w, name), separate_channels=True)
hdr = f.header()
ch = f.channels()
(x0, y0), (x1, y1) = hdr["dataWindow"]
W, H = int(x1 - x0 + 1), int(y1 - y0 + 1)
layer = sys.argv[3] if len(sys.argv) > 3 and name.startswith("layer") else ""
px = np.zeros((H, W, 4), dtype="f4")
px[:, :, 3] = 1
def get(n):
c = ch.get(layer + n)
if c is None:
return None
p = c.pixels.astype("f4")
if p.shape != (H, W):
p = np.repeat(np.repeat(p, c.ySampling, axis=0), c.xSampling, axis=1)[:H, :W]
return p
if get("R") is None and get("Y") is not None:
for k in range(3):
px[:, :, k] = get("Y")
for k, n in enumerate("RGBA"):
p = get(n)
if p is not None:
px[:, :, k] = p
out[name] = {"w": W, "h": H, "floats": px.tobytes().hex(), "compression": str(hdr["compression"]).split(".")[-1]}
print(json.dumps(out))
'''
def generate(ctx):
work = tempfile.mkdtemp(prefix="formats-exr-")
try:
_generate(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def py(ctx, code, *args):
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.openexr p.numpy])"
res = subprocess.run(["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + list(args), capture_output=True)
if res.returncode:
raise RuntimeError("OpenEXR bindings failed: " + res.stderr.decode()[-2000:])
return res.stdout
def _generate(ctx, work):
import json
names = json.loads(py(ctx, WRITE, work))
tiled = []
sh = []
for cn in ("none", "rle", "zip", "piz"):
sh.append("exrmaketiled -o -t 16 8 -z %s half_rgba_zip.exr tiled_%s.exr" % (cn, cn))
tiled.append("tiled_%s.exr" % cn)
sh.append("exrmaketiled -m -t 8 8 -z zip -f R -f G -f B -f A half_rgba_zip.exr tiled_mip.exr")
sh.append("exrmaketiled -m -u -t 8 8 -z piz half_rgba_zip.exr tiled_mip_up.exr")
sh.append("exrmaketiled -r -t 16 16 -z zips half_rgba_zip.exr tiled_rip.exr")
sh.append("exrmaketiled -o -t 8 8 -z zip float_rgb_none.exr tiled_float.exr")
sh.append("exrmaketiled -o -t 7 5 -z zip window_zip.exr tiled_window.exr")
tiled += ["tiled_mip.exr", "tiled_mip_up.exr", "tiled_rip.exr", "tiled_float.exr", "tiled_window.exr"]
sh.append("exrmultipart -combine -i half_rgba_piz.exr::left half_rgba_rle.exr::right tiled_zip.exr::tiles -o multipart.exr")
ctx.nix("openexr", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
ref = json.loads(py(ctx, READ, work, json.dumps(names + tiled), "diffuse."))
cases = []
for n in names + tiled:
r = ref[n]
c = {"name": n, "data": open(os.path.join(work, n), "rb").read(), "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])}
if n.startswith("layer"):
c["layer"] = "diffuse"
if n.startswith("tiled_mip") or n.startswith("tiled_rip"):
c["mips"] = True
cases.append(c)
# multipart: every part against the file it came from
mp = open(os.path.join(work, "multipart.exr"), "rb").read()
for i, (src, pname) in enumerate((("half_rgba_piz.exr", "left"), ("half_rgba_rle.exr", "right"), ("tiled_zip.exr", "tiles"))):
r = ref[src]
cases.append({"name": "multipart part %d (%s)" % (i + 1, pname), "data": mp, "part": i + 1, "partName": pname,
"w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])})
for cn in ("pxr24", "b44", "dwaa"):
cases.append({"name": "unsupported_%s.exr" % cn, "data": open(os.path.join(work, "unsupported_%s.exr" % cn), "rb").read(), "unsupported": True})
ours = _ours(ctx, work)
ctx.emit("exr", {"cases": cases, "ours": ours})
ctx.emit("exr_bench", {"zip": open(os.path.join(work, "bench_zip.exr"), "rb").read(), "piz": open(os.path.join(work, "bench_piz.exr"), "rb").read()})
def _ours(ctx, work):
import json
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "exr"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
names = sorted(files)
for n in names:
open(os.path.join(work, n), "wb").write(files[n])
ref = json.loads(py(ctx, READ, work, json.dumps(names)))
rc = ctx.nix("openexr", ["sh", "-c", "cd %s && for f in %s; do exrheader $f > /dev/null 2>&1; echo $f $?; done" % (work, " ".join(names))]).decode()
ok = {line.split()[0]: line.split()[1] == "0" for line in rc.strip().split("\n")}
return [{"name": n, "data": files[n], "floats": bytes.fromhex(ref[n]["floats"]), "compression": ref[n]["compression"], "headerOk": ok.get(n, False)} for n in names]
+401
View File
@@ -0,0 +1,401 @@
# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64,
# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a
# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY /
# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba).
# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } }
import importlib.util, os, random, struct, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py"]
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def s8(v):
return v & 0xFF
def chunk(typ, body):
if len(body) & 1:
body += b"\0"
return le32(6 + len(body)) + le16(typ) + body
def frame(chunks, magic=0xF1FA):
body = b"".join(chunks)
return le32(16 + len(body)) + le16(magic) + le16(len(chunks)) + bytes(8) + body
# ---------------------------------------------------------------------------------------------------- chunks
def color(entries, six):
"""COLOR_64 / COLOR_256: entries = [(skip, [(r, g, b), ...])]"""
out = le16(len(entries))
for skip, cols in entries:
out += bytes([skip, len(cols) & 0xFF])
for c in cols:
out += bytes(c)
return chunk(11 if six else 4, out)
def runs(seq, maxrun=127):
"""split a sequence into ('rep', value, n) and ('lit', [values]) pieces"""
out, i = [], 0
while i < len(seq):
j = i
while j + 1 < len(seq) and seq[j + 1] == seq[i] and j - i + 1 < maxrun:
j += 1
if j - i >= 2:
out.append(("rep", seq[i], j - i + 1))
i = j + 1
else:
k = i
while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]):
k += 1
k = max(k, i + 1)
out.append(("lit", seq[i:k]))
i = k
return out
def brun_line(units, unit_bytes):
"""BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)"""
out = bytes([0])
for p in runs(units):
if p[0] == "rep":
out += bytes([p[2]]) + p[1]
else:
out += bytes([s8(-len(p[1]))]) + b"".join(p[1])
return out
def brun(img, bpp, pixel_runs, typ=15):
lines = b""
for row in img:
if pixel_runs:
units = [row[x] for x in range(len(row))]
else:
flat = b"".join(row)
units = [flat[i:i + 1] for i in range(len(flat))]
lines += brun_line(units, bpp)
return chunk(typ, lines)
def lc(img, prev):
"""DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes"""
h, w = len(img), len(img[0])
ch = [y for y in range(h) if img[y] != prev[y]]
if not ch:
return chunk(12, le16(0) + le16(0))
y0, y1 = ch[0], ch[-1] + 1
out = le16(y0) + le16(y1 - y0)
for y in range(y0, y1):
row, prow = img[y], prev[y]
packets = []
x = 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
seg = [bytes([v]) for v in row[x:e]]
pieces = runs(seg)
first = True
for p in pieces:
sk = skip if first else 0
first = False
if p[0] == "rep":
packets.append(bytes([sk, s8(-p[2])]) + p[1])
else:
packets.append(bytes([sk, len(p[1])]) + b"".join(p[1]))
x = e
out += bytes([len(packets)]) + b"".join(packets)
return chunk(12, out)
def ss2(img, prev, last_byte=False):
"""DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines"""
h, w = len(img), len(img[0])
out = b""
count = 0
skip_lines = 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body = b""
packets = 0
lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1]
ww = w - (1 if lastop else 0)
words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
i = 0
while i < len(words):
skip = 0
while i < len(words) and words[i] == pwords[i] and skip < 127:
skip += 1
i += 1
if i >= len(words):
break
e = i
while e < len(words) and words[e] != pwords[e] and e - i < 127:
e += 1
first = True
for p in runs(words[i:e]):
sk = skip * 2 if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
i = e
if lastop:
out += le16(0x8000 | row[w - 1])
out += le16(packets) + body
count += 1
return chunk(7, le16(count) + out)
def delta_deep(img, prev, bpp, typ=7):
"""DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)"""
h, w = len(img), len(img[0])
out, count, skip_lines = b"", 0, 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body, packets, x = b"", 0, 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
first = True
for p in runs(row[x:e]):
sk = skip if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
x = e
out += le16(packets) + body
count += 1
return chunk(typ, le16(count) + out)
def copy8(img):
w = len(img[0])
pad = (w + 3) // 4 * 4 - w
return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img)
def copy_deep(img, bpp, typ=16):
w = len(img[0])
body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img)
return le32(6 + len(body)) + le16(typ) + body
# ---------------------------------------------------------------------------------------------------- pictures
def idx_frames(w, h, n, colors, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)]
sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12)
for y in range(sy, sy + 12):
for x in range(sx, sx + 16):
img[y][x] = (200 + t) % colors
for y in range(h // 2, h // 2 + 4):
for x in range(w // 2, w // 2 + 10):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def deep_frames(w, h, n, bpp, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = []
for y in range(h):
row = []
for x in range(w):
v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255)
if 10 + t <= x < 26 + t and 8 <= y < 20:
v = 0x7C00 if bpp == 2 else (250, 10, 10)
if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7:
v = rnd.randrange(65536)
row.append(struct.pack("<H", v) if bpp == 2 else bytes([v[2], v[1], v[0]]))
img.append(row)
out.append(img)
return out
def header(typ, frames, w, h, depth, speed, oframes=(0, 0)):
hd = bytearray(128)
hd[4:6] = le16(typ)
hd[6:8] = le16(frames)
hd[8:10] = le16(w)
hd[10:12] = le16(h)
hd[12:14] = le16(depth)
hd[14:16] = le16(3)
if typ == 0xAF11:
hd[16:18] = le16(speed)
else:
hd[16:20] = le32(speed)
hd[80:84] = le32(oframes[0])
hd[84:88] = le32(oframes[1])
return hd
def file(typ, w, h, depth, speed, frames, prefix=b"", nframes=None):
hd = header(typ, nframes if nframes is not None else len(frames), w, h, depth, speed)
body = prefix + b"".join(frames)
hd[0:4] = le32(128 + len(body))
if typ != 0xAF11 and frames:
hd[80:84] = le32(128 + len(prefix))
hd[84:88] = le32(128 + len(prefix) + len(frames[0]))
return bytes(hd) + body
def pal(n, seed, six):
rnd = random.Random(seed)
m = 64 if six else 256
return [(rnd.randrange(m), rnd.randrange(m), rnd.randrange(m)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- files
def fli_8():
"""FLI (AF11), 70 Hz jiffies: COLOR_64 + BRUN, LC deltas, a BLACK frame, a COPY frame, a palette change, PSTAMP"""
w, h, n = 80, 50, 10
imgs = idx_frames(w, h, n, 256, 1)
frames = [frame([color([(0, pal(256, 1, True))], True), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 4:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy8(imgs[t]), chunk(18, le16(10) + le16(6) + bytes(20))]))
elif t == 7:
frames.append(frame([color([(10, pal(20, 9, True)), (30, pal(5, 10, True))], True), lc(imgs[t], imgs[t - 1])]))
else:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
frames.append(frame([lc(imgs[0], imgs[-1])])) # the ring frame
return file(0xAF11, w, h, 8, 5, frames, nframes=n)
def flc_8():
"""FLC (AF12), ms: a prefix chunk, COLOR_256 + BRUN, SS2 deltas (line skips, last-byte opcode), COPY, BLACK, an
empty frame, COLOR_256 updates"""
w, h, n = 128, 64, 12
imgs = idx_frames(w, h, n, 256, 2)
frames = [frame([color([(0, pal(256, 2, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 3:
imgs[t] = imgs[t - 1]
frames.append(frame([]))
elif t == 6:
frames.append(frame([copy8(imgs[t])]))
elif t == 8:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b""), color([(0, pal(16, 3, False)), (100, pal(50, 4, False))], False)]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1], last_byte=True)]))
prefix = le32(16) + le16(0xF100) + le16(0) + bytes(8)
return file(0xAF12, w, h, 8, 66, frames, prefix=prefix)
def flc_8_odd():
"""FLC 8-bit at an odd size: BRUN, LC, SS2 without the last-byte opcode, COPY with padded rows"""
w, h, n = 61, 37, 6
imgs = idx_frames(w, h, n, 256, 3)
frames = [frame([color([(0, pal(256, 5, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 2:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
elif t == 4:
frames.append(frame([copy8(imgs[t])]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1])]))
return file(0xAF12, w, h, 8, 100, frames)
def flc_deep(typ, depth, bpp, w, h):
"""15 / 16 / 24-bit: BRUN (bytes) or DTA_BRUN (pixels), DELTA / DTA_LC, BLACK, COPY / DTA_COPY"""
n = 7
imgs = deep_frames(w, h, n, bpp, depth)
frames = [frame([brun(imgs[0], bpp, False)])]
for t in range(1, n):
if t == 2:
frames.append(frame([copy_deep(imgs[t], bpp, 16)]))
elif t == 3:
frames.append(frame([brun(imgs[t], bpp, True, 25)]))
elif t == 4:
imgs[t] = [[bytes(bpp)] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy_deep(imgs[t], bpp, 26)]))
else:
frames.append(frame([delta_deep(imgs[t], imgs[t - 1], bpp, 7 if t % 2 else 27)]))
return file(typ, w, h, depth, 50, frames)
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flifx_")
files = [
("anim.fli", fli_8(), 80, 50, 8, 70 / 5),
("anim.flc", flc_8(), 128, 64, 8, 1000 / 66),
("odd.flc", flc_8_odd(), 61, 37, 8, 10),
("rgb15.flc", flc_deep(0xAF12, 16, 2, 63, 40), 63, 40, 15, 20),
("rgb565.flc", flc_deep(0xAF44, 16, 2, 48, 30), 48, 30, 16, 20),
("bgr24.flc", flc_deep(0xAF12, 24, 3, 41, 30), 41, 30, 24, 20),
]
cases = []
for name, data, w, h, depth, rate in files:
path = os.path.join(tmp, name)
open(path, "wb").write(data)
crcs = rgba_crcs(path, w, h)
assert crcs, name
cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs})
ctx.emit("fli_cases", cases)
# tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas)
w, h, n = 320, 200, 10
imgs = idx_frames(w, h, n, 256, 9)
frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n})
+132
View File
@@ -0,0 +1,132 @@
# glTF + Draco fixtures (tools/fixtures.py): KHR_draco_mesh_compression files. The Khronos samples of
# tests/fixtures/gltf compressed by draco_transcoder 1.5.7 (nix) at its default and at a finer quantization, Draco's
# own glTF test files (Box_Draco.glb, BoxMetaDraco) and assimp's 2CylinderEngine (robot.glb: 12 MB, left out), read from the
# nixpkgs sources and never committed. Reference values: every Draco primitive's buffer view decoded by libdraco
# (tools/fixtures/_draco_dump.cc, compiled against nixpkgs#draco): points, faces, the index and per-attribute CRCs.
# tests/gen/gltf_draco.luau { { name, data, files = { uri -> bytes }, original? = { data, files } (the uncompressed
# source), prims = { { mesh, prim, points, faces, indices, attrs = { [name] = { uniqueId,
# dataType, crc } } } } } }
import json, os, struct, subprocess, tempfile, zlib
INPUTS = ["tests/fixtures/gltf", "tools/fixtures/_draco_dump.cc"]
def store_path(attr):
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def load(path):
# -> (doc, bin, files): the JSON, the GLB binary chunk, the sibling files a .gltf refers to
raw = open(path, "rb").read()
files, binchunk = {}, None
if raw[:4] == b"glTF":
off = 12
doc = None
while off + 8 <= len(raw):
n, kind = struct.unpack_from("<II", raw, off)
chunk = raw[off + 8:off + 8 + n]
if kind == 0x4E4F534A:
doc = json.loads(chunk)
elif kind == 0x004E4942:
binchunk = chunk
off += 8 + n
else:
doc = json.loads(raw)
d = os.path.dirname(path)
for b in doc.get("buffers", []) + doc.get("images", []):
uri = b.get("uri")
if uri and not uri.startswith("data:") and os.path.exists(os.path.join(d, uri)):
files[uri] = open(os.path.join(d, uri), "rb").read()
return doc, binchunk, files
def buffer_bytes(doc, binchunk, files, i):
b = doc["buffers"][i]
uri = b.get("uri")
if uri is None:
return binchunk
if uri.startswith("data:"):
import base64
return base64.b64decode(uri.split(",", 1)[1])
return files[uri]
def references(doc, binchunk, files, dump, tmp):
prims = []
for mi, m in enumerate(doc.get("meshes", [])):
for pi, p in enumerate(m.get("primitives", [])):
ext = p.get("extensions", {}).get("KHR_draco_mesh_compression")
if not ext:
continue
v = doc["bufferViews"][ext["bufferView"]]
data = buffer_bytes(doc, binchunk, files, v["buffer"])
off = v.get("byteOffset", 0)
drc = data[off:off + v["byteLength"]]
path = os.path.join(tmp, "p.drc")
open(path, "wb").write(drc)
lines = subprocess.run([dump, path], capture_output=True).stdout.decode().split("\n")
entry = {"mesh": mi + 1, "prim": pi + 1, "attrs": {}}
by_id = {}
for line in lines:
parts = line.split(" ")
if parts[0] == "POINTS":
entry["points"] = int(parts[1])
elif parts[0] == "FACES":
entry["faces"] = int(parts[1])
entry["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
elif parts[0] == "ATTR":
by_id[int(parts[5])] = {"dataType": int(parts[2]), "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))}
for name, uid in ext.get("attributes", {}).items():
if uid in by_id:
a = dict(by_id[uid])
a["uniqueId"] = uid
entry["attrs"][name] = a
prims.append(entry)
return prims
def generate(ctx):
draco = store_path("draco")
dsrc = store_path("draco.src")
asrc = store_path("assimp.src")
tmp = tempfile.mkdtemp(prefix="formats-gltfdraco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
transcoder = os.path.join(draco, "bin", "draco_transcoder")
sources = [] # (name, path, original path?)
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
for model in sorted(os.listdir(gl)):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, variant)
if not os.path.isdir(d) or "Quantized" in variant:
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
src = os.path.join(d, mains[0])
for q, args in (("default", []), ("fine", ["-qp", "16", "-qt", "14", "-qn", "12", "-qc", "10", "-qw", "12", "-qtg", "10"])):
out = os.path.join(tmp, "%s_%s.glb" % (model, q))
r = subprocess.run([transcoder, "-i", src, "-o", out] + args, capture_output=True)
if r.returncode == 0 and os.path.exists(out):
sources.append(("transcoded/%s/%s" % (model, q), out, src))
break
for name, rel in (("draco/Box_Draco.glb", os.path.join(dsrc, "testdata", "Box", "glTF_Binary", "Box_Draco.glb")),
("draco/BoxMetaDraco.gltf", os.path.join(dsrc, "testdata", "BoxMetaDraco", "glTF", "BoxMetaDraco.gltf")),
("assimp/2CylinderEngine.gltf", os.path.join(asrc, "test", "models", "glTF2", "draco", "2CylinderEngine.gltf"))):
if os.path.exists(rel):
sources.append((name, rel, None))
cases = []
for name, path, orig in sources:
doc, binchunk, files = load(path)
prims = references(doc, binchunk, files, dump, tmp)
if not prims:
continue
case = {"name": name, "data": open(path, "rb").read(), "files": files, "prims": prims}
if orig:
_, _, ofiles = load(orig)
case["original"] = {"data": open(orig, "rb").read(), "files": ofiles}
cases.append(case)
ctx.emit("gltf_draco", cases)
+73
View File
@@ -0,0 +1,73 @@
# ICNS fixtures (tools/fixtures.py): a libicns png2icns file (is32 / il32 / ih32 RLE entries with their masks, ic07 /
# ic08 PNG entries), a JPEG 2000 entry that must be skipped (hand-written into hand.icns), a Pillow file (PNG entries), a hand-written one (ics# / ICN#
# 1-bit icons, an ic04 ARGB entry, an uncompressed is32); every entry's reference pixels from icns2png -x (libicns)
# or written here; our encoder's RLE file (tools/fixtures/_tex_encode.luau -a icns) read back by icns2png.
# tests/gen/icns.luau { cases = { { name, data, entries = { { type, w, h, rgba } }, skipped } }, ours = { ... } }
import importlib.util, os, re, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/icns"]
def extract(ctx, w, name):
"""icns2png -x name -> { 'WxH': rgba } (one per extracted entry)"""
log = w.sh("libicns", ["mkdir -p x_%s && cd x_%s && icns2png -x ../%s" % (name, name, name)]).decode()
files = sorted(f for f in os.listdir(w.path("x_" + name)) if f.endswith(".png"))
out = {}
for f, (mode, ww, hh, raw) in zip(files, T.pillow(ctx, [w.read(os.path.join("x_" + name, f)) for f in files])):
out["%dx%d" % (ww, hh)] = T.rgba_from(mode, raw)
return out
def generate(ctx):
w = R.Work(ctx)
try:
for s in (16, 32, 48, 128, 256):
w.png("i%d.png" % s, s, s, R.photo(s, s, s, True))
w.sh("libicns", ["png2icns libicns.icns i16.png i32.png i48.png i128.png i256.png"])
w.png("p64.png", 64, 64, R.photo(64, 64, 9, True))
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('p64.png').save('pillow.icns')\n" % w.dir)
cases = []
lib = extract(ctx, w, "libicns.icns")
cases.append({"name": "libicns.icns", "data": w.read("libicns.icns"), "skipped": 0,
"entries": [{"type": t, "w": s, "h": s, "rgba": lib["%dx%d" % (s, s)]} for t, s in (("is32", 16), ("il32", 32), ("ih32", 48), ("ic07", 128), ("ic08", 256))]})
pil = extract(ctx, w, "pillow.icns")
cases.append({"name": "pillow.icns", "data": w.read("pillow.icns"), "skipped": 0,
"entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(pil.items())]})
# hand-written: ics# (16x16 1-bit + mask), an uncompressed is32 + s8mk, an ic04 ARGB with RLE runs
bits = bytes((0xF0 if (i // 2) % 2 else 0x0F) for i in range(32))
mask = bytes((0xFF if i < 24 else 0x00) for i in range(32))
mono = []
for i in range(256):
b = (bits[i // 8] >> (7 - i % 8)) & 1
m = (mask[i // 8] >> (7 - i % 8)) & 1
mono += [0, 0, 0] if b else [255, 255, 255]
mono.append(255 if m else 0)
raw = bytes((i * 3 + k * 50) % 256 for k in range(3) for i in range(256))
alpha = bytes((i * 7) % 256 for i in range(256))
rgb = bytes(v for i in range(256) for v in (raw[i], raw[256 + i], raw[512 + i], alpha[i]))
def ch(t, d):
return t + struct.pack(">I", len(d) + 8) + d
# ARGB channels: A = 256 x 77 (two runs of 128), then R / G / B as runs
argb = b"ARGB" + bytes((253, 77, 253, 77)) + bytes((253, 10, 253, 10)) + bytes((253, 20, 253, 20)) + bytes((253, 30, 253, 30))
jp2 = b"\0\0\0\x0cjP \r\n\x87\n" + b"\0" * 20
body = ch(b"ics#", bits + mask) + ch(b"is32", raw) + ch(b"s8mk", alpha) + ch(b"ic04", argb) + ch(b"ic09", jp2)
hand = b"icns" + struct.pack(">I", len(body) + 8) + body
cases.append({"name": "hand.icns", "data": hand, "skipped": 1, "entries": [
{"type": "ics#", "w": 16, "h": 16, "rgba": bytes(mono)}, {"type": "is32", "w": 16, "h": 16, "rgba": rgb},
{"type": "ic04", "w": 16, "h": 16, "rgba": bytes((10, 20, 30, 77)) * 256}]})
mine = S.ours(ctx, "icns")
ours = []
for n, d in mine.items():
w.write(n, d)
ex = extract(ctx, w, n)
ours.append({"name": n, "data": d, "entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(ex.items())]})
ctx.emit("icns", {"cases": cases, "ours": ours})
finally:
w.close()
+121
View File
@@ -0,0 +1,121 @@
# IFF ILBM fixtures (tools/fixtures.py): files from netpbm's ppmtoilbm (palette ByteRun1 / uncompressed, few planes,
# HAM6, HAM8, 24-bit deep) and hand-written ones (EHB, chunky PBM, a mask plane, a transparent colour index, an odd
# CMAP), decoded by ilbmtoppm as the reference (alpha separately: ilbmtoppm writes PPM; HAM values within the scaling
# difference: ilbmtoppm shifts, we replicate bits); our encoder's files
# (tools/fixtures/_tex_encode.luau -a ilbm) read by ilbmtoppm.
# tests/gen/ilbm.luau { cases = { { name, data, w, h, rgba, transparent? } }, ours = { ... } }
import importlib.util, os, random, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ilbm"]
def chunk(cid, data):
return cid + struct.pack(">I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
def byterun1(row):
out = bytearray()
i = 0
while i < len(row):
run = 1
while i + run < len(row) and run < 128 and row[i + run] == row[i]:
run += 1
if run >= 2:
out += bytes((257 - run, row[i]))
i += run
else:
j = i
while j < len(row) and j - i < 128 and not (j + 1 < len(row) and row[j + 1] == row[j]):
j += 1
j = max(j, i + 1)
out += bytes((j - i - 1,)) + row[i:j]
i = j
return bytes(out)
def planar(w, h, idx, planes, mask=None, comp=True):
rb = ((w + 15) // 16) * 2
body = bytearray()
for y in range(h):
rows = []
for k in range(planes):
row = bytearray(rb)
for x in range(w):
if (idx[y * w + x] >> k) & 1:
row[x // 8] |= 0x80 >> (x % 8)
rows.append(bytes(row))
if mask is not None:
row = bytearray(rb)
for x in range(w):
if mask[y * w + x]:
row[x // 8] |= 0x80 >> (x % 8)
rows.append(bytes(row))
for row in rows:
body += byterun1(row) if comp else row
return bytes(body)
def ilbm(w, h, planes, body, cmap=b"", camg=None, masking=0, trans=0, comp=1, form=b"ILBM", extra=b""):
bmhd = struct.pack(">HHhhBBBxHBBhh", w, h, 0, 0, planes, masking, comp, trans, 10, 11, w, h)
data = form + chunk(b"BMHD", bmhd) + (chunk(b"CMAP", cmap) if cmap else b"") + (chunk(b"CAMG", struct.pack(">I", camg)) if camg is not None else b"") + extra + chunk(b"BODY", body)
return b"FORM" + struct.pack(">I", len(data)) + data
def generate(ctx):
rng = random.Random(8)
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 31, 19, R.palette_image(31, 19, 60))
w.png("pal8.png", 26, 11, R.palette_image(26, 11, 7))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam pal8.png | pamtopnm > pal8.ppm",
"ppmtoilbm pal.ppm > nb_pal.iff", "ppmtoilbm -nocompress pal.ppm > nb_pal_raw.iff", "ppmtoilbm pal8.ppm > nb_3planes.iff",
"ppmtoilbm -ham6 photo.ppm > nb_ham6.iff", "ppmtoilbm -ham8 photo.ppm > nb_ham8.iff", "ppmtoilbm -24force photo.ppm > nb_24.iff"])
hand = []
# EHB: 6 planes, 32 colours
W, H = 20, 7
cm = bytes(rng.randrange(256) for _ in range(32 * 3))
idx = [rng.randrange(64) for _ in range(W * H)]
hand.append(("hand_ehb.iff", ilbm(W, H, 6, planar(W, H, idx, 6), cm, 0x80), None))
# chunky PBM (rows padded to even), 256 colours
cm2 = bytes(rng.randrange(256) for _ in range(256 * 3))
W2 = 14
idx2 = [rng.randrange(256) for _ in range(W2 * H)]
hand.append(("hand_pbm.lbm", ilbm(W2, H, 8, b"".join(byterun1(bytes(idx2[y * W2:(y + 1) * W2])) for y in range(H)), cm2, form=b"PBM "), None))
# a mask plane and a transparent colour index
cm3 = bytes(rng.randrange(256) for _ in range(16 * 3))
idx3 = [rng.randrange(16) for _ in range(W * H)]
mask = [rng.random() < 0.7 for _ in range(W * H)]
hand.append(("hand_mask.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, mask), cm3, masking=1), [not m for m in mask]))
hand.append(("hand_transparent.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, comp=False), cm3, masking=2, trans=5, comp=0,
extra=chunk(b"NAME", b"tiny\0")), [i == 5 for i in idx3]))
for n, data, _ in hand:
w.write(n, data)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".iff") or f.endswith(".lbm"))
mine = S.ours(ctx, "ilbm")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
allnames = [n for n in allnames if n != "ours_alpha.ilbm"] # ilbmtoppm reads no 32-plane files
w.sh("netpbm", ["ilbmtoppm %s > %s.ppm" % (n, n) for n in allnames])
tmap = {n: t for n, _, t in hand}
out = {"cases": [], "ours": []}
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
if "ham" in n:
# ilbmtoppm scales HAM values by shifting (4-bit v -> v << 4); we replicate the bits (v * 17)
c["tol"] = 15 if "ham6" in n else 3
if tmap.get(n):
c["transparent"] = [bool(v) for v in tmap[n]]
out["ours" if n.startswith("ours_") else "cases"].append(c)
ctx.emit("ilbm", out)
finally:
w.close()
+57
View File
@@ -0,0 +1,57 @@
# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp
# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent
# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed
# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf)
# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader.
# tests/gen/iqm_cases.luau { name, data, assimp, ref }
# tests/gen/iqm_gltf.luau { name, data, files }
# tests/gen/iqm_xcheck.luau { name, assimp, ref }
import importlib.util, os
INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def info(ctx, M, fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
for k in ("min", "max", "perMesh"):
a.pop(k, None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
R = module(ctx, "_iqm_reference")
tmp = M.tempdir()
p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm")
data = open(p, "rb").read()
ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}])
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []:
d = os.path.join(d0, variant)
mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else []
if mains:
picks.append({"name": model, "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
ctx.emit("iqm_gltf", picks)
ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau")
out = []
for name in sorted(ours):
q = os.path.join(tmp, name)
open(q, "wb").write(ours[name])
out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])})
ctx.emit("iqm_xcheck", out)
+279
View File
@@ -0,0 +1,279 @@
# KTX fixtures (tools/fixtures.py):
# - KTX2 from KTX-Software 4.4 (`ktx create`): PNG sources (mip chains, sRGB, cube maps, arrays), --raw data in
# uncompressed / packed / float / BCn / ETC2 / EAC VkFormats, a 3D texture, `ktx deflate` Zstandard and ZLIB
# supercompression, Basis Universal (ETC1S and UASTC: must give UNSUPPORTED);
# - KTX1 from toktx (PNG sources, mips, cube map, odd widths with row padding) and nvcompress -ktx (BC1 / BC3 / BC7),
# plus hand-written big-endian and packed-type KTX1 files;
# - our encoder's KTX2 files (tools/fixtures/_tex_encode.luau -a ktx): `ktx validate` and `ktx extract` read them.
# References: the PNG sources / raw values themselves, `ktx extract` PNGs for the generated mip levels, Pillow (BCn,
# through a one-surface DDS) and Godot (ETC / EAC) for block data.
# tests/gen/ktx.luau { cases = { { name, data, layout?, mips?, surfaces = { { level, layer, slice, w, h, rgba?,
# floats?, tol } }, unsupported? } }, ours = { { name, data, valid, extract = { rgba / floats } } } }
import importlib.util, os, random, shutil, struct, subprocess, tempfile
_dir = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(_dir, "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
_spec2 = importlib.util.spec_from_file_location("_dds_fixture", os.path.join(_dir, "dds.py"))
D = importlib.util.module_from_spec(_spec2)
_spec2.loader.exec_module(D)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ktx", "tools/fixtures/dds.py"]
def q8(v):
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
def generate(ctx):
work = tempfile.mkdtemp(prefix="formats-ktx-")
try:
cases = _cases(ctx, work, random.Random(9))
ours = _ours(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("ktx", {"cases": cases, "ours": ours})
def read_png(ctx, paths):
return [R.rgba_from(m, raw) if m in ("RGB", "L", "LA", "RGBA") else raw for (m, w, h, raw) in
R.pillow(ctx, [open(p, "rb").read() for p in paths])]
def _cases(ctx, work, rng):
cases = []
sh = []
def run(cmd):
sh.append(cmd)
# sources
srcs = {}
for name, w, h, salt in (("a", 37, 23, 0), ("sq", 32, 32, 3)):
srcs[name] = (w, h, D.source(w, h, salt))
open(os.path.join(work, name + ".png"), "wb").write(D.png(w, h, srcs[name][2]))
faces = []
for i in range(6):
px = D.source(16, 16, i + 1)
faces.append(px)
open(os.path.join(work, "f%d.png" % i), "wb").write(D.png(16, 16, px))
fl = " ".join("f%d.png" % i for i in range(6))
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear a.png k2_rgba8.ktx2")
run("ktx create --format R8G8B8A8_SRGB --assign-tf srgb --generate-mipmap sq.png k2_srgb_mips.ktx2")
run("ktx extract --level all k2_srgb_mips.ktx2 k2mips")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --cubemap %s k2_cube.ktx2" % fl)
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --layers 3 f0.png f1.png f2.png k2_array.ktx2")
run("ktx create --format R8G8B8_UNORM --assign-tf linear a.png k2_rgb8.ktx2")
run("ktx deflate --zstd 12 k2_srgb_mips.ktx2 k2_zstd.ktx2")
run("ktx deflate --zlib 6 k2_cube.ktx2 k2_zlib.ktx2")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode basis-lz a.png k2_basis.ktx2")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode uastc a.png k2_uastc.ktx2")
# raw formats with known values
W, H = 8, 4
raws = []
def raw(name, vk, data, texels=None, block=None, w=W, h=H, extra="", parts=1):
n = len(data) // parts
files = []
for i in range(parts):
open(os.path.join(work, "%s_%d.raw" % (name, i)), "wb").write(data[i * n:(i + 1) * n])
files.append("%s_%d.raw" % (name, i))
run("ktx create --raw --width %d --height %d --format %s %s %s %s.ktx2" % (w, h, vk, extra, " ".join(files), name))
raws.append((name, texels, block, w, h, data))
u8 = bytes(rng.randrange(256) for _ in range(W * H * 4))
raw("k2_raw_rgba8", "R8G8B8A8_UNORM", u8, [tuple(u8[i + k] / 255 for k in range(4)) for i in range(0, len(u8), 4)])
raw("k2_raw_bgra8_srgb", "B8G8R8A8_SRGB", u8, [(u8[i + 2] / 255, u8[i + 1] / 255, u8[i] / 255, u8[i + 3] / 255) for i in range(0, len(u8), 4)])
raw("k2_raw_rg8", "R8G8_UNORM", u8[:W * H * 2], [(u8[i] / 255, u8[i + 1] / 255, 0.0, 1.0) for i in range(0, W * H * 2, 2)])
vals = [(rng.uniform(-1, 4), rng.uniform(0, 1), rng.uniform(0, 2), rng.uniform(0, 1)) for _ in range(W * H)]
hd = b"".join(struct.pack("<4e", *v) for v in vals)
raw("k2_raw_rgba16f", "R16G16B16A16_SFLOAT", hd, [struct.unpack("<4e", hd[i:i + 8]) for i in range(0, len(hd), 8)])
fd = b"".join(struct.pack("<4f", *v) for v in vals)
raw("k2_raw_rgba32f", "R32G32B32A32_SFLOAT", fd, [struct.unpack("<4f", fd[i:i + 16]) for i in range(0, len(fd), 16)])
u16 = [rng.randrange(65536) for _ in range(W * H)]
raw("k2_raw_r16", "R16_UNORM", b"".join(struct.pack("<H", v) for v in u16), [(v / 65535,) * 3 + (1.0,) for v in u16])
raw("k2_raw_r5g6b5", "R5G6B5_UNORM_PACK16", b"".join(struct.pack("<H", v) for v in u16),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in u16])
p32 = [rng.getrandbits(32) for _ in range(W * H)]
raw("k2_raw_a2b10g10r10", "A2B10G10R10_UNORM_PACK32", b"".join(struct.pack("<I", v) for v in p32),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
raw("k2_raw_e5b9g9r9", "E5B9G9R9_UFLOAT_PACK32", b"".join(struct.pack("<I", v) for v in p32),
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
vol = bytes(rng.randrange(256) for _ in range(4 * 4 * 3 * 4))
raw("k2_raw_3d", "R8G8B8A8_UNORM", vol, None, None, 4, 4, "--depth 3", 3)
for kind, vk in (("bc1", "BC1_RGB_UNORM_BLOCK"), ("bc1", "BC1_RGBA_UNORM_BLOCK"), ("bc3", "BC3_UNORM_BLOCK"),
("bc7", "BC7_UNORM_BLOCK"), ("bc6h", "BC6H_UFLOAT_BLOCK"), ("etc2_rgba", "ETC2_R8G8B8A8_UNORM_BLOCK"),
("etc2_rgb", "ETC2_R8G8B8_UNORM_BLOCK"), ("eac_rg11", "EAC_R11G11_UNORM_BLOCK")):
bb = {"bc1": 8, "bc3": 16, "bc7": 16, "bc6h": 16, "etc2_rgba": 16, "etc2_rgb": 8, "eac_rg11": 16}[kind]
data = bytes(rng.getrandbits(8) for _ in range(4 * 2 * bb))
raw("k2_raw_" + vk.lower(), vk, data, None, kind, 13, 7)
# KTX1
run("toktx --genmipmap k1_mips.ktx sq.png")
run("toktx k1_rgba.ktx a.png")
run("toktx --cubemap k1_cube.ktx %s" % fl)
run("ktx2ktx2 -o k1_mips_as2.ktx2 k1_mips.ktx")
run("ktx extract --level all k1_mips_as2.ktx2 k1mips")
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && nvcompress -silent -ktx -bc1 a.png n_bc1.ktx && nvcompress -silent -ktx -bc3 a.png n_bc3.ktx && nvcompress -silent -ktx -bc7 -nomips a.png n_bc7.ktx" % work])
def rd(n):
return open(os.path.join(work, n), "rb").read()
def surf(level, layer, s, w, h, rgba=None, floats=None, tol=0):
d = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": tol}
if rgba is not None:
d["rgba"] = rgba
if floats is not None:
d["floats"] = floats
return d
aw, ah, apx = srcs["a"]
sw, shh, spx = srcs["sq"]
cases.append({"name": "k2_rgba8.ktx2", "data": rd("k2_rgba8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
mip_files = sorted(f for f in os.listdir(work) if f.startswith("k2mips") or f.startswith("output_level"))
mips = []
lw = sw
level = 0
while True:
p = os.path.join(work, "k2mips_level%d.png" % level)
if not os.path.exists(p):
p = os.path.join(work, "k2mips", "output_level%d.png" % level)
if not os.path.exists(p):
break
mips.append((level, p))
level += 1
if not mips:
raise RuntimeError("ktx extract wrote no mip levels: %r" % os.listdir(work))
pngs = read_png(ctx, [p for _, p in mips])
msurf = [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for (lv, _), px in zip(mips, pngs)]
cases.append({"name": "k2_srgb_mips.ktx2", "data": rd("k2_srgb_mips.ktx2"), "layout": "2d", "mips": len(mips), "srgb": True, "surfaces": msurf})
cases.append({"name": "k2_zstd.ktx2", "data": rd("k2_zstd.ktx2"), "layout": "2d", "mips": len(mips), "surfaces": msurf})
csurf = [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]
cases.append({"name": "k2_cube.ktx2", "data": rd("k2_cube.ktx2"), "layout": "cube", "surfaces": csurf})
cases.append({"name": "k2_zlib.ktx2", "data": rd("k2_zlib.ktx2"), "layout": "cube", "surfaces": csurf})
cases.append({"name": "k2_array.ktx2", "data": rd("k2_array.ktx2"), "layout": "array", "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(3)]})
opaque = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(apx))
cases.append({"name": "k2_rgb8.ktx2", "data": rd("k2_rgb8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, opaque)]})
cases.append({"name": "k2_basis.ktx2", "data": rd("k2_basis.ktx2"), "unsupported": True, "surfaces": []})
cases.append({"name": "k2_uastc.ktx2", "data": rd("k2_uastc.ktx2"), "unsupported": True, "surfaces": []})
pil, pil_t, gd, gd_t = [], [], [], []
for (name, texels, block, w, h, data) in raws:
c = {"name": name + ".ktx2", "data": rd(name + ".ktx2"), "layout": "volume" if name.endswith("3d") else "2d"}
if texels is not None:
c["surfaces"] = [surf(0, 0, 0, w, h, bytes(q8(v) for t in texels for v in t), b"".join(struct.pack("<4f", *t) for t in texels), 1)]
elif block is None:
c["surfaces"] = [surf(0, 0, s, w, h, data[s * w * h * 4:(s + 1) * w * h * 4]) for s in range(3)]
else:
sd = surf(0, 0, 0, w, h)
c["surfaces"] = [sd]
if block.startswith("bc") and block != "bc6h":
dx = {"bc1": 71, "bc3": 77, "bc7": 98}[block]
pil.append(R.dds_dx10(w, h, dx, data))
pil_t.append((sd, "RGB_UNORM" in name.upper()))
else:
gd.append((data, w, h, R.GODOT[block], block == "bc6h"))
gd_t.append((sd, block))
cases.append(c)
for (sd, opaque_), (mode, w, h, rw) in zip(pil_t, R.pillow(ctx, pil)):
px = R.rgba_from(mode, rw)
if opaque_:
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px))
sd["rgba"] = px
for (sd, block), out in zip(gd_t, R.godot(ctx, gd)):
if block == "bc6h":
sd["floats"] = out
elif block == "eac_rg11":
sd["rgba"] = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(out))
sd["tol"] = 1
else:
sd["rgba"] = out
# KTX1
k1 = []
level = 0
while True:
p = os.path.join(work, "k1mips_level%d.png" % level)
if not os.path.exists(p):
p = os.path.join(work, "k1mips", "output_level%d.png" % level)
if not os.path.exists(p):
break
k1.append(p)
level += 1
k1png = read_png(ctx, k1)
cases.append({"name": "k1_mips.ktx", "data": rd("k1_mips.ktx"), "layout": "2d", "mips": len(k1),
"surfaces": [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for lv, px in enumerate(k1png)]})
cases.append({"name": "k1_rgba.ktx", "data": rd("k1_rgba.ktx"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
cases.append({"name": "k1_cube.ktx", "data": rd("k1_cube.ktx"), "layout": "cube",
"surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]})
# nvcompress KTX1: the level-0 blocks follow the 64-byte header + key / value data + imageSize
nv = []
for n, dx in (("n_bc1.ktx", 71), ("n_bc3.ktx", 77), ("n_bc7.ktx", 98)):
d = rd(n)
kvb = struct.unpack("<I", d[60:64])[0]
off = 64 + kvb + 4
size = struct.unpack("<I", d[off - 4:off])[0]
nv.append((n, d, R.dds_dx10(aw, ah, dx, d[off:off + size])))
for (n, d, dds), (mode, w, h, rw) in zip(nv, R.pillow(ctx, [x[2] for x in nv])):
px = R.rgba_from(mode, rw)
if n == "n_bc1.ktx":
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px)) # GL_COMPRESSED_RGB_S3TC_DXT1
cases.append({"name": n, "data": d, "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, px)]})
# hand-written KTX1: big-endian 16-bit RGBA, GL_UNSIGNED_SHORT_5_6_5, RGB8 with row padding and T=u orientation
def ktx1(gltype, typesize, glformat, internal, base, w, h, image, be=False, kv=b""):
f = ">" if be else "<"
hdr = b"\xabKTX 11\xbb\r\n\x1a\n" + struct.pack(f + "13I", 0x04030201, gltype, typesize, glformat, internal, base, w, h, 0, 0, 1, 1, len(kv))
return hdr + kv + struct.pack(f + "I", len(image)) + image
W2, H2 = 5, 3
v16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W2 * H2)]
img = b"".join(struct.pack(">4H", *v) for v in v16) + b"\0" * 0 # rows of 40 bytes: already 4-aligned
cases.append({"name": "hand big-endian RGBA16", "data": ktx1(0x1403, 2, 0x1908, 0x805B, 0x1908, W2, H2, img, True), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(x / 65535) for v in v16 for x in v), b"".join(struct.pack("<4f", *(x / 65535 for x in v)) for v in v16), 1)]})
p565 = [rng.getrandbits(16) for _ in range(W2 * H2)]
rows = b"".join(b"".join(struct.pack("<H", p565[y * W2 + x]) for x in range(W2)) + b"\0\0" for y in range(H2))
cases.append({"name": "hand RGB 5_6_5 (row padding)", "data": ktx1(0x8363, 2, 0x1907, 0x8D62, 0x1907, W2, H2, rows), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(v) for p in p565 for v in ((p >> 11) / 31, ((p >> 5) & 63) / 63, (p & 31) / 31, 1.0)), None, 1)]})
rgb = bytes(rng.randrange(256) for _ in range(W2 * H2 * 3))
rows = b"".join(rgb[y * W2 * 3:(y + 1) * W2 * 3] + b"\0" for y in range(H2))
kv = b"KTXorientation\0S=r,T=u\0"
kv = struct.pack("<I", len(kv)) + kv + b"\0" * ((4 - len(kv) % 4) % 4)
flipped = b"".join(rgb[(H2 - 1 - y) * W2 * 3 + x * 3:(H2 - 1 - y) * W2 * 3 + x * 3 + 3] + b"\xff" for y in range(H2) for x in range(W2))
cases.append({"name": "hand RGB8 T=u", "data": ktx1(0x1401, 1, 0x1907, 0x8051, 0x1907, W2, H2, rows, False, kv), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, flipped)]})
return cases
def _ours(ctx, work):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "ktx"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
names = sorted(files)
sh = []
for n in names:
open(os.path.join(work, n), "wb").write(files[n])
base = n[:-5]
sh.append("(ktx validate %s > %s.val 2>&1; echo $? > %s.rc)" % (n, base, base))
sh.append("(ktx extract %s %s.x > /dev/null 2>&1 || true)" % (n, base))
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " ; ".join(sh))])
out = []
pngs, idx = [], []
for i, n in enumerate(names):
base = n[:-5]
rc = open(os.path.join(work, base + ".rc")).read().strip()
e = {"name": n, "data": files[n], "valid": rc == "0", "report": open(os.path.join(work, base + ".val"), "rb").read()[:2000]}
for ext in (".x", ".x.png", ".x.exr"):
p = os.path.join(work, base + ext)
if os.path.exists(p) and os.path.isfile(p):
e["extracted"] = open(p, "rb").read()[:8]
if open(p, "rb").read(4) == b"\x89PNG":
pngs.append(p)
idx.append(i)
out.append(e)
for i, (mode, w, h, raw) in zip(idx, R.pillow(ctx, [open(p, "rb").read() for p in pngs])):
if mode in ("RGBA", "RGB", "L", "LA"):
out[i]["png"] = R.rgba_from(mode, raw)
return out
+417
View File
@@ -0,0 +1,417 @@
# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through
# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT,
# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions,
# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts
# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never
# committed: each case carries the files it needs). References: an independent expansion written here (world
# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and
# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in
# colour table.
# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} }
# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } }
import math, os, re, subprocess, zipfile
INPUTS = []
def nix_out(attr):
out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def library_zip(leocad):
# LeoCAD's wrapper points LEOCAD_LIB at the parts library zip
wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1")
m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper)
return m.group(1) if m else None
# ---------------------------------------------------------------------------------------------------- reference
def norm(name):
return name.strip().replace("\\", "/").lower()
class Ref:
"""an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)"""
PREFIXES = ("", "parts/", "p/", "parts/s/", "models/")
def __init__(self, main, files, colours):
self.files = {norm(k): v for k, v in files.items()}
self.colours = colours # code -> (rgb, edge)
self.mpd = {}
self.missing = set()
self.tris = [] # (colour, ds, (v0, v1, v2))
self.lines = 0
self.optional = 0
text = main
if re.search(r"^\s*0\s+FILE\s", text, re.M):
cur = None
first = None
for line in text.splitlines():
m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line)
if m:
cur = norm(m.group(1))
first = first or cur
self.mpd[cur] = []
continue
if re.match(r"^\s*0\s+NOFILE\b", line):
cur = None
continue
if cur:
self.mpd[cur].append(line)
self.main = "\n".join(self.mpd[first])
else:
self.main = text
org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M)
refs = re.search(r"^\s*1\s", self.main, re.M)
self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs
def lookup(self, name):
n = norm(name)
if n in self.mpd:
return "\n".join(self.mpd[n])
for p in self.PREFIXES:
if p + n in self.files:
return self.files[p + n]
self.missing.add(n)
return None
def colour(self, code, cur):
if code == 16:
return cur
if code == 24:
return self.edge(cur)
return code
def edge(self, c):
if c in self.colours:
e = self.colours[c][1]
return e
return 0x2333333 if c < 0x2000000 else 0x2000000
def walk(self, text, m, colour, inv, certified, depth, model, stack=()):
# model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place
if depth > 64:
return
st = {"cw": False, "cert": None, "clip": True, "invert": False}
for raw in text.splitlines():
t = raw.split()
if not t:
continue
if t[0] == "0":
if len(t) >= 3 and t[1] == "!COLOUR":
self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()})
if len(t) >= 3 and t[1] == "BFC":
words = [w.upper() for w in t[2:]]
if "NOCERTIFY" in words:
st["cert"] = False
elif "CERTIFY" in words:
st["cert"] = True
if "CW" in words:
st["cw"] = True
if "CCW" in words:
st["cw"] = False
if "NOCLIP" in words:
st["clip"] = False
elif "CLIP" in words:
st["clip"] = True
if "INVERTNEXT" in words:
st["invert"] = True
continue
invert_next = st["invert"]
st["invert"] = False
try:
kind = int(t[0])
code = int(t[1], 0)
cert = certified and st["cert"] is True and st["clip"]
if kind == 1 and len(t) >= 15:
x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]]
loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]]
name = raw.split(None, 14)[14].strip()
if norm(name) in stack:
continue # a file that (indirectly) places itself
sub = self.lookup(name)
if sub is None:
continue
sub_model = norm(name).endswith((".ldr", ".mpd"))
self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next,
(True if model else cert), depth + 1, sub_model, stack + (norm(name),))
elif kind in (3, 4) and len(t) >= 2 + 3 * kind:
pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)]
if st["cw"] ^ inv ^ (det(m) < 0):
pts = pts[::-1]
col = self.colour(code, colour)
one = cert and not model or (model and st["cert"] is True and st["clip"])
self.tris.append((col, not one, (pts[0], pts[1], pts[2])))
if kind == 4:
self.tris.append((col, not one, (pts[0], pts[2], pts[3])))
elif kind == 2 and len(t) >= 8:
[float(v) for v in t[2:8]]
self.lines += 1
elif kind == 5 and len(t) >= 14:
[float(v) for v in t[2:14]]
self.optional += 1
except ValueError:
pass
def run(self, main_colour=16):
flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]]
self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part)
return self
def summary(self):
per = {}
area, vol = 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
for col, ds, (a, b, c) in self.tris:
per[col] = per.get(col, 0) + 1
for p in (a, b, c):
lo = [min(u, v) for u, v in zip(lo, p)]
hi = [max(u, v) for u, v in zip(hi, p)]
area += tri_area(a, b, c)
if not ds:
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol,
"doubleSided": sum(1 for x in self.tris if x[1]),
"colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)}
if self.tris:
out["min"], out["max"] = lo, hi
return out
def mul(m, l):
# 3x4 affine product m * l
r = [[0.0] * 4 for _ in range(3)]
for i in range(3):
for j in range(4):
s = sum(m[i][k] * l[k][j] for k in range(3))
r[i][j] = s + (m[i][3] if j == 3 else 0)
return r
def apply(m, p):
return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)]
def det(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
def tri_area(a, b, c):
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x = e1[1] * e2[2] - e1[2] * e2[1]
y = e1[2] * e2[0] - e1[0] * e2[2]
z = e1[0] * e2[1] - e1[1] * e2[0]
return math.sqrt(x * x + y * y + z * z) / 2
def parse_ldconfig(text):
out = {}
for line in text.splitlines():
m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line)
if not m:
continue
t = m.group(2).split()
kv = {}
for i in range(0, len(t) - 1):
if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv:
kv[t[i]] = t[i + 1]
code = int(kv["CODE"])
rgb = int(kv["VALUE"][1:], 16)
e = kv["EDGE"]
edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e)
out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1))
return out
# ---------------------------------------------------------------------------------------------------- hand-written
BOX = """0 a unit box primitive (faces outward, CCW)
0 BFC CERTIFY CCW
4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1
4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1
4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1
4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1
4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1
4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1
2 24 -1 -1 -1 1 -1 -1
2 24 -1 -1 -1 -1 1 -1
5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1
"""
BOX_CW = """0 the same box written clockwise
0 BFC CERTIFY CW
4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1
4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1
4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1
4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1
4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1
4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1
"""
TRI = """0 an uncertified triangle
3 16 0 0 0 1 0 0 0 0 1
"""
# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle
BRICK = """0 Test Brick 1 x 2
0 Name: testbrick.dat
0 Author: formats-luau
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat
0 BFC INVERTNEXT
1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat
1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat
1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat
1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat
"""
PLAIN_LDR = """0 Two bricks
0 Name: two.ldr
1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat
1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat
0 STEP
1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat
"""
MPD = """0 FILE main.ldr
0 MPD main
0 Name: main.ldr
0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200
1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat
3 24 0 0 0 10 0 0 0 10 0
0 NOFILE
0 FILE sub.ldr
0 a sub-model: two parts and a nested sub-model
1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr
0 NOFILE
0 FILE inner.ldr
1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat
0 FILE Embedded Part.dat
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat
0 BFC NOCLIP
3 24 0 -5 0 5 -5 0 0 -5 5
0 BFC CLIP
4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5
"""
BAD_REFS = """0 cycles and bad lines are survived
1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat
1 16 0 0 0 1 0 0 0 1
3 16 0 0 0 1 x 0 0 0 1
4 16 0 0 0 1 0 0 1 1 0 0 1 0
"""
LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n"
LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI,
"parts/testbrick.dat": BRICK, "loop.dat": LOOP}
def hand_cases(colours):
cases = []
def add(name, text, files, opts=None):
ref = Ref(text, files, colours).run()
c = {"name": name, "data": text, "files": files, "want": ref.summary()}
if opts:
c["opts"] = opts
cases.append(c)
add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"})
add("two.ldr", PLAIN_LDR, dict(LIB))
add("model.mpd", MPD, {"parts/box.dat": BOX})
add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP})
add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB))
return cases
# ---------------------------------------------------------------------------------------------------- real parts
def closure(z, names, text_of):
"""the library files a set of references needs: { library path -> text }"""
have = {}
index = {}
for n in z.namelist():
if n.startswith("ldraw/") and n.lower().endswith(".dat"):
index[n[6:].lower()] = n
todo = list(names)
while todo:
n = norm(todo.pop())
for p in Ref.PREFIXES:
key = p + n
if key in index:
if key not in have:
t = z.read(index[key]).decode("utf-8", "replace")
have[key] = t
for line in t.splitlines():
parts = line.split(None, 14)
if len(parts) == 15 and parts[0] == "1":
todo.append(parts[14].strip())
break
return have
def leocad_obj(leocad, libzip, path, tmp):
out = os.path.join(tmp, "leocad.obj")
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True)
vs, area = [], 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) - 1 for x in p[1:]]
for k in range(1, len(idx) - 1):
area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]])
return {"min": lo, "max": hi, "area": area}
def generate(ctx):
import tempfile
tmp = tempfile.mkdtemp(prefix="formats-ldraw-")
leocad = nix_out("nixpkgs#leocad")
libzip = library_zip(leocad)
z = zipfile.ZipFile(libzip)
config = z.read("ldraw/LDConfig.ldr").decode("utf-8")
colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()}
ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]})
cases = hand_cases(colours)
# real parts and the library's sample models, with LeoCAD's export
reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"),
("pyramid.ldr", "ldraw/models/pyramid.ldr")]
for name, member in reals:
if member:
text = z.read(member).decode("utf-8", "replace")
else:
text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name
files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None)
ref = Ref(text, files, colours).run()
c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()}
p = os.path.join(tmp, "model.ldr")
with open(p, "w") as f:
f.write(text)
try:
c["leocad"] = leocad_obj(leocad, libzip, p, tmp)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
pass
cases.append(c)
ctx.emit("ldraw_cases", cases)
+108
View File
@@ -0,0 +1,108 @@
# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC
# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 /
# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits
# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The
# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba.
# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } }
import importlib.util, os, tempfile, zlib
_here = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
V = _load("_video")
M = _load("_legacy_mux")
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"]
W, H = 128, 96
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"]
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def case(tmp, name, codec, w=W, h=H):
path = os.path.join(tmp, name)
return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h,
"frames": rgba_crcs(path, w, h)}
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="legacyfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
cases = []
# ffmpeg's encoders
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "cinepak", "cinepak." + ext)
cases.append(case(tmp, "cinepak." + ext, "cinepak"))
ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi")
cases.append(case(tmp, "cinepak_gray.avi", "cinepak"))
ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov")
cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68))
ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi")
cases.append(case(tmp, "cinepak_strips.avi", "cinepak"))
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext)
cases.append(case(tmp, "msvideo1." + ext, "msvideo1"))
for pf in ("rgb24", "rgb555be", "argb", "gray"):
ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf)
cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle"))
ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov")
cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60))
for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8)
ff(*SRC, "-c:v", "smc", "smc." + ext)
cases.append(case(tmp, "smc." + ext, "smc"))
# streams encoded here
w, h, n = 64, 48, 8
for bits in (1, 2, 4, 8):
imgs = M.index_frames(w, h, n, 1 << bits, seed=bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
keys = [i == 0 for i in range(n)]
# a colour table in the sample description, and the Macintosh default table
pal = M.palette(1 << bits, seed=bits)
name = "qtrle_%d_ctab.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
name = "qtrle_%d_default.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
# grey depths (0x20 + bits) with the default table id: grey ramps
for bits in (2, 4):
imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
name = "qtrle_%d_grey.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3))
cases.append(case(tmp, name, "qtrle", w, h))
# 8-bit Microsoft Video 1 and Cinepak with an AVI palette
pal = M.palette(256, seed=3)
imgs = M.index_frames(w, h, n, 256, seed=5)
frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write(
M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h))
imgs = M.index_frames(w, h, n, 200, seed=6)
frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "cinepak_8.avi"), "wb").write(
M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h))
for c in cases:
assert c["frames"], c["name"] + ": ffmpeg decoded no frame"
ctx.emit("legacy_cases", cases)
# tools/bench.luau: 320x240, 10 frames of each codec
bench = []
big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"]
for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]),
("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]:
ff(*big, *args, "bench_" + name)
bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240})
ctx.emit("legacy_bench", bench)
+41
View File
@@ -0,0 +1,41 @@
# LightWave object fixtures (tools/fixtures.py): assimp's LWO test models (LWO2, LWOB, Modo LXOB; models and
# models-nonbsd, read from the nixpkgs assimp source, never committed) with assimp's view of them (`assimp info -r`:
# meshes, polygons, corners, materials, nodes; world bounds from assimp's PreTransformVertices export).
# tests/gen/lwo_cases.luau { name, data, assimp = { meshes, faces, vertices, materials, nodes, min, max } }
import importlib.util, os
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
INPUTS = ["src/Formats/model/lwo", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx") # assimp_src, ptv_bounds
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/LWO", "models-nonbsd/LWO"):
d0 = os.path.join(src, "test", sub)
for root, _, files in sorted(os.walk(d0)):
for f in sorted(files):
if f.lower().endswith((".lwo", ".lxo")):
p = os.path.join(root, f)
cases.append({"name": sub.split("/")[0] + "/" + os.path.relpath(p, d0), "path": p})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("lwo_cases", cases)
+11 -4
View File
@@ -4,7 +4,9 @@
# tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } },
# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA),
# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib),
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) }
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib),
# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT
# codecs/video/Dsp reproduces: the decode must equal it) }
# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } }
# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with
# B-frames) for tools/bench.luau
@@ -122,9 +124,9 @@ def generate(ctx):
es = open(path, "rb").read()
return (patch_size(es, *size) if size else es), path
def reference(path, fmt):
out = path + "." + fmt
ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
def reference(path, fmt, idct=None):
out = path + "." + fmt + (idct or "")
ff((["-idct", idct] if idct else []) + ["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2])
@@ -134,10 +136,13 @@ def generate(ctx):
es, path = encode(name, args, size)
rgba, w, h = reference(path, "rgba")
yuv, _, _ = reference(path, "yuv420p")
exact, _, _ = reference(path, "yuv420p", "int")
if size:
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
exact = crop_yuv(exact, w, h, size[0], size[1])
w, h = size
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
c = ((w + 1) // 2) * ((h + 1) // 2)
n = len(rgba) // fs
means = []
for k in range(n):
@@ -151,6 +156,8 @@ def generate(ctx):
"means": means,
"rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks],
"yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks],
"exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])]
for f in (exact[k * ys:(k + 1) * ys] for k in range(n))],
})
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
+424
View File
@@ -0,0 +1,424 @@
# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder
# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the
# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second
# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors),
# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so
# the planes must match exactly.
# tests/gen/mpeg2_<name>.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64),
# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of
# every frame's cropped planes, display order), bands = { { crc } } (per frame, of
# each 16-line luma band), first / last = the yuv frame (base64 zlib) }
# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS,
# Matroska and AVI, base64, with the stream's crcs
# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau
import base64, os, shutil, subprocess, tempfile, zlib
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
FF = ["-hide_banner", "-loglevel", "error", "-y"]
ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"]
ILACE = ["-flags", "+ilme+ildct"]
CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64))
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
def src(kind, w, h, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
# name: (ffmpeg input + encoder args, chroma)
CASES = {
"prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1",
"-b:v", "1500k", "-bf", "1", "-g", "9"], 1),
"tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k",
"-bf", "2", "-g", "8"], 1),
"dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER,
"-b:v", "800k", "-bf", "1", "-g", "6"], 1),
"dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1),
"motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1),
"odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1),
"c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6",
"-chroma_intra_matrix", CHROMA_INTRA], 2),
"c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE +
["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2),
}
def access_units(es):
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
starts = []
i = 0
pending = None
while True:
i = es.find(b"\x00\x00\x01", i)
if i < 0 or i + 3 >= len(es):
break
code = es[i + 3]
if code in (0xB3, 0xB8) and pending is None:
pending = i
elif code == 0x00:
starts.append(pending if pending is not None else i)
pending = None
i += 3
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
def ff(args):
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
def size(path):
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path, chroma):
out = path + ".yuv"
ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo",
"-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out])
return open(out, "rb").read()
def emit(name, es, path, chroma):
w, h = size(path)
yuv = reference(path, chroma)
cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2)
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs, bands = [], []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)])
ctx.emit("mpeg2_" + name, {
"name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es),
"units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]),
})
return crcs
with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp:
crcs = {}
for name, (args, chroma) in CASES.items():
path = os.path.join(tmp, name + ".m2v")
ff(args + ENC + [path])
crcs[name] = emit(name, open(path, "rb").read(), path, chroma)
# mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires)
y4m = os.path.join(tmp, "src.y4m")
ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m])
dp = os.path.join(tmp, "dualprime.m2v")
ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'"
% (dp, y4m)])
emit("dualprime", open(dp, "rb").read(), dp, 1)
# field pictures and concealment vectors (field_stream below: no encoder at hand writes them)
seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")]
for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)):
path = os.path.join(tmp, name + ".m2v")
es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal)
open(path, "wb").write(es)
emit(name, es, path, 1)
# the prog stream in the containers (stream copy)
prog = os.path.join(tmp, "prog.m2v")
cont = {"crcs": crcs["prog"]}
for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")):
out = os.path.join(tmp, "prog." + ext)
ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out])
cont[ext] = b64(open(out, "rb").read())
# stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone
ts = bytearray(base64.b64decode(cont["ts"]))
patched = False
for p in range(0, len(ts), 188):
pkt = ts[p:p + 188]
if pkt[0] != 0x47 or not (pkt[1] & 0x40):
continue
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
if pid == 0 or pid == 0x11 or pkt[3] & 0x20:
continue
o = p + 5 + pkt[4]
if ts[o] != 0x02: # table_id of a PMT
continue
slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2]
pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11]
e = o + 12 + pinfo
while e < o + 3 + slen - 4:
if ts[e] == 0x02:
ts[e] = 0x80
patched = True
e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4])
crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4]))
ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big")
assert patched, "mpeg2: no PMT entry patched"
cont["ts80"] = b64(bytes(ts))
ctx.emit("mpeg2_containers", cont)
bench = []
path = os.path.join(tmp, "bench.m2v")
ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path])
es = open(path, "rb").read()
bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg2_bench", bench)
def zlib_crc32_mpeg(data):
# CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor
crc = 0xFFFFFFFF
for b in data:
crc ^= b << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF
return crc
# ---------------------------------------------------------------------------------------------------------------------
# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field
# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in
# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse
# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is
# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here).
MBAI = {1: "1", 2: "011", 3: "010"}
DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]
DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]
# |motion_code| 0..16 (Table B-10), then the sign bit
MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001",
"0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"]
CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"}
MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"}
MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011",
"intra": "00011"}
class Bits:
def __init__(self):
self.s = []
def put(self, v, n):
self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "")
def code(self, c):
self.s.append(c)
def start(self, code):
# next_start_code: zero stuffing to a byte boundary, then 00 00 01 code
n = len("".join(self.s))
if n % 8:
self.s.append("0" * (8 - n % 8))
self.put(0x000001, 24)
self.put(code, 8)
def bytes(self):
s = "".join(self.s)
s += "0" * (-len(s) % 8)
return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8))
def field_stream(rng, w, h, frames, conceal=False):
"""frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]"""
b = Bits()
mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32)
fh = mbh * 8 # field height in lines (coded)
b.start(0xB3)
b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1)
b.put(0, 1), b.put(0, 1)
b.start(0xB5)
b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1)
b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5)
b.start(0xB8)
b.put(0, 25), b.put(1, 1), b.put(0, 1)
# temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded
# just before it)
tr, d, last_ref = {}, 0, None
for k, f in enumerate(frames):
if f[0] != "B":
if last_ref is not None:
tr[last_ref] = d
d += 1
last_ref = k
else:
tr[k] = d
d += 1
tr[last_ref] = d
for k, (t0, t1) in enumerate(frames):
for fi, ptype in enumerate((t0, t1)):
parity = fi # top field first
pt = {"I": 1, "P": 2, "B": 3}[ptype]
b.start(0x00)
b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16)
if pt >= 2:
b.put(0, 1), b.put(7, 3)
if pt == 3:
b.put(0, 1), b.put(7, 3)
b.put(0, 1)
b.start(0xB5)
fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15)
if pt == 1 and conceal:
fc = (1, 1, 15, 15)
b.put(8, 4)
for f in fc:
b.put(f, 4)
b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1)
b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1)
# the second field of the first frame has one reference: the first field (no skips, zero-vector or
# dual-prime prediction from its own parity)
only_first = k == 0 and fi == 1
for row in range(mbh // 2):
b.start(row + 1)
b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1)
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c]
dc = [128, 128, 128]
col = 0
prev_dirs = None
while col < mbw:
# B skips repeat the previous vectors: only after zero ones (they stay inside the picture)
skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and
prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1])))
if skip:
b.code(MBAI[2])
col += 1 # the skipped one
dc = [128, 128, 128]
if pt == 2:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
else:
b.code(MBAI[1])
if pt == 1 or rng.random() < 0.08:
b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"])
if conceal:
# field_select, a concealment vector (the predictor again: motion codes 0), marker
b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1)
pmv[0][2:] = pmv[0][:2]
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
for blk in range(6):
comp = 0 if blk < 4 else blk - 3
target = rng.randrange(40, 216)
diff = target - dc[comp]
dc[comp] = target
size = abs(diff).bit_length()
b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size])
if size:
b.put(diff if diff > 0 else diff + (1 << size) - 1, size)
ac_block(b, rng, 1, 0.5)
prev_dirs = None
col += 1
continue
dc = [128, 128, 128]
if pt == 2:
kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else
("mc", "mc_coded", "mc_coded", "nomc_coded", "mc"))
dirs = (0,) if kind != "nomc_coded" else ()
b.code(MBTYPE_P[kind])
coded = kind != "mc"
else:
kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded"))
dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,)
b.code(MBTYPE_B[kind])
coded = kind.endswith("coded")
if dirs:
choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else [])
mt = rng.choice(choices)
b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2)
for d in dirs:
motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None)
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
if coded:
cbp = rng.choice(list(CBP))
b.code(CBP[cbp])
for blk in range(6):
if cbp & (32 >> blk):
ac_block(b, rng, 0, 0.6)
prev_dirs = dirs
col += 1
b.start(0xB7)
return b.bytes()
def ac_block(b, rng, first, more):
# escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one
n = first
count = 0
while n < 64 and (count == 0 and first == 0 or rng.random() < more):
run = rng.randrange(0, 6)
if n + run > 63:
break
level = rng.choice((-1, 1)) * rng.randrange(1, 24)
b.code("000001"), b.put(run, 6), b.put(level, 12)
n += run + 1
count += 1
b.code("10")
def put_motion(b, delta):
b.code(MOTION[abs(delta)])
if delta:
b.put(1 if delta < 0 else 0, 1)
def wrap(v):
return (v + 16) % 32 - 16
def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel):
"""one direction's vectors for a field-picture macroblock, kept inside the reference field"""
def ok(mx, my, rows, y0):
sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1)
return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh
def pick(px, py, rows, y0, extra=None):
for _ in range(50):
mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11)
dx, dy = wrap(mx - px), wrap(my - py)
if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)):
return dx, dy, mx, my
return None
if mt == "field":
sel = rng.randrange(2) if force_sel is None else force_sel
r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
elif mt == "16x8":
for half in range(2):
sel = rng.randrange(2) if force_sel is None else force_sel
px, py = pmv[half * 2], pmv[half * 2 + 1]
r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1])
else:
# dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector
def dmv_ok(dmx, dmy):
def f(mx, my):
ox = ((mx + (mx > 0)) >> 1) + dmx
oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1)
return ok(ox, oy, 16, row * 16)
return f
for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7):
r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy))
if r:
break
assert r, "dual prime: no vector fits"
put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx])
put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
+68
View File
@@ -0,0 +1,68 @@
# MS3D fixtures (tools/fixtures.py): assimp's MilkShape 3D test models (test/models/MS3D: groups, materials, textures,
# version 4 with and without the sub-versioned blocks; read from the nixpkgs assimp source, never committed), with
# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, bones; world bounds
# from its PreTransformVertices export). No tool writes MS3D with joints, so skins and animation are checked through
# our writer: glTF sample models (skins, animation, textures) written by tools/fixtures/_ms3d_encode.luau and read
# back by assimp.
# tests/gen/ms3d_cases.luau { name, data, assimp }
# tests/gen/ms3d_gltf.luau glTF sample models: { name, data, files }
# tests/gen/ms3d_xcheck.luau { name, case? | gltf?, assimp }
import importlib.util, os
INPUTS = ["src/Formats/model/ms3d", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/3ds.py", "tools/fixtures/_ms3d_encode.luau"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
GLTF = ("Box", "BoxTextured", "SimpleSkin", "RiggedSimple", "SimpleMeshes", "MultiUVTest", "NegativeScaleTest",
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes")
def generate(ctx):
M = load(ctx, "_model_ref")
X = load(ctx, "fbx")
R = load(ctx, "3ds")
tmp = M.tempdir()
d = os.path.join(X.assimp_src(ctx), "test", "models", "MS3D")
cases = [{"name": "assimp/" + f, "path": os.path.join(d, f)} for f in sorted(os.listdir(d)) if f.lower().endswith(".ms3d")]
for c, a in zip(cases, R.reference(ctx, M, X, [c["path"] for c in cases], tmp)):
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("ms3d_cases", cases)
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in sorted(os.listdir(d0)):
dd = os.path.join(d0, variant)
mains = [f for f in sorted(os.listdir(dd)) if f.endswith(".gltf") or f.endswith(".glb")] if os.path.isdir(dd) else []
if mains:
picks.append({"name": model + "/" + variant, "data": open(os.path.join(dd, mains[0]), "rb").read(),
"files": {f: open(os.path.join(dd, f), "rb").read() for f in sorted(os.listdir(dd)) if f != mains[0]}})
break
ctx.emit("ms3d_gltf", picks)
ours = M.luau_encode(ctx, "tools/fixtures/_ms3d_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".ms3d"))
paths = []
for n in names:
p = os.path.join(xtmp, n)
with open(p, "wb") as f:
f.write(ours[n])
paths.append(p)
xs = []
for n, a in zip(names, R.reference(ctx, M, X, paths, xtmp)):
kind, idx = n[:-5].split("_")
e = {"name": n, "assimp": a}
e["case" if kind == "case" else "gltf"] = int(idx)
xs.append(e)
ctx.emit("ms3d_xcheck", xs)
+95
View File
@@ -0,0 +1,95 @@
# OpenRaster fixtures (tools/fixtures.py): ORA files assembled here by the specification (python zipfile, the stored
# mimetype first, stack.xml, Pillow-written PNG layers, mergedimage.png, a thumbnail): plain layers with offsets /
# opacity / hidden / composite-ops, nested stacks (isolate and auto), a file without mergedimage; and our encoder's
# file (tools/fixtures/_tex_encode.luau -a ora) taken apart by python (zip order and method, stack.xml, PNG pixels
# through Pillow). References: the layer attributes and source pixels written here.
# tests/gen/ora.luau { cases = { { name, data, w, h, layers (bottom to top, depth-first) = { { name, x, y, opacity,
# visible, blend, depth, rgba?, w?, h? } }, merged? } }, ours = { ok, entries, layers } }
import importlib.util, io, os, struct, xml.etree.ElementTree as ET, zipfile
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/layered/ora"]
OPS = {"svg:src-over": "normal", "svg:multiply": "multiply", "svg:screen": "screen", "svg:overlay": "overlay", "svg:color-dodge": "colorDodge"}
def build(stack_xml, pngs, merged=True, w=40, h=30):
buf = io.BytesIO()
z = zipfile.ZipFile(buf, "w")
z.writestr(zipfile.ZipInfo("mimetype"), "image/openraster", compress_type=zipfile.ZIP_STORED)
z.writestr("stack.xml", stack_xml, compress_type=zipfile.ZIP_DEFLATED)
for n, d in pngs.items():
z.writestr(n, d, compress_type=zipfile.ZIP_STORED)
if merged:
z.writestr("mergedimage.png", R.png(w, h, bytes(w * h * 4)), compress_type=zipfile.ZIP_STORED)
z.close()
return buf.getvalue()
def generate(ctx):
cases = []
imgs = {}
for i, (w, h) in enumerate(((40, 30), (20, 10), (8, 8), (10, 12), (6, 5))):
imgs["data/l%d.png" % i] = (w, h, R.photo(w, h, i + 1, i > 0))
pngs = {k: R.png(*v) for k, v in imgs.items()}
def lay(src, name, x, y, op, vis, depth):
w, h, px = imgs[src]
return {"name": name, "x": x, "y": y, "opacity": op[0], "visible": vis, "blend": op[1], "depth": depth, "rgba": px, "w": w, "h": h}
xml1 = '''<?xml version="1.0" encoding="UTF-8"?>
<image version="0.0.6" w="40" h="30" xres="144" yres="144"><stack>
<layer name="top hidden" src="data/l2.png" x="1" y="2" visibility="hidden" opacity="1.0"/>
<layer name="mid" src="data/l1.png" x="5" y="7" opacity="0.5" composite-op="svg:multiply"/>
<layer name="background" src="data/l0.png"/>
</stack></image>'''
cases.append({"name": "plain", "data": build(xml1, pngs), "w": 40, "h": 30, "dpi": 144, "merged": True, "layers": [
lay("data/l0.png", "background", 0, 0, (1.0, "normal"), True, 0), lay("data/l1.png", "mid", 5, 7, (0.5, "multiply"), True, 0),
lay("data/l2.png", "top hidden", 1, 2, (1.0, "normal"), False, 0)]})
xml2 = '''<image w="40" h="30"><stack>
<stack name="outer" isolation="isolate" opacity="0.8" x="2" y="3">
<layer name="a" src="data/l3.png" x="1" y="1" composite-op="svg:screen"/>
<stack name="inner" opacity="0.5"><layer name="b" src="data/l4.png" composite-op="svg:color-dodge"/></stack>
</stack>
<layer name="base" src="data/l0.png"/>
</stack></image>'''
cases.append({"name": "nested", "data": build(xml2, pngs, merged=False), "w": 40, "h": 30, "merged": False, "layers": [
lay("data/l0.png", "base", 0, 0, (1.0, "normal"), True, 0),
{"name": "outer", "x": 0, "y": 0, "opacity": 0.8, "visible": True, "blend": "normal", "depth": 0, "group": True},
{"name": "inner", "x": 0, "y": 0, "opacity": 0.5, "visible": True, "blend": "passThrough", "depth": 1, "group": True},
lay("data/l4.png", "b", 2, 3, (1.0, "colorDodge"), True, 2),
lay("data/l3.png", "a", 3, 4, (1.0, "screen"), True, 1)]})
# ours, taken apart
mine = S.ours(ctx, "ora")["ours_doc.ora"]
z = zipfile.ZipFile(io.BytesIO(mine))
infos = z.infolist()
ok = infos[0].filename == "mimetype" and infos[0].compress_type == zipfile.ZIP_STORED and z.read("mimetype") == b"image/openraster"
root = ET.fromstring(z.read("stack.xml"))
layers = []
def walk(node, depth):
for ch in node:
a = ch.attrib
e = {"tag": ch.tag, "name": a.get("name", ""), "depth": depth, "opacity": float(a.get("opacity", "1")),
"visible": a.get("visibility", "visible") == "visible", "op": a.get("composite-op", ""), "isolation": a.get("isolation", "")}
if ch.tag == "layer":
e["x"], e["y"] = int(a.get("x", "0")), int(a.get("y", "0"))
e["src"] = a["src"]
layers.append(e)
if ch.tag == "stack":
walk(ch, depth + 1)
walk(root.find("stack"), 0)
srcs = [l["src"] for l in layers if l["tag"] == "layer"] + ["mergedimage.png", "Thumbnails/thumbnail.png"]
decoded = T.pillow(ctx, [z.read(s) for s in srcs])
px = {s: {"w": d[1], "h": d[2], "rgba": T.rgba_from(d[0], d[3])} for s, d in zip(srcs, decoded)}
for l in layers:
if l["tag"] == "layer":
l.update(px[l["src"]])
ours = {"data": mine, "ok": ok, "w": int(root.attrib["w"]), "h": int(root.attrib["h"]), "entries": [i.filename for i in infos],
"layers": layers, "merged": px["mergedimage.png"], "thumb": [px["Thumbnails/thumbnail.png"]["w"], px["Thumbnails/thumbnail.png"]["h"]]}
ctx.emit("ora", {"cases": cases, "ours": ours})
+63
View File
@@ -0,0 +1,63 @@
# Quake PAK fixtures (tools/fixtures.py): PAK files written here from the Quake source's dpackheader_t / dpackfile_t
# layout (header, file data in order, directory at the end: the layout id's qpak and most tools write), in the Quake
# ("PACK", 56-byte names) and SiN ("SPAK", 120-byte names) variants, plus one with the directory first and padding
# between files; with the expected entries read back by an independent Python reader here.
# tests/gen/pak.luau { { name, variant, data, entries = { { name, size, crc } }, files = { { name, data } } } }
import struct, zlib
VARIANTS = {"quake": (b"PACK", 56), "sin": (b"SPAK", 120)}
def write(files, variant="quake", dir_first=False, pad=0):
magic, nl = VARIANTS[variant]
dirlen = len(files) * (nl + 8)
out = bytearray(magic + b"\0" * 8)
if dir_first:
dirofs = 12
out += b"\0" * dirlen
offs = []
for name, data in files:
out += b"\xee" * pad
offs.append(len(out))
out += data
if not dir_first:
dirofs = len(out)
out += b"\0" * dirlen
for i, (name, data) in enumerate(files):
struct.pack_into("<%dsII" % nl, out, dirofs + i * (nl + 8), name.encode(), offs[i], len(data))
struct.pack_into("<II", out, 4, dirofs, dirlen)
return bytes(out)
def read(data):
magic, dirofs, dirlen = struct.unpack_from("<4sII", data)
nl = {b"PACK": 56, b"SPAK": 120}[magic]
out = []
for i in range(dirlen // (nl + 8)):
name, at, n = struct.unpack_from("<%dsII" % nl, data, dirofs + i * (nl + 8))
out.append({"name": name.split(b"\0")[0].decode(), "size": n, "crc": zlib.crc32(data[at:at + n])})
return out
def generate(ctx):
rng = ctx.rng(17)
base = [
("gfx/palette.lmp", bytes(rng.randrange(256) for _ in range(768))),
("maps/start.bsp", rng.randbytes(5000)),
("sound/misc/null.wav", b""),
("progs/player.mdl", rng.randbytes(1234)),
("default.cfg", b"bind w +forward\n"),
("a" * 55, b"longest quake name"),
]
cases = [
("quake", "quake", write(base), base),
("quake-dir-first", "quake", write(base, dir_first=True, pad=3), base),
("empty", "quake", write([]), []),
("sin", "sin", write(base + [("models/" + "b" * 100 + ".def", b"sin")], "sin"), base + [("models/" + "b" * 100 + ".def", b"sin")]),
]
out = []
for name, variant, data, files in cases:
out.append({"name": name, "variant": variant, "data": data, "entries": read(data),
"layoutDefault": not name.endswith("dir-first"),
"files": [{"name": n, "data": d} for n, d in files]})
ctx.emit("pak", out)
+58
View File
@@ -0,0 +1,58 @@
# PCX fixtures (tools/fixtures.py): files from netpbm's ppmtopcx (24-bit planes, 8-bit palette, packed 1 / 2 / 4-bit,
# 4-plane EGA, 1-bit mono), ImageMagick (24-bit, palette) and Pillow (RGB, P, L, 1), decoded by pcxtoppm (netpbm) as
# the reference; our encoder's files (tools/fixtures/_tex_encode.luau -a pcx) decoded by ImageMagick (it reads 4-plane alpha).
# tests/gen/pcx.luau { cases = { { name, data, w, h, rgba } }, ours = { { name, data, w, h, rgba } } }
import importlib.util, os, shutil, subprocess
_spec = importlib.util.spec_from_file_location("_raster_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_raster_ref.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/pcx"]
def ours(ctx, which):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if line.startswith("ours_") and "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
return files
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 40, 30, R.palette_image(40, 30, 200))
w.png("c16.png", 33, 17, R.palette_image(33, 17, 16, 5))
w.png("c4.png", 21, 9, R.palette_image(21, 9, 4, 6))
w.png("mono.png", 29, 13, bytes(v for i in range(29 * 13) for v in ((255,) * 3 if (i * 7) % 5 < 2 else (0,) * 3) + (255,)))
nb = ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam c16.png | pamtopnm > c16.ppm",
"pngtopam c4.png | pamtopnm > c4.ppm", "pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm > mono.pbm",
"ppmtopcx -24bit photo.ppm > nb_24bit.pcx", "ppmtopcx -8bit pal.ppm > nb_8bit.pcx", "ppmtopcx -packed c16.ppm > nb_packed4.pcx",
"ppmtopcx -packed c4.ppm > nb_packed2.pcx", "ppmtopcx -planes 4 c16.ppm > nb_planes4.pcx", "ppmtopcx mono.pbm > nb_mono.pcx",
"ppmtopcx -planes 3 c4.ppm > nb_planes3.pcx"]
w.sh("netpbm", nb)
w.sh("imagemagick", ["magick photo.png -alpha off im_24bit.pcx", "magick pal.png -alpha off -type palette im_palette.pcx"])
code = ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('photo.png').convert('RGB')\nim.save('pil_rgb.pcx')\n"
"Image.open('pal.png').convert('RGB').quantize(256).save('pil_p.pcx')\nim.convert('L').save('pil_l.pcx')\n"
"Image.open('mono.png').convert('1').save('pil_1.pcx')\n") % w.dir
ctx.python(["pillow"], code)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".pcx"))
mine = ours(ctx, "pcx")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
w.sh("netpbm", ["pcxtoppm %s > %s.ppm" % (n, n) for n in names])
w.sh("imagemagick", ["magick %s -depth 8 pam:%s.ppm" % (n, n) for n in sorted(mine)])
cases, our = [], []
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
(our if n.startswith("ours_") else cases).append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
ctx.emit("pcx", {"cases": cases, "ours": our})
finally:
w.close()
+77
View File
@@ -0,0 +1,77 @@
# PMX / PMD fixtures (tools/fixtures.py): assimp's MMD test model (test/models-nonbsd/MMD/Alicia_blade.pmx, read from
# the nixpkgs assimp source, never committed) and synthetic models from tools/fixtures/_pmx_writer.py (PMX 2.0 / 2.1,
# UTF-16 / UTF-8, index sizes 1 / 2 / 4, additional UVs, every deform and morph type), with assimp's counts
# (`assimp info -r`: meshes, faces, vertices, materials, bones) and world bounds (assimp's PreTransformVertices
# export), plus the generator's own facts (vertex / bone / morph counts, sample vertices). The same synthetic models as
# PMD 1.0 (no reference reads PMD: the test compares them with the PMX decode).
# tests/gen/pmx_cases.luau { name, data, files = { name -> bytes }, assimp, expect? }
# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) }
import importlib.util, os, struct, zlib
INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def tiny_png():
raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
W = load(ctx, "_pmx_writer")
tmp = M.tempdir()
cases, pmds = [], []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx")
if os.path.exists(src):
cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}})
variants = [
("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)),
("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)),
("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)),
("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)),
]
png = tiny_png()
for fname, wopts, topts in variants:
uva = wopts["uva"]
model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts)
data = W.Pmx(**wopts).build(model)
path = os.path.join(tmp, fname)
with open(path, "wb") as f:
f.write(data)
vs = model["vertices"]
samples = []
for i in (0, 1, 2, 3, len(vs) - 1):
v = vs[i]
samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]})
types = {}
for mo in model["morphs"]:
types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1
expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types,
"textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"],
"rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])}
cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect})
if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2:
pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.update(Fbx.assimp_extra(ctx, c["path"]))
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.ptv_bounds(ctx, c["path"], tmp))
if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"):
a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("pmx_cases", cases)
ctx.emit("pmx_pmd", pmds)
+39
View File
@@ -0,0 +1,39 @@
# SGI fixtures (tools/fixtures.py): files from netpbm (pnmtosgi: RLE and verbatim, RGB and grey), ImageMagick (RGB,
# RGBA, 16-bit) and Pillow (L, RGB, RGBA), plus our encoder's files (tools/fixtures/_tex_encode.luau -a sgi); the
# reference is ImageMagick's decode of each file (16-bit within 1: it rounds where we keep the high byte).
# tests/gen/sgi.luau { cases = { { name, data, w, h, rgba, tol } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sgi"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pnmtosgi -rle photo.ppm > nb_rle.sgi", "pnmtosgi -verbatim photo.ppm > nb_verbatim.sgi",
"ppmtopgm photo.ppm | pnmtosgi -rle > nb_grey.sgi"])
w.sh("imagemagick", ["magick photo.png -alpha off im_rgb.sgi", "magick alpha.png im_rgba.sgi", "magick photo.png -alpha off -depth 16 im_rgb16.sgi",
"magick alpha.png -compress none im_rgba_verbatim.sgi"])
ctx.python(["pillow"], ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('alpha.png')\nim.save('pil_rgba.sgi')\n"
"im.convert('RGB').save('pil_rgb.sgi')\nim.convert('L').save('pil_l.sgi')\n") % w.dir)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".sgi"))
mine = S.ours(ctx, "sgi")
for n, d in mine.items():
w.write(n, d)
ref = S.magick_cases(R, w, names + sorted(mine))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba, "tol": 1 if "16" in n else 0})
ctx.emit("sgi", out)
finally:
w.close()
+499
View File
@@ -0,0 +1,499 @@
# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four
# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every
# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips,
# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and
# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each
# audio track as f32le.
# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels,
# bits, codec, frames, crc } } } }
import heapq, importlib.util, math, os, random, struct, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py"]
RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048]
# ---------------------------------------------------------------------------------------------------- bits / trees
class Bits:
def __init__(self):
self.bits = []
def put(self, v, n):
for i in range(n):
self.bits.append((v >> i) & 1)
def code(self, c):
self.bits.extend(c)
def bytes(self):
out = bytearray((len(self.bits) + 7) // 8)
for i, b in enumerate(self.bits):
out[i >> 3] |= b << (i & 7)
return bytes(out)
def huffman(freqs, maxdepth):
"""a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)"""
f = dict(freqs)
while True:
heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))]
heapq.heapify(heap)
k = len(heap)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2])))
k += 1
tree = heap[0][2]
if depth(tree) <= maxdepth:
return tree
f = {v: c // 2 + 1 for v, c in f.items()}
def depth(t):
return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1]))
def codes(t, prefix=(), out=None):
out = {} if out is None else out
if t[0] == "leaf":
out[t[1]] = list(prefix)
else:
codes(t[0], prefix + (0,), out)
codes(t[1], prefix + (1,), out)
return out
def write_tree8(bw, t):
if t[0] == "leaf":
bw.put(0, 1)
bw.put(t[1], 8)
else:
bw.put(1, 1)
write_tree8(bw, t[0])
write_tree8(bw, t[1])
class BigTree:
"""a header tree: values (16-bit) with three escape leaves for the recent-value cache"""
def __init__(self, freqs, rnd, absent_ok=True):
self.absent = not freqs
if self.absent:
return
lo = {}
hi = {}
for v, c in freqs.items():
lo[v & 255] = lo.get(v & 255, 0) + c
hi[v >> 8] = hi.get(v >> 8, 0) + c
# three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is
# left out: absent byte trees decode as 0)
esc = []
for l in sorted(lo):
for h in sorted(hi):
v = l | h << 8
if v not in freqs and len(esc) < 3:
esc.append(v)
while len(esc) < 3: # every combination used: widen the low byte tree
nl = next(x for x in range(256) if x not in lo)
lo[nl] = 1
esc.append(nl | sorted(hi)[0] << 8)
self.esc = esc
self.lo = huffman(lo, 27)
self.hi = huffman(hi, 27)
allv = dict(freqs)
for i, e in enumerate(esc):
allv[e] = max(1, sum(freqs.values()) // (8 + i))
self.tree = huffman(allv, 200)
self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree)
self.entries = count_entries(self.tree)
self.hi_absent = len(hi) == 1 and 0 in hi
self.rnd = rnd
def write(self, bw):
if self.absent:
bw.put(0, 1)
return
bw.put(1, 1)
bw.put(1, 1)
write_tree8(bw, self.lo)
bw.put(0, 1)
if self.hi_absent:
bw.put(0, 1)
else:
bw.put(1, 1)
write_tree8(bw, self.hi)
bw.put(0, 1)
for e in self.esc:
bw.put(e, 16)
self._write_big(bw, self.tree)
bw.put(0, 1)
def _write_big(self, bw, t):
if t[0] == "leaf":
bw.put(0, 1)
v = t[1]
bw.code(self.lcodes[v & 255])
if not self.hi_absent:
bw.code(self.hcodes[v >> 8])
else:
bw.put(1, 1)
self._write_big(bw, t[0])
self._write_big(bw, t[1])
def size(self):
return 0 if self.absent else (self.entries + 3) * 4
def reset(self):
self.cache = [0, 0, 0]
def emit(self, bw, v):
if self.absent:
assert v == 0
return
hit = [k for k in range(3) if self.cache[k] == v]
if hit and self.rnd.random() < 0.7:
bw.code(self.vcodes[self.esc[hit[0]]])
else:
bw.code(self.vcodes[v])
if v != self.cache[0]:
self.cache[2] = self.cache[1]
self.cache[1] = self.cache[0]
self.cache[0] = v
def count_entries(t):
return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1])
# ---------------------------------------------------------------------------------------------------- video
def blocks_of(img, w, h):
return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)]
def classify(b, prev, v4):
if prev is not None and b == prev:
return ("skip",)
flat = [p for r in b for p in r]
cols = sorted(set(flat))
if len(cols) == 1:
return ("fill", cols[0])
if len(cols) == 2:
lo, hi = cols
m = 0
for i, p in enumerate(flat):
if p == hi:
m |= 1 << i
return ("mono", hi << 8 | lo, m)
if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]:
return ("full", 1)
if v4 and b[0] == b[1] and b[2] == b[3]:
return ("full", 2)
return ("full", 0)
def full_codes(b, mode):
if mode == 0:
out = []
for r in b:
out += [r[2] | r[3] << 8, r[0] | r[1] << 8]
return out
if mode == 1:
return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8]
return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8]
def plan(frames, w, h, v4):
"""per frame the list of runs: (kind, extra, [blocks])"""
out = []
prev = None
for img in frames:
bl = blocks_of(img, w, h)
cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)]
runs = []
i = 0
while i < len(bl):
c = cls[i]
key = c[:2] if c[0] in ("fill", "full") else c[:1]
j = i
while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key:
j += 1
n = j - i + 1
# the largest run length of the table that fits
k = max(r for r in RUNS if r <= n)
runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k)))
i += k
out.append(runs)
prev = bl
return out
def type_value(c, ri):
kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]]
v = kind | ri << 2
if c[0] == "fill":
v |= c[1] << 8
return v
def stats(plans, v4):
f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}}
def add(t, v):
f[t][v] = f[t].get(v, 0) + 1
for runs in plans:
for c, bl, cl, ri in runs:
add("type", type_value(c, ri))
if c[0] == "mono":
for x in cl:
add("mclr", x[1])
add("mmap", x[2])
elif c[0] == "full":
for b in bl:
for v in full_codes(b, c[1]):
add("full", v)
return f
def encode_video(frames, w, h, v4, rnd):
plans = plan(frames, w, h, v4)
f = stats(plans, v4)
trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")}
tb = Bits()
for k in ("mmap", "mclr", "full", "type"):
trees[k].write(tb)
treebytes = tb.bytes()
out = []
for runs in plans:
for t in trees.values():
t.reset()
bw = Bits()
for c, bl, cl, ri in runs:
trees["type"].emit(bw, type_value(c, ri))
if c[0] == "mono":
for x in cl:
trees["mclr"].emit(bw, x[1])
trees["mmap"].emit(bw, x[2])
elif c[0] == "full":
if v4:
bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0])
for b in bl:
for v in full_codes(b, c[1]):
trees["full"].emit(bw, v)
out.append(bw.bytes() or b"\0")
return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out
# ---------------------------------------------------------------------------------------------------- palettes
def pal_chunk(new, old, first):
"""a palette update: new / old are lists of 256 6-bit (r, g, b)"""
body = bytearray()
i = 0
while i < 256:
if not first and new[i] == old[i]:
j = i
while j < 256 and j - i < 128 and new[j] == old[j]:
j += 1
body.append(0x80 | (j - i - 1))
i = j
continue
# a copy from the old palette when the next entries appear there in a row
if not first:
for off in range(256):
n = 0
while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]:
n += 1
if n >= 2:
body += bytes([0x40 | (n - 1), off])
i += n
break
else:
off = None
if off is not None:
continue
body += bytes(new[i])
i += 1
size = 1 + len(body)
size = (size + 3) // 4 * 4
return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body))
# ---------------------------------------------------------------------------------------------------- audio
def pack_audio(samples, ch, bits):
"""one packed (SMKA) chunk body: samples interleaved (s16 or u8)"""
nb = bits // 8
bw = Bits()
bw.put(1, 1)
bw.put(1 if ch == 2 else 0, 1)
bw.put(1 if bits == 16 else 0, 1)
mod = 65536 if bits == 16 else 256
pred = list(samples[:ch])
deltas = []
for i in range(ch, len(samples)):
c = i % ch
d = (samples[i] - pred[c]) % mod
pred[c] = samples[i]
deltas.append((c, d))
ntrees = (2 if bits == 16 else 1) * ch
freqs = [dict() for _ in range(ntrees)]
for c, d in deltas:
if bits == 16:
freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1
freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1
else:
freqs[c][d] = freqs[c].get(d, 0) + 1
trees = [huffman(f or {0: 1}, 27) for f in freqs]
cds = [codes(t) for t in trees]
for t in trees:
bw.put(1, 1)
write_tree8(bw, t)
bw.put(0, 1)
for c in range(ch - 1, -1, -1):
v = samples[c] % mod
if bits == 16:
v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped
bw.put(v, bits)
for c, d in deltas:
if bits == 16:
bw.code(cds[2 * c][d & 255])
bw.code(cds[2 * c + 1][d >> 8])
else:
bw.code(cds[c][d])
return struct.pack("<I", len(samples) * nb) + bw.bytes()
def tone(n, ch, bits, rate, seed, f0):
rnd = random.Random(seed)
out = []
for i in range(n):
for c in range(ch):
v = 0.5 * math.sin(2 * math.pi * f0 * (c + 1) * i / rate) + 0.05 * (rnd.random() - 0.5)
if bits == 16:
out.append(int(v * 30000))
else:
out.append(int(128 + v * 120))
return out
# ---------------------------------------------------------------------------------------------------- files
def idx_frames(w, h, n, seed, busy=False):
rnd = random.Random(seed)
out = []
for t in range(n):
if busy: # textured, moving: mostly FULL blocks (the bench)
img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)]
else:
img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)]
for y in range(8, 24):
for x in range(8 + t * 4, 24 + t * 4):
img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks
for y in range(h - 16, h - 8):
for x in range(0, w):
img[y][x] = 50 + ((x // 2) % 5) if (t % 2 == 0) else 60 # doubled pixels: SMK4 modes
for y in range(28, 36):
for x in range(w // 2, w // 2 + 12):
img[y][x] = rnd.randrange(256)
out.append(img)
return out
def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False):
"""version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info"""
rnd = random.Random(seed)
frames = idx_frames(w, h, nframes, seed, busy)
if ring:
frames = frames + [frames[0]]
treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd)
total = len(frames)
# palettes (6-bit), changing on some frames
pals = []
cur = [(rnd.randrange(64), rnd.randrange(64), rnd.randrange(64)) for _ in range(256)]
for t in range(total):
if t in (3, 5):
cur = list(cur)
for k in range(20 + t, 40 + t):
cur[k] = (rnd.randrange(64), rnd.randrange(64), rnd.randrange(64))
cur[200:210] = pals[0][10:20] # a copy from the old palette
pals.append(list(cur))
# audio per frame
seconds = (pts_inc / 1000.0 if pts_inc > 0 else -pts_inc / 100000.0)
achunks = []
for ti, (kind, rate, ch, bits) in enumerate(tracks):
per = []
done = 0
for t in range(total):
n = int(round((t + 1) * seconds * rate)) - done
done += n
s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti)
if kind == "packed":
per.append(pack_audio(s, ch, bits))
else:
per.append(b"".join(struct.pack("<h", v) if bits == 16 else bytes([v]) for v in s))
achunks.append(per)
data = []
flags = []
for t in range(total):
body = b""
fl = 0
if t == 0 or pals[t] != pals[t - 1]:
body += pal_chunk(pals[t], pals[t - 1] if t else None, t == 0)
fl |= 1
for ti in range(len(tracks)):
a = achunks[ti][t]
body += struct.pack("<I", 4 + len(a)) + a
fl |= 2 << ti
body += video[t]
body += bytes((-len(body)) % 4)
data.append(body)
flags.append(fl)
hd = b"SMK%d" % version + struct.pack("<IIIiI", w, h, nframes, pts_inc, 1 if ring else 0)
hd += struct.pack("<7I", *[max(len(a) for a in achunks[i]) if i < len(tracks) else 0 for i in range(7)])
hd += struct.pack("<I", len(treebytes)) + struct.pack("<4I", *sizes)
for i in range(7):
if i < len(tracks):
kind, rate, ch, bits = tracks[i]
f = 0x40 | (0x80 if kind == "packed" else 0) | (0x20 if bits == 16 else 0) | (0x10 if ch == 2 else 0)
hd += struct.pack("<I", rate | f << 24)
else:
hd += struct.pack("<I", 0)
hd += struct.pack("<I", 0)
hd += b"".join(struct.pack("<I", len(d) | (1 if t == 0 else 0)) for t, d in enumerate(data))
hd += bytes(flags)
return hd + treebytes + b"".join(data)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="smkfx_")
specs = [
("smk2_audio.smk", 2, 64, 48, 8, 100, [("packed", 22050, 2, 16), ("packed", 11025, 1, 8)], False, 1),
("smk4_ring.smk", 4, 96, 64, 9, -6667, [("raw", 16000, 1, 16), ("raw", 8000, 2, 8)], True, 2),
("smk4_mono.smk", 4, 64, 48, 6, 80, [("packed", 22050, 1, 16), ("packed", 11025, 2, 8)], False, 3),
("smk2_silent.smk", 2, 128, 64, 5, 66, [], False, 4),
]
cases = []
for name, ver, w, h, n, pts, tracks, ring, seed in specs:
data = smk_file(ver, w, h, n, pts, tracks, ring, seed)
path = os.path.join(tmp, name)
open(path, "wb").write(data)
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
sz = w * h * 4
crcs = [zlib.crc32(raw[i:i + sz]) & 0xffffffff for i in range(0, len(raw) - sz + 1, sz)]
assert len(crcs) == n + (1 if ring else 0), (name, len(crcs))
audio = []
for i, (kind, rate, ch, bits) in enumerate(tracks):
pcm = V.ffmpeg(["-i", path, "-map", "0:a:%d" % i, "-f", "f32le", "-"])
audio.append({"rate": rate, "channels": ch, "bits": bits,
"codec": "smackaudio" if kind == "packed" else ("pcm_s16le" if bits == 16 else "pcm_u8"),
"frames": len(pcm) // (4 * ch), "crc": zlib.crc32(pcm) & 0xffffffff})
rate = 1000 / pts if pts > 0 else 100000 / -pts
cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio,
"ring": ring})
ctx.emit("smk_cases", cases)
# tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames
ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320,
"height": 200, "frames": 10})
+45
View File
@@ -0,0 +1,45 @@
# Sun Raster fixtures (tools/fixtures.py): files from netpbm (pnmtorast: standard and byte-encoded, 1 / 8 / 24-bit) and
# ImageMagick (24-bit, 32-bit with alpha, 8-bit palette, 1-bit), plus our encoder's files (tools/fixtures/_tex_encode
# .luau -a sunras); the reference is rasttopnm for netpbm's and our files (RGB only) and ImageMagick's decode for the others.
# tests/gen/sunras.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sunras"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm",
"pnmtorast -standard photo.ppm > nb_24_standard.ras", "pnmtorast -rle photo.ppm > nb_24_rle.ras",
"pnmtorast -rle pal.ppm > nb_8_rle.ras", "ppmtopgm photo.ppm | pnmtorast -standard > nb_grey.ras",
"ppmtopgm photo.ppm | pgmtopbm | pnmtorast -rle > nb_1.ras"])
w.sh("imagemagick", ["magick photo.png -alpha off im_24.ras", "magick alpha.png im_32.ras", "magick pal.png -alpha off -type palette im_8.ras",
"magick photo.png -monochrome im_1.ras"])
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".ras"))
mine = S.ours(ctx, "sunras")
for n, d in mine.items():
w.write(n, d)
# netpbm's own files through rasttopnm (ImageMagick cuts the last row of nb_8_rle short), the rest through ImageMagick
nb = [n for n in names if n.startswith("nb_")] + sorted(mine)
w.sh("netpbm", ["rasttopnm %s > %s.pnm" % (n, n) for n in nb])
ref = S.magick_cases(R, w, [n for n in names if not n.startswith("nb_")], "sun")
for n in nb:
ref[n] = R.pnm_rgba(w.read(n + ".pnm"))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
ctx.emit("sunras", out)
finally:
w.close()
+208
View File
@@ -0,0 +1,208 @@
# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's
# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions
# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a
# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode
# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per
# frame over the packed planes of the picture region, with the frame's pts.
# tests/gen/theora_<name>.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } }
# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original)
# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64),
# rate, channels }
# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio
# tests/gen/theora_mkv.luau { file (base64 .mkv), frames }
# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau
import base64, os, shutil, struct, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
def src(kind, w, h, rate, t):
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
# name: (input args, encoder args, pixel format)
CASES = {
"q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"),
"q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"),
"q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"),
"motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"),
"odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"),
"static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"),
"yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"),
"yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"),
"odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"),
}
# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd
# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched
# file (-flags unaligned: the exact crop)
PATCH = {
"crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)),
"crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)),
}
def crc32(b):
return zlib.crc32(b) & 0xFFFFFFFF
def ogg_pages(data):
"""yield (header fields, segment table, body) of each Ogg page"""
i = 0
while i + 27 <= len(data):
assert data[i:i + 4] == b"OggS"
flags, granule, serial, seq = data[i + 5], struct.unpack_from("<q", data, i + 6)[0], \
struct.unpack_from("<I", data, i + 14)[0], struct.unpack_from("<I", data, i + 18)[0]
n = data[i + 26]
segs = list(data[i + 27:i + 27 + n])
body = data[i + 27 + n:i + 27 + n + sum(segs)]
yield flags, granule, serial, seq, segs, body
i += 27 + n + sum(segs)
OGG_CRC = []
for _i in range(256):
r = _i << 24
for _ in range(8):
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
OGG_CRC.append(r & 0xFFFFFFFF)
def ogg_crc(b):
c = 0
for x in b:
c = ((c << 8) ^ OGG_CRC[((c >> 24) ^ x) & 0xFF]) & 0xFFFFFFFF
return c
def page(flags, granule, serial, seq, packets_segs, body):
head = b"OggS" + bytes([0, flags]) + struct.pack("<qII", granule, serial, seq) + b"\0\0\0\0" + \
bytes([len(packets_segs)]) + bytes(packets_segs)
p = bytearray(head + body)
struct.pack_into("<I", p, 22, ogg_crc(p))
return bytes(p)
def splice_empty(data, after):
"""rewrite a single-stream Ogg Theora file with one page per packet and an empty packet after data packet
`after` (1-based); granules are recomputed as frame counts since the last keyframe (bitstream 3.2.1 numbering)"""
packets, cur = [], b""
shift = None
for flags, granule, serial, seq, segs, body in ogg_pages(data):
o = 0
for s in segs:
cur += body[o:o + s]
o += s
if s < 255:
packets.append(cur)
cur = b""
sid = serial
shift = (packets[0][40] & 0x03) << 3 | packets[0][41] >> 5
out = []
seq = 0
frames = []
data_packets = packets[3:]
data_packets = data_packets[:after] + [b""] + data_packets[after:]
key = 0
for k, p in enumerate(packets[:3]):
segs = [255] * (len(p) // 255) + [len(p) % 255]
out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p))
seq += 1
for k, p in enumerate(data_packets):
n = k + 1
if len(p) > 0 and not (p[0] & 0x40):
key = n
segs = [255] * (len(p) // 255) + [len(p) % 255]
g = (key << shift) | (n - key)
out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p))
seq += 1
return b"".join(out)
def patch_picture(data, w, h, x, y):
"""rewrite the first page (the identification header) with another picture region"""
out = bytearray(data)
n = out[26]
o = 27 + n # the packet starts here
assert out[o:o + 7] == b"\x80theora"
out[o + 14:o + 17] = w.to_bytes(3, "big")
out[o + 17:o + 20] = h.to_bytes(3, "big")
out[o + 20] = x
out[o + 21] = y
plen = 27 + n + sum(out[27:27 + n])
out[22:26] = b"\0\0\0\0"
struct.pack_into("<I", out, 22, ogg_crc(bytes(out[:plen])))
return bytes(out)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
def ff(args):
return subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True).stdout
def framecrc(path, pixfmt, extra=None):
out = ff(["-flags", "unaligned", "-i", path] + (extra or []) + ["-map", "0:v", "-fps_mode", "passthrough", "-pix_fmt", pixfmt,
"-f", "framecrc", "-"]).decode()
frames = []
for line in out.splitlines():
if line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
frames.append([int(parts[1]), int(parts[5], 16)])
return frames
with tempfile.TemporaryDirectory(prefix="formats-theora-") as tmp:
for name, (inp, enc, pixfmt) in CASES.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = open(path, "rb").read()
w, h = [int(x) for x in inp[3].split("=")[2].split(":")[0].split("x")]
ctx.emit("theora_" + name, {"name": name, "width": w, "height": h, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
if name == "q6":
# an empty packet (a dropped / repeated frame) after the 5th frame
dupe = splice_empty(data, 5)
dpath = os.path.join(tmp, "dupe.ogv")
open(dpath, "wb").write(dupe)
ctx.emit("theora_dupe", {"name": "dupe", "width": w, "height": h, "pixfmt": pixfmt, "file": b64(dupe),
"frames": framecrc(path, pixfmt)})
for name, (inp, enc, pixfmt, (pw, ph, px, py)) in PATCH.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = patch_picture(open(path, "rb").read(), pw, ph, px, py)
open(path, "wb").write(data)
ctx.emit("theora_" + name, {"name": name, "width": pw, "height": ph, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
# Theora + Vorbis (stereo 44.1 kHz)
av = os.path.join(tmp, "av.ogv")
ff(src("testsrc2", 160, 120, 25, 1) + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1",
"-ac", "2", "-c:v", "libtheora", "-q:v", "5", "-c:a", "libvorbis",
"-q:a", "3", "-shortest", av])
pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"),
"width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2})
# Theora + Opus, Theora + FLAC (mono, 0.5 s)
for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)):
path = os.path.join(tmp, "a_" + name + ".ogv")
ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate,
"-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc +
["-shortest", path])
pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"),
"width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1})
# Theora in Matroska (CodecPrivate: the three headers, Xiph-laced)
mkv = os.path.join(tmp, "t.mkv")
ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv])
ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"),
"width": 174, "height": 98})
# the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves)
bench = []
for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")):
path = os.path.join(tmp, "bench_" + kind + ".ogv")
ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path])
bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240})
ctx.emit("theora_bench", bench)
+99
View File
@@ -0,0 +1,99 @@
# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source,
# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's
# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as
# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back
# by VTK.
# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) }
# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files }
# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk }
import importlib.util, os, re
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py",
"tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"]
GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest",
"NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def primitives(data):
return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data))
def gltf_picks(ctx):
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in ("glTF", "glTF-Embedded", "glTF-Binary"):
d = os.path.join(d0, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if mains:
picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
return picks
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
tmp = M.tempdir()
cases = []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL")
for f in sorted(os.listdir(src)):
if f.lower().endswith(".wrl"):
files = {}
if f == "HelloWorld.wrl":
files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files})
picks = gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]):
cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}})
for name, text in sorted(R.FEATURES.items()):
p = os.path.join(tmp, name)
with open(p, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)})
for name, text in R.INLINE.items():
with open(os.path.join(tmp, name), "w") as f:
f.write(text)
refs = R.vtk_read(ctx, [c["path"] for c in cases])
for c, v in zip(cases, refs):
c["data"] = open(c["path"], "rb").read()
c["vtk"] = v
c["primitives"] = primitives(c["data"])
c["vtkTransforms"] = R.vtk_xform_ok(c["data"])
del c["path"]
ctx.emit("vrml_cases", cases)
for p in picks:
del p["path"]
ctx.emit("vrml_gltf", picks)
# VTK reads our output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".wrl"))
for name, data in ours.items():
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names])
out = []
for n, v in zip(names, refs):
e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])}
m = re.match(r"(case|gltf)_(\d+)\.wrl$", n)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("vrml_xcheck", out)
+126
View File
@@ -0,0 +1,126 @@
# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary;
# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the
# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with
# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners,
# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too.
# tests/gen/x_cases.luau { name, data, assimp = { ... } }
import importlib.util, os, re, struct, zlib
INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+')
def to_binary64(text):
"""a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)"""
body = text[16:]
out = bytearray(b"xof 0303bin 0064")
toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))]
i, nums = 0, []
def flush():
while nums:
isf = nums[0][0]
run = []
while nums and nums[0][0] == isf:
run.append(nums.pop(0)[1])
if isf:
out.extend(struct.pack("<HI", 7, len(run)) + b"".join(struct.pack("<d", v) for v in run))
else:
out.extend(struct.pack("<HI", 6, len(run)) + b"".join(struct.pack("<I", int(v) & 0xFFFFFFFF) for v in run))
while i < len(toks):
t = toks[i]
if t == b"template":
flush()
depth = 0
while i < len(toks):
if toks[i] == b"{":
depth += 1
elif toks[i] == b"}":
depth -= 1
if depth == 0:
break
i += 1
elif t in (b";", b","):
pass
elif t[:1] in b"0123456789-+.":
try:
v = float(t)
except ValueError:
v = 0.0
nums.append((b"." in t or b"e" in t.lower() or b"#" in t, v))
else:
flush()
if t == b"{":
out.extend(struct.pack("<H", 0x0A))
elif t == b"}":
out.extend(struct.pack("<H", 0x0B))
elif t.startswith(b'"'):
s = t[1:-1]
out.extend(struct.pack("<HI", 2, len(s)) + s + struct.pack("<H", 0x14))
elif t.startswith(b"<"):
pass
else:
out.extend(struct.pack("<HI", 1, len(t)) + t)
i += 1
flush()
return bytes(out)
def to_tzip(text):
"""a text .x file -> "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary"""
body = text[16:]
out = bytearray(b"xof 0303tzip0032") + struct.pack("<I", 0)
data = body
prev = b""
for p in range(0, len(data), 32768):
blk = data[p:p + 32768]
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
z = c.compress(blk) + c.flush(zlib.Z_FINISH)
out.extend(struct.pack("<HH", len(blk), len(z) + 2) + b"CK" + z)
prev = blk
struct.pack_into("<I", out, 16, len(data) + 16) # the size counts the 16-byte header (D3DX)
return bytes(out)
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/X", "models-nonbsd/X"):
d0 = os.path.join(src, "test", sub)
for f in sorted(os.listdir(d0)):
p = os.path.join(d0, f)
if os.path.isfile(p) and open(p, "rb").read(4) == b"xof ":
cases.append({"name": sub.split("/")[0] + "/" + f, "path": p})
# variants of the small text files: binary 64-bit floats and tzip
for name in ("test_cube_text.x", "kwxport_test_cubewithvcolors.x", "test.x", "anim_test.x"):
p = os.path.join(src, "test", "models", "X", name)
text = open(p, "rb").read()
for kind, data in (("bin64", to_binary64(text)), ("tzip", to_tzip(text))):
q = os.path.join(tmp, "%s.%s.x" % (name[:-2], kind))
open(q, "wb").write(data)
cases.append({"name": "variant/%s.%s.x" % (name[:-2], kind), "path": q, "of": "models/" + name})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.assimp_extra(ctx, c["path"]))
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("x_cases", cases)
+135
View File
@@ -0,0 +1,135 @@
# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs
# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models
# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference
# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's
# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp.
# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) }
# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp }
import importlib.util, os, re, subprocess
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf",
"tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py",
"tools/fixtures/_vrml_encode.luau"]
FEATURES = {
"feat_sets.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Interchange" version="3.3"><Scene>
<Transform translation="0 0 0"><Shape><Appearance><Material diffuseColor="1 0 0"/></Appearance>
<IndexedTriangleSet index="0 1 2 0 2 3" solid="false"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/>
<ColorRGBA color="1 0 0 1 0 1 0 1 0 0 1 0.5 1 1 1 1"/></IndexedTriangleSet></Shape></Transform>
<Transform translation="2 0 0"><Shape><TriangleFanSet fanCount="5"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0 -1 1 0"/></TriangleFanSet></Shape></Transform>
<Transform translation="4 0 0"><Shape><IndexedTriangleStripSet index="0 1 2 3 -1 4 5 6"><Coordinate point="0 0 0 1 0 0 0 1 0 1 1 0 0 2 0 1 2 0 0 3 0"/></IndexedTriangleStripSet></Shape></Transform>
<Transform translation="6 0 0"><Shape><IndexedQuadSet index="0 1 2 3"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/></IndexedQuadSet></Shape></Transform>
<Transform translation="8 0 0"><Shape><TriangleSet><Coordinate point="0 0 0 1 0 0 0 1 0 0 0 1 1 0 1 0 1 1"/></TriangleSet></Shape></Transform>
<Transform translation="0 3 0"><Shape><LineSet vertexCount="3 2"><Coordinate point="0 0 0 1 0 0 1 1 0 2 2 2 3 3 3"/></LineSet></Shape></Transform>
</Scene></X3D>
""",
"feat_proto.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Immersive" version="3.3"><head><meta name="title" content="protos"/><unit category="length" name="centimetre" conversionFactor="0.01"/></head>
<Scene>
<ProtoDeclare name="Post"><ProtoInterface>
<field name="height" type="SFFloat" accessType="initializeOnly" value="2"/>
<field name="where" type="SFVec3f" accessType="inputOutput" value="0 0 0"/>
<field name="look" type="SFNode" accessType="inputOutput"><Appearance><Material diffuseColor="0 0 1"/></Appearance></field>
</ProtoInterface>
<ProtoBody><Transform><IS><connect nodeField="translation" protoField="where"/></IS>
<Shape><IS><connect nodeField="appearance" protoField="look"/></IS>
<Cylinder radius="0.1"><IS><connect nodeField="height" protoField="height"/></IS></Cylinder></Shape></Transform></ProtoBody>
</ProtoDeclare>
<ProtoInstance name="Post" DEF="P1"><fieldValue name="where" value="1 0 0"/></ProtoInstance>
<ProtoInstance name="Post"><fieldValue name="where" value="-1 0 0"/><fieldValue name="height" value="4"/></ProtoInstance>
<Transform DEF="Spin"><Shape><Appearance><PhysicalMaterial baseColor="0.5 0.5 0.5" metallic="0.25" roughness="0.75"/></Appearance>
<Box size="1 1 1"/></Shape></Transform>
<TimeSensor DEF="Clock" cycleInterval="2" loop="true"/>
<OrientationInterpolator DEF="Rot" key="0 0.5 1" keyValue="0 1 0 0 0 1 0 3.14159 0 1 0 6.28318"/>
<ROUTE fromNode="Clock" fromField="fraction_changed" toNode="Rot" toField="set_fraction"/>
<ROUTE fromNode="Rot" fromField="value_changed" toNode="Spin" toField="set_rotation"/>
<OrthoViewpoint fieldOfView="-2 -1 2 1" position="0 0 5"/>
<Shape><Appearance><UnlitMaterial emissiveColor="0 1 0"/></Appearance><PointSet><Coordinate point="0 5 0 1 5 0"/><Color color="1 0 0 0 1 0"/></PointSet></Shape>
</Scene></X3D>
""",
"feat_classic.x3dv": """#X3D V3.3 utf8
PROFILE Interchange
COMPONENT Geometry2D:1
META "title" "classic"
UNIT length millimetre 0.001
DEF Root Transform { translation 1 2 3 children [
Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } }
geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ]
color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } }
Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } }
] }
""",
}
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def reference(ctx, M, Fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
if not a.get("failed"):
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.assimp_extra(ctx, path))
a.update(Fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
V = load(ctx, "vrml")
tmp = M.tempdir()
cases = []
root = os.path.join(Fbx.assimp_src(ctx), "test", "models")
for sub in ("X3D", "X3DV", "X3DB"):
d = os.path.join(root, sub)
for f in sorted(os.listdir(d)):
if f.lower().endswith((".x3d", ".x3dv", ".x3db")):
files = {}
if f.startswith("HelloWorld"):
files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files})
picks = V.gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]):
cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}})
for p in picks:
out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d")
try:
ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"])
except subprocess.CalledProcessError:
continue
cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])})
for name, text in sorted(FEATURES.items()):
path = os.path.join(tmp, name)
with open(path, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": path, "files": {}})
for c in cases:
c["data"] = open(c["path"], "rb").read()
c["primitives"] = V.primitives(c["data"])
c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True}
del c["path"]
ctx.emit("x3d_cases", cases)
# assimp reads our X3D output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
out = []
for name in sorted(n for n in ours if n.endswith(".x3d")):
path = os.path.join(xtmp, name)
with open(path, "wb") as f:
# assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires)
f.write(re.sub(rb'url="&quot;([^&"]*)&quot;"', rb'url="\1"', ours[name]))
e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)}
m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("x3d_xcheck", out)
+43
View File
@@ -0,0 +1,43 @@
# XBM fixtures (tools/fixtures.py): files from netpbm (pbmtoxbm X11 and -x10), ImageMagick and Pillow (with a hotspot),
# a hand-written one (comments, odd spacing); the reference is xbmtopbm (netpbm); our encoder's files
# (tools/fixtures/_tex_encode.luau -a xbm) read by xbmtopbm.
# tests/gen/xbm.luau { cases = { { name, data, w, h, rgba, hotspot? } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xbm"]
def generate(ctx):
w = R.Work(ctx)
try:
mono = bytes(v for i in range(29 * 13) for v in ((0,) * 3 if (i * 7 + i // 29) % 5 < 2 else (255,) * 3) + (255,))
w.png("mono.png", 29, 13, mono)
w.png("mono2.png", 16, 9, bytes(v for i in range(16 * 9) for v in ((0,) * 3 if (i % 3 == 0) else (255,) * 3) + (255,)))
w.sh("netpbm", ["pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm -threshold > mono.pbm", "pbmtoxbm mono.pbm > nb_x11.xbm",
"pbmtoxbm -x10 mono.pbm > nb_x10.xbm"])
w.sh("imagemagick", ["magick mono2.png im.xbm"])
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('mono.png').convert('1').save('pil.xbm', hotspot=(3, 4))\n" % w.dir)
w.write("hand.xbm", b"/* a comment */\n#define hand_width 10\n#define hand_height 2\nstatic unsigned char hand_bits[] = {\n 0xff,0x03, /* row 0 */\n 0x00, 0x01 };\n")
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xbm"))
mine = S.ours(ctx, "xbm")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
w.sh("netpbm", ["xbmtopbm %s > %s.pbm" % (n, n) for n in allnames])
out = {"cases": [], "ours": []}
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".pbm"))
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
if n == "pil.xbm":
c["hotspot"] = [3, 4]
out["ours" if n.startswith("ours_") else "cases"].append(c)
ctx.emit("xbm", out)
finally:
w.close()
+58
View File
@@ -0,0 +1,58 @@
# XPM fixtures (tools/fixtures.py): files from netpbm (ppmtoxpm -hexonly), ImageMagick (with alpha: None) and
# hand-written ones (colour names, #RGB / #RRRRGGGGBBBB, g / m keys, two chars per pixel, XPM 2); the reference is
# ImageMagick's decode (the XPM 2 file's values are written here: ImageMagick does not read XPM 2); our encoder's files (tools/fixtures/_tex_encode.luau -a xpm) read by ImageMagick.
# tests/gen/xpm.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xpm"]
HAND = b'''/* XPM */
static char * hand_xpm[] = {
/* width height ncolors cpp */
"6 4 6 2",
" c None",
".. c red",
"XX g4 #888 c LightBlue m white",
"oo c #FFFF00000000",
"++ s mine c navy",
"@@ c Gold",
" ..XXoo++@@",
"..XXoo++@@ ",
"XXoo++@@ ..",
"oo++@@ ..XX"};
'''
XPM2 = b"! XPM2\n3 2 2 1\na c #102030\nb c white\nabb\nbab\n"
def generate(ctx):
w = R.Work(ctx)
try:
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
w.png("alpha.png", 20, 11, bytes(v for i in range(20 * 11) for v in (((i * 40) % 256, 80, 200, 255 if i % 3 else 0))))
w.sh("netpbm", ["pngtopam pal.png | pamtopnm > pal.ppm", "ppmtoxpm -hexonly pal.ppm > nb.xpm"])
w.sh("imagemagick", ["magick pal.png -alpha off im.xpm", "magick alpha.png im_alpha.xpm"])
w.write("hand.xpm", HAND)
w.write("hand2.xpm", XPM2)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xpm") and f != "hand2.xpm")
mine = S.ours(ctx, "xpm")
for n, d in mine.items():
w.write(n, d)
ref = S.magick_cases(R, w, names + sorted(mine), "xpm")
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
# ImageMagick keeps the colour of transparent pixels; we decode None as transparent black
rgba = bytes(0 if rgba[i - i % 4 + 3] == 0 else v for i, v in enumerate(rgba))
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
a, b = bytes((0x10, 0x20, 0x30, 255)), b"\xff" * 4
out["cases"].append({"name": "hand2.xpm (XPM 2)", "data": XPM2, "w": 3, "h": 2, "rgba": a + b + b + b + a + b})
ctx.emit("xpm", out)
finally:
w.close()