ws-3d2/usda: model/usda - USD ASCII read / write (+ USDZ read), checked against OpenUSD (pxr), assimp's USD models and Blender exports

Reads stage metadata, xform op stacks (every rotate order, orient, transform, pivots / !invert!, resetXformStack),
time samples -> TRS animation, Mesh (all primvar interpolations + indices, GeomSubsets, holes, leftHanded),
UsdPreviewSurface / UsdUVTexture / UsdTransform2d materials with inherited bindings, cameras, UsdLux lights,
selected variants. USDC returns UNSUPPORTED. Writes Xform / Mesh / GeomSubset / Material / Camera / lights.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 09:41:47 -05:00
1 parent 75c677074a
commit fb7f6359cd
10 files changed
+4539

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
-- tools/fixtures/_usda_encode: run by tools/fixtures/usda.py (luau CLI, repo root): decodes every USDA case with our
-- reader and writes it back with our writer, printing "<file>\t<hex>" lines (case_<n>.usda + the texture files it
-- references) for OpenUSD (pxr) to read back.
local Usda = require("@formats/model/usda")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/usda_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for i, c in Cases do
if not c.expect then
local scene = Usda.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
local files = {}
local out = assert(Usda.encode(scene, { files = files, name = "case_" .. i .. ".usda" }))
print(string.format("case_%d.usda\t%s", i, hex(buffer.tostring(out))))
for name, data in files do
if not string.find(name, "%.%.") and string.sub(name, 1, 1) ~= "/" then
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
end
end
end
end
end
+404
View File
@@ -0,0 +1,404 @@
# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], <this file's text>) with a JSON
# request on stdin:
# {"mode": "author", "dir": d} -> writes the authored test stages into d (usda, plus a usdc and a usdz) and prints
# the file names
# {"mode": "metrics", "paths": [...]} -> prints [ metrics per file ] (see metrics() below)
# {"mode": "convert", "src": a, "dst": b} -> usdc -> usda through Sdf (as usdcat does)
# {"mode": "specs", "paths": [...]} -> the number of prim specs in each layer (parse-only checks)
import json, math, os, struct, sys, zlib
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, UsdUtils, Vt
req = json.loads(sys.stdin.read())
def png(w, h, rgba):
raw = b"".join(b"\0" + bytes(rgba[(y * w) * 4:(y * w + 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) & 0xffffffff)
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 cube(stage, path, size=1.0, quads=True):
m = UsdGeom.Mesh.Define(stage, path)
s = size / 2
pts = [(-s, -s, -s), (s, -s, -s), (s, s, -s), (-s, s, -s), (-s, -s, s), (s, -s, s), (s, s, s), (-s, s, s)]
faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
m.CreatePointsAttr([Gf.Vec3f(*p) for p in pts])
if quads:
m.CreateFaceVertexCountsAttr([4] * 6)
m.CreateFaceVertexIndicesAttr([i for f in faces for i in f])
else:
m.CreateFaceVertexCountsAttr([3] * 12)
m.CreateFaceVertexIndicesAttr([i for f in faces for i in (f[0], f[1], f[2], f[0], f[2], f[3])])
m.CreateExtentAttr([Gf.Vec3f(-s, -s, -s), Gf.Vec3f(s, s, s)])
return m
def author(d):
names = []
# 1. transforms: every op kind and order
st = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
UsdGeom.SetStageMetersPerUnit(st, 1.0)
root = UsdGeom.Xform.Define(st, "/World")
st.SetDefaultPrim(root.GetPrim())
x = UsdGeom.Xform.Define(st, "/World/TRS")
x.AddTranslateOp().Set(Gf.Vec3d(1, 2, 3))
x.AddRotateXYZOp().Set(Gf.Vec3f(30, 45, 60))
x.AddScaleOp().Set(Gf.Vec3f(1, 2, 0.5))
cube(st, "/World/TRS/Cube")
for k, order in enumerate(["XZY", "YXZ", "YZX", "ZXY", "ZYX"]):
x = UsdGeom.Xform.Define(st, "/World/R%s" % order)
x.AddTranslateOp().Set(Gf.Vec3d(k * 3, 0, 0))
op = x.AddXformOp(getattr(UsdGeom.XformOp, "TypeRotate" + order))
op.Set(Gf.Vec3f(10 + k, 70, -25))
cube(st, "/World/R%s/Cube" % order, 0.5)
x = UsdGeom.Xform.Define(st, "/World/Single")
x.AddRotateYOp().Set(33.0)
x.AddRotateXOp().Set(-12.0)
x.AddScaleOp().Set(Gf.Vec3f(2, 2, 2))
cube(st, "/World/Single/Cube")
x = UsdGeom.Xform.Define(st, "/World/Orient")
x.AddOrientOp().Set(Gf.Quatf(0.9238795, 0, 0.3826834, 0))
x.AddTranslateOp().Set(Gf.Vec3d(0, 1, 0))
cube(st, "/World/Orient/Cube")
x = UsdGeom.Xform.Define(st, "/World/Pivot")
x.AddTranslateOp().Set(Gf.Vec3d(5, 0, 0))
piv = x.AddTranslateOp(opSuffix="pivot")
piv.Set(Gf.Vec3d(1, 1, 0))
x.AddRotateZOp().Set(90.0)
x.AddTranslateOp(opSuffix="pivot", isInverseOp=True)
cube(st, "/World/Pivot/Cube")
x = UsdGeom.Xform.Define(st, "/World/Matrix")
x.AddTransformOp().Set(Gf.Matrix4d(Gf.Rotation(Gf.Vec3d(1, 1, 0), 40), Gf.Vec3d(-2, 0, 4)) * Gf.Matrix4d().SetScale(Gf.Vec3d(1.5, 1.5, 1.5)))
cube(st, "/World/Matrix/Cube")
r = UsdGeom.Xform.Define(st, "/World/Matrix/Reset")
r.SetResetXformStack(True)
r.AddTranslateOp().Set(Gf.Vec3d(0, -3, 0))
cube(st, "/World/Matrix/Reset/Cube", 0.25)
neg = UsdGeom.Xform.Define(st, "/World/Negative")
neg.AddScaleOp().Set(Gf.Vec3f(-1, 1, 1))
cube(st, "/World/Negative/Cube")
names.append(("xforms.usda", st))
# 2. primvars, interpolations, holes, orientation, n-gons
st = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(st, 0.01)
m = UsdGeom.Mesh.Define(st, "/Grid")
st.SetDefaultPrim(m.GetPrim())
n = 4
pts = [Gf.Vec3f(i, j, 0.1 * i * j) for j in range(n + 1) for i in range(n + 1)]
counts, idx = [], []
for j in range(n):
for i in range(n):
a = j * (n + 1) + i
counts.append(4)
idx += [a, a + 1, a + n + 2, a + n + 1]
# a pentagon and a triangle
pts += [Gf.Vec3f(10, 0, 0), Gf.Vec3f(11, 0, 0), Gf.Vec3f(11.5, 1, 0), Gf.Vec3f(10.5, 2, 0), Gf.Vec3f(9.5, 1, 0)]
b = (n + 1) * (n + 1)
counts += [5, 3]
idx += [b, b + 1, b + 2, b + 3, b + 4, b, b + 2, b + 3]
m.CreatePointsAttr(pts)
m.CreateFaceVertexCountsAttr(counts)
m.CreateFaceVertexIndicesAttr(idx)
m.CreateHoleIndicesAttr([5])
pv = UsdGeom.PrimvarsAPI(m)
stp = pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
stp.Set([Gf.Vec2f(0, 0), Gf.Vec2f(1, 0), Gf.Vec2f(1, 1), Gf.Vec2f(0, 1)])
stp.SetIndices(Vt.IntArray([k % 4 for k in range(len(idx))]))
col = pv.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.uniform)
col.Set([Gf.Vec3f((k % 3) / 2, (k % 5) / 4, 1 - (k % 2)) for k in range(len(counts))])
op = pv.CreatePrimvar("displayOpacity", Sdf.ValueTypeNames.FloatArray, UsdGeom.Tokens.vertex)
op.Set([0.5 + 0.5 * (k % 2) for k in range(len(pts))])
uv2 = pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
uv2.Set([Gf.Vec2f(p[0] / 12, p[1] / 4) for p in pts])
m.CreateNormalsAttr([Gf.Vec3f(0, 0, 1)] * len(pts))
m.SetNormalsInterpolation(UsdGeom.Tokens.vertex)
m2 = cube(st, "/Grid/Left")
m2.CreateOrientationAttr(UsdGeom.Tokens.leftHanded)
UsdGeom.Xformable(m2).AddTranslateOp().Set(Gf.Vec3d(0, 0, 5))
m3 = cube(st, "/Grid/ConstColor", 2)
UsdGeom.Xformable(m3).AddTranslateOp().Set(Gf.Vec3d(0, 6, 0))
m3.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(0.2, 0.4, 0.8)])
names.append(("primvars.usda", st))
# 3. materials: textures, transforms, subsets, inherited bindings, interface inputs
st = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
root = UsdGeom.Xform.Define(st, "/Root")
st.SetDefaultPrim(root.GetPrim())
UsdGeom.Scope.Define(st, "/Root/Looks")
def surface(path, **inputs):
mat = UsdShade.Material.Define(st, path)
sh = UsdShade.Shader.Define(st, path + "/Surface")
sh.CreateIdAttr("UsdPreviewSurface")
for k, v in inputs.items():
if isinstance(v, tuple):
sh.CreateInput(k, Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*v))
else:
sh.CreateInput(k, Sdf.ValueTypeNames.Float).Set(v)
mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface")
return mat, sh
def texture(mat, sh, name, file, varname="st", wrap="repeat", transform=None, iface=False):
path = mat.GetPath().pathString
reader = UsdShade.Shader.Define(st, path + "/" + name + "_Reader")
reader.CreateIdAttr("UsdPrimvarReader_float2")
if iface:
mi = mat.CreateInput("frame:stPrimvarName", Sdf.ValueTypeNames.Token)
mi.Set(varname)
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).ConnectToSource(mi)
else:
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(varname)
src = reader.ConnectableAPI()
if transform:
tr = UsdShade.Shader.Define(st, path + "/" + name + "_Transform")
tr.CreateIdAttr("UsdTransform2d")
tr.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
tr.CreateInput("rotation", Sdf.ValueTypeNames.Float).Set(transform[0])
tr.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[1]))
tr.CreateInput("translation", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[2]))
src = tr.ConnectableAPI()
t = UsdShade.Shader.Define(st, path + "/" + name)
t.CreateIdAttr("UsdUVTexture")
t.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(file)
t.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
t.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set(wrap)
t.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp")
return t.ConnectableAPI()
red, _ = surface("/Root/Looks/Red", diffuseColor=(0.8, 0.1, 0.1), metallic=0.25, roughness=0.75)
glass, _ = surface("/Root/Looks/Glass", diffuseColor=(0.9, 0.9, 1.0), opacity=0.3, roughness=0.05, ior=1.33)
glow, _ = surface("/Root/Looks/Glow", emissiveColor=(1.0, 0.5, 0.0), opacityThreshold=0.4, opacity=0.9)
tex, tsh = surface("/Root/Looks/Textured", roughness=0.5)
c = texture(tex, tsh, "Diffuse", "./textures/checker.png", iface=True)
tsh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(c, "rgb")
mr = texture(tex, tsh, "MetalRough", "textures/mr.png", varname="uv2", wrap="mirror", transform=(30.0, (2, 2), (0.25, 0.5)))
tsh.CreateInput("metallic", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "b")
tsh.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "g")
nrm = texture(tex, tsh, "Normal", "textures/normal.png")
tsh.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(nrm, "rgb")
grp = UsdGeom.Xform.Define(st, "/Root/Group")
UsdShade.MaterialBindingAPI.Apply(grp.GetPrim()).Bind(red)
a = cube(st, "/Root/Group/Inherits")
b = cube(st, "/Root/Group/Own")
UsdGeom.Xformable(b).AddTranslateOp().Set(Gf.Vec3d(2, 0, 0))
UsdShade.MaterialBindingAPI.Apply(b.GetPrim()).Bind(glass)
s = cube(st, "/Root/Subsets", 1.0, quads=False)
UsdGeom.Xformable(s).AddTranslateOp().Set(Gf.Vec3d(0, 3, 0))
pv = UsdGeom.PrimvarsAPI(s)
pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 2), (k // 2) % 2) for k in range(8)])
pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 4) / 4, k / 8) for k in range(8)])
mb = UsdShade.MaterialBindingAPI.Apply(s.GetPrim())
mb.Bind(glow)
s1 = mb.CreateMaterialBindSubset("top", Vt.IntArray([0, 1, 2, 3]))
UsdShade.MaterialBindingAPI.Apply(s1.GetPrim()).Bind(tex)
s2 = mb.CreateMaterialBindSubset("side", Vt.IntArray([4, 5, 6]))
UsdShade.MaterialBindingAPI.Apply(s2.GetPrim()).Bind(red)
names.append(("materials.usda", st))
# 4. cameras and lights
st = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
root = UsdGeom.Xform.Define(st, "/Scene")
st.SetDefaultPrim(root.GetPrim())
cam = UsdGeom.Camera.Define(st, "/Scene/Persp")
cam.CreateFocalLengthAttr(35)
cam.CreateHorizontalApertureAttr(36)
cam.CreateVerticalApertureAttr(24)
cam.CreateClippingRangeAttr(Gf.Vec2f(0.1, 500))
UsdGeom.Xformable(cam).AddTranslateOp().Set(Gf.Vec3d(0, 1, 10))
o = UsdGeom.Camera.Define(st, "/Scene/Ortho")
o.CreateProjectionAttr(UsdGeom.Tokens.orthographic)
o.CreateHorizontalApertureAttr(40)
o.CreateVerticalApertureAttr(30)
UsdLux.DistantLight.Define(st, "/Scene/Sun").CreateIntensityAttr(3)
sp = UsdLux.SphereLight.Define(st, "/Scene/Bulb")
sp.CreateIntensityAttr(50)
sp.CreateColorAttr(Gf.Vec3f(1, 0.8, 0.6))
sp.CreateExposureAttr(2)
UsdGeom.Xformable(sp).AddTranslateOp().Set(Gf.Vec3d(0, 4, 0))
spot = UsdLux.SphereLight.Define(st, "/Scene/Spot")
sh = UsdLux.ShapingAPI.Apply(spot.GetPrim())
sh.CreateShapingConeAngleAttr(30)
sh.CreateShapingConeSoftnessAttr(0.5)
UsdLux.RectLight.Define(st, "/Scene/Panel").CreateIntensityAttr(7)
UsdLux.DiskLight.Define(st, "/Scene/Disk")
cube(st, "/Scene/Floor", 10)
names.append(("camlights.usda", st))
# 5. time samples
st = Usd.Stage.CreateInMemory()
st.SetTimeCodesPerSecond(30)
st.SetStartTimeCode(0)
st.SetEndTimeCode(60)
root = UsdGeom.Xform.Define(st, "/Anim")
st.SetDefaultPrim(root.GetPrim())
x = UsdGeom.Xform.Define(st, "/Anim/Mover")
t = x.AddTranslateOp()
for k, v in ((0, (0, 0, 0)), (30, (4, 1, 0)), (60, (4, 1, -6))):
t.Set(Gf.Vec3d(*v), k)
r = x.AddRotateXYZOp()
for k, v in ((0, (0, 0, 0)), (20, (0, 90, 0)), (45, (30, 180, 10))):
r.Set(Gf.Vec3f(*v), k)
s = x.AddScaleOp()
s.Set(Gf.Vec3f(1, 1, 1))
cube(st, "/Anim/Mover/Box")
y = UsdGeom.Xform.Define(st, "/Anim/Mover/Child")
q = y.AddOrientOp()
q.Set(Gf.Quatf(1, 0, 0, 0), 0)
q.Set(Gf.Quatf(0.7071068, 0.7071068, 0, 0), 60)
y.AddTranslateOp().Set(Gf.Vec3d(0, 2, 0))
cube(st, "/Anim/Mover/Child/Box", 0.5)
names.append(("anim.usda", st))
out = []
for name, st in names:
st.GetRootLayer().Export(os.path.join(d, name))
out.append(name)
os.makedirs(os.path.join(d, "textures"), exist_ok=True)
checker = []
for yy in range(8):
for xx in range(8):
v = 255 if (xx + yy) % 2 else 40
checker += [v, v, v, 255]
for f, data in (("checker.png", png(8, 8, checker)), ("mr.png", png(2, 2, [0, 128, 255, 255] * 4)), ("normal.png", png(2, 2, [128, 128, 255, 255] * 4))):
with open(os.path.join(d, "textures", f), "wb") as fh:
fh.write(data)
# a usdc (UNSUPPORTED) and a usdz package of the materials stage
Sdf.Layer.FindOrOpen(os.path.join(d, "xforms.usda")).Export(os.path.join(d, "xforms.usdc"))
out.append("xforms.usdc")
cwd = os.getcwd()
os.chdir(d)
UsdUtils.CreateNewUsdzPackage(Sdf.AssetPath("materials.usda"), "materials.usdz")
os.chdir(cwd)
out.append("materials.usdz")
return out
def mat16(m):
return [float(m[i][j]) for i in range(4) for j in range(4)]
def metrics(path):
stage = Usd.Stage.Open(path)
if stage is None:
return {"failed": True}
res = {
"upAxis": str(UsdGeom.GetStageUpAxis(stage)),
"metersPerUnit": float(UsdGeom.GetStageMetersPerUnit(stage)) if UsdGeom.StageHasAuthoredMetersPerUnit(stage) else -1.0,
"tcps": float(stage.GetTimeCodesPerSecond()),
"meshes": [], "xforms": [], "materials": [], "cameras": [], "lights": [], "anim": [],
}
t0 = Usd.TimeCode.EarliestTime()
cache = UsdGeom.XformCache(t0)
for prim in stage.Traverse():
if not prim.IsA(UsdGeom.Xformable):
continue
path_s = prim.GetPath().pathString
world = cache.GetLocalToWorldTransform(prim)
res["xforms"].append({"path": path_s, "type": str(prim.GetTypeName()), "world": mat16(world)})
x = UsdGeom.Xformable(prim)
times = x.GetTimeSamples()
if len(times) > 1:
samples = []
for t in times:
samples.append({"time": float(t), "world": mat16(x.ComputeLocalToWorldTransform(t))})
res["anim"].append({"path": path_s, "samples": samples})
if prim.IsA(UsdGeom.Mesh):
m = UsdGeom.Mesh(prim)
pts = m.GetPointsAttr().Get(t0) or []
counts = m.GetFaceVertexCountsAttr().Get(t0) or []
idx = m.GetFaceVertexIndicesAttr().Get(t0) or []
holes = set(m.GetHoleIndicesAttr().Get(t0) or [])
wp = [world.Transform(Gf.Vec3d(*p)) for p in pts]
tris, area, at = 0, 0.0, 0
lo, hi = [math.inf] * 3, [-math.inf] * 3
for f, c in enumerate(counts):
corners = list(idx[at:at + c])
at += c
if c < 3 or f in holes:
continue
for k in range(1, c - 1):
a, b, cc = wp[corners[0]], wp[corners[k]], wp[corners[k + 1]]
area += 0.5 * Gf.Cross(b - a, cc - a).GetLength()
tris += 1
for v in corners:
for j in range(3):
lo[j] = min(lo[j], wp[v][j])
hi[j] = max(hi[j], wp[v][j])
mat, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
subsets = UsdShade.MaterialBindingAPI(prim).GetMaterialBindSubsets()
res["meshes"].append({
"path": path_s, "triangles": tris, "area": area, "min": lo if tris else [], "max": hi if tris else [],
"material": mat.GetPath().pathString if mat else "", "subsets": len(subsets),
"subsetMaterials": sorted(
(UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0].GetPath().pathString if UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0] else "") for sub in subsets),
})
if prim.IsA(UsdGeom.Camera):
c = UsdGeom.Camera(prim)
cr = c.GetClippingRangeAttr().Get(t0)
res["cameras"].append({
"path": path_s, "projection": str(c.GetProjectionAttr().Get(t0)), "focal": float(c.GetFocalLengthAttr().Get(t0)),
"hap": float(c.GetHorizontalApertureAttr().Get(t0)), "vap": float(c.GetVerticalApertureAttr().Get(t0)),
"near": float(cr[0]), "far": float(cr[1]),
})
for lt in ("DistantLight", "SphereLight", "RectLight", "DiskLight"):
cls = getattr(UsdLux, lt)
if prim.IsA(cls):
l = cls(prim)
col = l.GetColorAttr().Get(t0)
cone = prim.GetAttribute("inputs:shaping:cone:angle")
res["lights"].append({
"path": path_s, "type": lt, "intensity": float(l.GetIntensityAttr().Get(t0)) * 2 ** float(l.GetExposureAttr().Get(t0)),
"color": [float(v) for v in col], "cone": float(cone.Get(t0)) if cone and cone.HasAuthoredValue() else -1.0,
})
for prim in stage.Traverse():
if not prim.IsA(UsdShade.Material):
continue
mat = UsdShade.Material(prim)
surf = mat.ComputeSurfaceSource()
sh = surf[0] if surf else None
if not sh or sh.GetIdAttr().Get() != "UsdPreviewSurface":
continue
d = {"path": prim.GetPath().pathString, "textures": {}}
for name in ("diffuseColor", "emissiveColor", "metallic", "roughness", "opacity", "opacityThreshold", "ior", "normal", "occlusion"):
inp = sh.GetInput(name)
if not inp:
continue
srcs = inp.GetConnectedSources()[0] if inp.HasConnectedSource() else []
if srcs:
src = UsdShade.Shader(srcs[0].source.GetPrim())
f = src.GetInput("file")
if f:
d["textures"][name] = {"file": f.Get().path, "output": str(srcs[0].sourceName)}
else:
v = inp.Get()
if v is not None:
d[name] = [float(x) for x in v] if hasattr(v, "__len__") else float(v)
res["materials"].append(d)
return res
mode = req["mode"]
if mode == "author":
print(json.dumps(author(req["dir"])))
elif mode == "metrics":
print(json.dumps([metrics(p) for p in req["paths"]]))
elif mode == "convert":
Sdf.Layer.FindOrOpen(req["src"]).Export(req["dst"])
print("[]")
elif mode == "specs":
out = []
for p in req["paths"]:
layer = Sdf.Layer.FindOrOpen(p)
n = [0]
def visit(path):
if path.IsPrimPath():
n[0] += 1
layer.Traverse(Sdf.Path.absoluteRootPath, visit)
out.append(n[0])
print(json.dumps(out))
+264
View File
@@ -0,0 +1,264 @@
# USDA fixtures (tools/fixtures.py): stages authored through OpenUSD's own API (pxr, nixpkgs python3Packages.openusd:
# every xform op kind / order, pivots, !resetXformStack!, primvar interpolations + indices, holes, leftHanded, n-gons,
# UsdPreviewSurface + UsdUVTexture / UsdTransform2d / interface inputs, GeomSubsets, inherited bindings, cameras,
# UsdLux lights, time samples; plus a .usdc and a .usdz), assimp's USD test models (models-nonbsd/USD: the .usda files
# and the .usdc ones converted to .usda by Sdf, read from the nixpkgs assimp source, not committed), Blender 5 USD
# exports of glTF sample models (when blender is on PATH), a hand-written file exercising the text grammar, and the
# OpenUSD schema layers (parse-only). Reference values come from pxr (Usd.Stage: world transforms, triangles / area /
# bounds per mesh, bound materials, cameras, lights, xform time samples).
# tests/gen/usda_cases.luau { name, data, files = { uri -> bytes }, ref = pxr metrics | nil, expect = "UNSUPPORTED"? }
# tests/gen/usda_specs.luau { name, data, prims = number of prim specs (Sdf) }
# tests/gen/usda_xcheck.luau our writer's .usda for every case (tools/fixtures/_usda_encode.luau) read back by pxr:
# { name, case, ref }
import json, os, shutil, subprocess, tempfile
INPUTS = ["src/Formats/model/usda", "tools/fixtures/_usda_reference.py", "tools/fixtures/_usda_encode.luau",
"tools/fixtures/_model_ref.py", "tests/fixtures/gltf"]
# the text grammar: comments, metadata of every kind, list ops, variants, class / over, dictionaries, strings,
# relative paths, typed values that the Scene ignores
HANDWRITTEN = r'''#usda 1.0
(
"""A layer written by hand: every construct of the text format the reader has to get through."""
customLayerData = {
string creator = "formats-luau tests"
dictionary nested = {
int[] numbers = [1, 2, 3]
double "quoted key" = 1.5
}
}
defaultPrim = "Hand"
metersPerUnit = 0.0254
upAxis = "Z"
timeCodesPerSecond = 24
)
# a class (abstract: not a node) and an over of nothing
class "_Template"
{
float3 xformOp:translate = (100, 100, 100)
}
def Xform "Hand" (
kind = "assembly"
doc = 'single quoted doc'
variants = {
string look = "big"
}
prepend variantSets = "look"
customData = { bool flag = true }
)
{
custom string notes = """multi
line""" // trailing comment
custom asset path = @@@[email protected]@@@
custom double[] empty = []
custom float big = inf
custom float small = -inf
custom token[] tokens = ["a", "b"]
custom rel others = [</Hand/Big>, <../Hand>]
reorder nameChildren = ["Big", "Tri"]
def Mesh "Tri" ( active = true )
{
point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] ; int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
double3 xformOp:translate = (1, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
rel material:binding = <../Looks/Blue>
}
variantSet "look" = {
"big" (doc = "selected") {
def Mesh "Big"
{
float3 xformOp:scale = (3, 3, 3)
uniform token[] xformOpOrder = ["xformOp:scale"]
point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
int[] faceVertexCounts = [4]
int[] faceVertexIndices = [0, 1, 2, 3]
color3f[] primvars:displayColor = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)] (
interpolation = "vertex"
)
}
}
"small" {
def Mesh "Small"
{
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
}
}
}
def Scope "Looks"
{
def Material "Blue"
{
color3f inputs:tint = (0.1, 0.2, 0.9)
token outputs:surface.connect = <Surface.outputs:surface>
def Shader "Surface"
{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor.connect = </Hand/Looks/Blue.inputs:tint>
float inputs:roughness = 0.25
token outputs:surface
}
}
}
def "Untyped"
{
def Xform "Inner" (
prepend references = @missing.usda@</Thing>
)
{
matrix4d xformOp:transform.timeSamples = {
0: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ),
10: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 5, 1) ),
}
uniform token[] xformOpOrder = ["xformOp:transform"]
def Mesh "Quad"
{
point3f[] points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)]
int[] faceVertexCounts = [4]
int[] faceVertexIndices = [0, 1, 2, 3]
}
}
}
}
over "Elsewhere"
{
def Xform "Undefined"
{
double3 xformOp:translate = (0, 0, -1)
uniform token[] xformOpOrder = ["xformOp:translate"]
}
}
'''
GLTF_MODELS = [("Box", "glTF", "Box.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"),
("Cameras", "glTF", "Cameras.gltf"), ("MultiUVTest", "glTF-Binary", None), ("BoxVertexColors", "glTF-Binary", None)]
BLENDER = r'''
import bpy, sys
args = sys.argv[sys.argv.index("--") + 1:]
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=args[0])
bpy.ops.wm.usd_export(filepath=args[1], export_materials=True, export_animation=True, relative_paths=True)
'''
def pxr(ctx, req):
code = ctx.read("tools/fixtures/_usda_reference.py").decode()
try:
return json.loads(ctx.python(["openusd"], code, input=json.dumps(req).encode()))
except subprocess.CalledProcessError as e:
raise RuntimeError("pxr (%s) failed:\n%s" % (req["mode"], e.stderr.decode(errors="replace")[-3000:])) from None
def files_under(d, skip):
out = {}
for root, _, fs in os.walk(d):
for f in fs:
p = os.path.join(root, f)
rel = os.path.relpath(p, d).replace(os.sep, "/")
if rel != skip and not rel.endswith((".usda", ".usdc", ".usdz", ".usd", ".py")):
out[rel] = open(p, "rb").read()
return out
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="formats-usda-")
cases = [] # name, path, files, expect?
# 1. stages authored through pxr
adir = os.path.join(tmp, "authored")
os.makedirs(adir)
for name in pxr(ctx, {"mode": "author", "dir": adir}):
p = os.path.join(adir, name)
c = {"name": "pxr/" + name, "path": p, "files": files_under(adir, name)}
if name.endswith(".usdc"):
c["expect"] = "UNSUPPORTED"
if name.endswith(".usdz"):
c["files"] = {}
c["like"] = "pxr/materials.usda"
cases.append(c)
# 2. hand-written grammar test
hand = os.path.join(tmp, "hand.usda")
with open(hand, "w") as f:
f.write(HANDWRITTEN)
cases.append({"name": "hand.usda", "path": hand, "files": {}})
# 3. assimp's USD test models (untrusted data: read only, from the nix store)
src = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip()
usd = os.path.join(src, "test", "models-nonbsd", "USD")
conv = os.path.join(tmp, "assimp")
os.makedirs(conv)
for f in sorted(os.listdir(os.path.join(usd, "usda"))):
if f.endswith(".usda"):
cases.append({"name": "assimp/" + f, "path": os.path.join(usd, "usda", f), "files": files_under(os.path.join(usd, "usda"), f)})
for d, f in [(os.path.join(usd, "usdc"), x) for x in sorted(os.listdir(os.path.join(usd, "usdc"))) if x.endswith(".usdc")] + [(os.path.join(src, "test", "models", "USD"), "MotionCaptureROM.usdc")]:
dst = os.path.join(conv, f[:-5] + ".usda")
pxr(ctx, {"mode": "convert", "src": os.path.join(d, f), "dst": dst})
cases.append({"name": "assimp/" + f + " (usdcat)", "path": dst, "files": files_under(d, f)})
# 4. Blender USD exports of glTF samples
if shutil.which("blender"):
bdir = os.path.join(tmp, "blender")
os.makedirs(bdir)
script = os.path.join(tmp, "blender_export.py")
with open(script, "w") as f:
f.write(BLENDER)
groot = os.path.join(ctx.root, "tests", "fixtures", "gltf")
for model, variant, main in GLTF_MODELS:
d = os.path.join(groot, model, variant)
if not os.path.isdir(d):
continue
main = main or [x for x in sorted(os.listdir(d)) if x.endswith((".gltf", ".glb"))][0]
out = os.path.join(bdir, model, model + ".usda")
os.makedirs(os.path.dirname(out), exist_ok=True)
r = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", os.path.join(d, main), out], capture_output=True)
if r.returncode == 0 and os.path.exists(out):
cases.append({"name": "blender/" + model, "path": out, "files": files_under(os.path.dirname(out), model + ".usda")})
refs = pxr(ctx, {"mode": "metrics", "paths": [c["path"] for c in cases if "expect" not in c]})
k = 0
for c in cases:
if "expect" not in c:
c["ref"] = refs[k]
k += 1
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("usda_cases", cases)
# 5. parse-only: OpenUSD's schema layers
usdpkg = ctx.python(["openusd"], "import pxr, os; print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(pxr.__file__)))))))").decode().strip()
specs = []
for root, _, fs in os.walk(usdpkg):
for f in fs:
if f.endswith(".usda") and ("usdGeom" in root or "usdShade" in root or "usdLux" in root or "usdSkel" in root):
specs.append(os.path.join(root, f))
specs = sorted(specs)[:8]
counts = pxr(ctx, {"mode": "specs", "paths": specs})
ctx.emit("usda_specs", [{"name": os.path.relpath(p, usdpkg), "data": open(p, "rb").read(), "prims": n} for p, n in zip(specs, counts)])
# 6. pxr reads our writer's output
exe = shutil.which("luau")
cmd = [exe, "tools/fixtures/_usda_encode.luau"] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_usda_encode.luau"]
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
xdir = os.path.join(tmp, "ours")
os.makedirs(xdir)
mains = []
for line in res.stdout.decode().split("\n"):
if "\t" in line:
name, hexdata = line.split("\t", 1)
p = os.path.join(xdir, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(bytes.fromhex(hexdata.strip()))
if name.endswith(".usda") and "/" not in name:
mains.append(name)
xrefs = pxr(ctx, {"mode": "metrics", "paths": [os.path.join(xdir, n) for n in mains]})
ctx.emit("usda_xcheck", [{"name": n, "case": int(n[5:].split(".")[0]), "ref": r} for n, r in zip(mains, xrefs)])
shutil.rmtree(tmp, ignore_errors=True)