use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget, TrackValues};
use crate::core::{BufferGeometry, ObjectArena, ObjectId, ObjectKind};
use crate::materials::Material;
use crate::textures::{Texture, TextureFormat, TextureWrap};
use super::parse::{Specifier, UsdLayer, UsdPrim, UsdProperty};
use super::value::UsdValue;
use super::write::layer_to_usda;
#[derive(Debug, Clone)]
pub struct UsdExportOptions {
pub meters_per_unit: f32,
pub up_axis: char,
pub default_prim: String,
pub time_codes_per_second: f32,
}
impl Default for UsdExportOptions {
fn default() -> Self {
Self {
meters_per_unit: 1.0,
up_axis: 'Y',
default_prim: "Root".into(),
time_codes_per_second: 24.0,
}
}
}
fn float_array(values: &[f32], stride: usize) -> UsdValue {
UsdValue::Array(
values
.chunks_exact(stride)
.map(|c| UsdValue::Tuple(c.iter().map(|v| UsdValue::Float(*v as f64)).collect()))
.collect(),
)
}
fn int_array(values: impl Iterator<Item = u32>) -> UsdValue {
UsdValue::Array(values.map(|v| UsdValue::Int(v as i128)).collect())
}
fn uniform(mut p: UsdProperty) -> UsdProperty {
p.uniform = true;
p
}
fn attribute(type_name: &str, name: &str, value: UsdValue) -> UsdProperty {
UsdProperty {
qualifier: String::new(),
name: name.into(),
type_name: type_name.into(),
uniform: false,
relationship: false,
value,
metadata: Vec::new(),
}
}
fn interpolated(mut p: UsdProperty, how: &str) -> UsdProperty {
p.metadata
.push(("interpolation".into(), UsdValue::Token(how.into())));
p
}
pub fn mesh_prim(g: &BufferGeometry, name: &str) -> UsdPrim {
let positions = g
.get_attribute("position")
.map(|a| a.array.clone())
.unwrap_or_default();
let vertices = positions.len() / 3;
let indices: Vec<u32> = match &g.index {
Some(i) => i.to_vec(),
None => (0..vertices as u32).collect(),
};
let triangles = indices.len() / 3;
let mut face_counts: Vec<u32> = Vec::with_capacity(triangles);
let mut face_indices: Vec<u32> = Vec::with_capacity(triangles * 3);
for corners in g.faces() {
face_counts.push(corners.len() as u32);
face_indices.extend_from_slice(&corners);
}
let mut properties = vec![
attribute("point3f[]", "points", float_array(&positions, 3)),
attribute(
"int[]",
"faceVertexCounts",
int_array(face_counts.into_iter()),
),
attribute(
"int[]",
"faceVertexIndices",
int_array(face_indices.into_iter()),
),
];
if vertices > 0 {
let mut lo = [f32::INFINITY; 3];
let mut hi = [f32::NEG_INFINITY; 3];
for p in positions.chunks_exact(3) {
for a in 0..3 {
lo[a] = lo[a].min(p[a]);
hi[a] = hi[a].max(p[a]);
}
}
properties.push(attribute(
"float3[]",
"extent",
UsdValue::Array(vec![
UsdValue::Tuple(lo.iter().map(|v| UsdValue::Float(*v as f64)).collect()),
UsdValue::Tuple(hi.iter().map(|v| UsdValue::Float(*v as f64)).collect()),
]),
));
}
if let Some(n) = g.get_attribute("normal") {
properties.push(interpolated(
attribute("normal3f[]", "normals", float_array(&n.array, 3)),
"vertex",
));
}
if let Some(c) = g.get_attribute("color") {
properties.push(interpolated(
attribute("color3f[]", "primvars:displayColor", float_array(&c.array, 3)),
"vertex",
));
}
if let Some(uv) = g.get_attribute("uv") {
properties.push(interpolated(
attribute("texCoord2f[]", "primvars:st", float_array(&uv.array, 2)),
"vertex",
));
}
properties.push(UsdProperty {
qualifier: String::new(),
name: "subdivisionScheme".into(),
type_name: "token".into(),
uniform: true,
relationship: false,
value: UsdValue::Token("none".into()),
metadata: Vec::new(),
});
UsdPrim {
specifier: Specifier::Def,
type_name: "Mesh".into(),
name: sanitize(name),
metadata: Vec::new(),
properties,
children: Vec::new(),
variant_sets: Vec::new(),
}
}
#[derive(Debug, Clone)]
pub struct ExportedTexture {
pub path: String,
pub data: Vec<u8>,
}
fn rgba8(texture: &Texture) -> Option<Vec<u8>> {
let count = (texture.width as usize).checked_mul(texture.height as usize)?;
if count == 0 || texture.data.is_empty() {
return None;
}
let pixels = unflipped(texture, count)?;
if texture.flip_y {
return Some(pixels);
}
let stride = texture.width as usize * 4;
Some(
pixels
.chunks_exact(stride)
.rev()
.flatten()
.copied()
.collect(),
)
}
fn unflipped(texture: &Texture, count: usize) -> Option<Vec<u8>> {
match texture.format {
TextureFormat::Rgba8UnormSrgb | TextureFormat::Rgba8Unorm => {
texture.data.get(..count * 4).map(<[u8]>::to_vec)
}
TextureFormat::R8Unorm => texture
.data
.get(..count)
.map(|d| d.iter().flat_map(|v| [*v, *v, *v, 255]).collect()),
TextureFormat::Rgba16Float => texture.data.get(..count * 8).map(|d| {
d.chunks_exact(2)
.map(|h| {
let bits = u16::from_le_bytes([h[0], h[1]]);
let value = half_bits_to_f32(bits);
(value.clamp(0.0, 1.0) * 255.0).round() as u8
})
.collect()
}),
_ => None,
}
}
fn half_bits_to_f32(bits: u16) -> f32 {
let sign = ((bits >> 15) & 1) as u32;
let exponent = ((bits >> 10) & 0x1f) as u32;
let mantissa = (bits & 0x3ff) as u32;
let assembled = match exponent {
0 if mantissa == 0 => sign << 31,
0 => {
let mut e = -1i32;
let mut m = mantissa;
while m & 0x400 == 0 {
m <<= 1;
e -= 1;
}
(sign << 31) | (((127 - 15 + e + 1) as u32) << 23) | ((m & 0x3ff) << 13)
}
0x1f => (sign << 31) | (0xff << 23) | (mantissa << 13),
_ => (sign << 31) | ((exponent + 127 - 15) << 23) | (mantissa << 13),
};
f32::from_bits(assembled)
}
fn wrap_name(wrap: TextureWrap) -> &'static str {
match wrap {
TextureWrap::Repeat => "repeat",
TextureWrap::ClampToEdge => "clamp",
TextureWrap::MirroredRepeat => "mirror",
}
}
struct Slot<'a> {
name: &'static str,
input: &'static str,
type_name: &'static str,
channel: &'static str,
color_space: &'static str,
scale: [f32; 4],
bias: [f32; 4],
texture: &'a Texture,
}
fn slot<'a>(
name: &'static str,
input: &'static str,
type_name: &'static str,
channel: &'static str,
color_space: &'static str,
texture: &'a Texture,
) -> Slot<'a> {
Slot {
name,
input,
type_name,
channel,
color_space,
scale: [1.0; 4],
bias: [0.0; 4],
texture,
}
}
fn texture_slots(material: &Material) -> Vec<Slot<'_>> {
let mut out = Vec::new();
macro_rules! push {
($opt:expr, $name:literal, $input:literal, $ty:literal, $ch:literal, $cs:literal) => {
if let Some(t) = $opt.as_deref() {
out.push(slot($name, $input, $ty, $ch, $cs, t));
}
};
}
match material {
Material::Standard(m) => {
push!(m.map, "DiffuseTex", "inputs:diffuseColor", "color3f", "rgb", "sRGB");
push!(m.emissive_map, "EmissiveTex", "inputs:emissiveColor", "color3f", "rgb", "sRGB");
push!(m.roughness_map, "RoughnessTex", "inputs:roughness", "float", "r", "raw");
push!(m.metalness_map, "MetallicTex", "inputs:metallic", "float", "r", "raw");
push!(m.ao_map, "OcclusionTex", "inputs:occlusion", "float", "r", "raw");
push!(m.displacement_map, "DisplacementTex", "inputs:displacement", "float", "r", "raw");
if let Some(t) = m.normal_map.as_deref() {
out.push(normal_slot(t));
}
}
Material::Physical(m) => {
push!(m.map, "DiffuseTex", "inputs:diffuseColor", "color3f", "rgb", "sRGB");
push!(m.emissive_map, "EmissiveTex", "inputs:emissiveColor", "color3f", "rgb", "sRGB");
push!(m.roughness_map, "RoughnessTex", "inputs:roughness", "float", "r", "raw");
push!(m.metalness_map, "MetallicTex", "inputs:metallic", "float", "r", "raw");
push!(m.ao_map, "OcclusionTex", "inputs:occlusion", "float", "r", "raw");
push!(m.displacement_map, "DisplacementTex", "inputs:displacement", "float", "r", "raw");
if let Some(t) = m.normal_map.as_deref() {
out.push(normal_slot(t));
}
}
Material::Basic(m) => {
push!(m.map, "DiffuseTex", "inputs:diffuseColor", "color3f", "rgb", "sRGB")
}
Material::Sprite(m) => {
push!(m.map, "DiffuseTex", "inputs:diffuseColor", "color3f", "rgb", "sRGB")
}
_ => {}
}
out
}
fn normal_slot(texture: &Texture) -> Slot<'_> {
Slot {
scale: [2.0, 2.0, 2.0, 1.0],
bias: [-1.0, -1.0, -1.0, 0.0],
..slot("NormalTex", "inputs:normal", "normal3f", "rgb", "raw", texture)
}
}
fn tuple2(v: [f32; 2]) -> UsdValue {
UsdValue::Tuple(v.iter().map(|c| UsdValue::Float(*c as f64)).collect())
}
fn token(name: &str, value: &str) -> UsdProperty {
let mut p = attribute("token", name, UsdValue::Token(value.into()));
p.uniform = true;
p
}
fn shader(name: &str, id: &str, mut properties: Vec<UsdProperty>) -> UsdPrim {
properties.insert(0, token("info:id", id));
UsdPrim {
specifier: Specifier::Def,
type_name: "Shader".into(),
name: name.into(),
metadata: Vec::new(),
properties,
children: Vec::new(),
variant_sets: Vec::new(),
}
}
fn connect(type_name: &str, name: &str, target: String) -> UsdProperty {
attribute(type_name, name, UsdValue::Path(target))
}
struct Preview {
color: [f32; 3],
roughness: f32,
metallic: f32,
emissive: [f32; 3],
opacity: f32,
specular: Option<[f32; 3]>,
ior: Option<f32>,
clearcoat: Option<(f32, f32)>,
opacity_threshold: f32,
}
fn roughness_from_shininess(shininess: f32) -> f32 {
(2.0 / (shininess.max(0.0) + 2.0)).sqrt().clamp(0.0, 1.0)
}
fn preview_surface(material: &Material) -> Preview {
let rgb = |c: &crate::math::Color| [c.r, c.g, c.b];
let plain = |color: [f32; 3], opacity: f32| Preview {
color,
roughness: 1.0,
metallic: 0.0,
emissive: [0.0; 3],
opacity,
specular: None,
ior: None,
clearcoat: None,
opacity_threshold: 0.0,
};
match material {
Material::Standard(s) => Preview {
color: rgb(&s.color),
roughness: s.roughness,
metallic: s.metalness,
emissive: rgb(&s.emissive),
opacity: s.opacity,
specular: None,
ior: None,
clearcoat: None,
opacity_threshold: 0.0,
},
Material::Physical(p) => Preview {
color: rgb(&p.color),
roughness: p.roughness,
metallic: p.metalness,
emissive: rgb(&p.emissive),
opacity: p.opacity,
specular: None,
ior: Some(p.ior),
clearcoat: (p.clearcoat > 0.0).then_some((p.clearcoat, p.clearcoat_roughness)),
opacity_threshold: 0.0,
},
Material::Basic(b) => Preview {
opacity_threshold: b.alpha_test,
..plain(rgb(&b.color), b.opacity)
},
Material::Lambert(l) => Preview {
emissive: rgb(&l.emissive),
..plain(rgb(&l.color), l.opacity)
},
Material::Phong(p) => Preview {
roughness: roughness_from_shininess(p.shininess),
emissive: rgb(&p.emissive),
specular: Some(rgb(&p.specular)),
..plain(rgb(&p.color), p.opacity)
},
Material::Toon(t) => Preview {
emissive: rgb(&t.emissive),
..plain(rgb(&t.color), t.opacity)
},
Material::Matcap(m) => plain(rgb(&m.color), m.opacity),
Material::Sprite(s) => plain(rgb(&s.color), s.opacity),
Material::Points(p) => plain(rgb(&p.color), p.opacity),
Material::Line(l) => plain(rgb(&l.color), l.opacity),
Material::Mirror(m) => Preview {
roughness: 0.0,
metallic: 1.0,
..plain(rgb(&m.color), 1.0)
},
Material::Atmosphere(a) => plain(rgb(&a.color), 1.0),
Material::Normal(n) => plain([0.8; 3], n.opacity),
Material::Depth(d) => plain([0.8; 3], d.opacity),
Material::Distance(_) | Material::Sky(_) | Material::Shader(_) => plain([0.8; 3], 1.0),
}
}
pub fn material_prim_with_textures(
material: &Material,
name: &str,
root: &str,
) -> (UsdPrim, Vec<ExportedTexture>) {
let mut prim = material_prim(material, name);
let slots = texture_slots(material);
if slots.is_empty() {
return (prim, Vec::new());
}
let path = format!("{root}/{}", sanitize(name));
let mut images = Vec::new();
let mut nodes = Vec::new();
let mut reader_used = false;
for slot in slots {
let Some(pixels) = rgba8(slot.texture) else {
continue;
};
let file = format!("textures/{}_{}.png", sanitize(name), slot.name);
images.push(ExportedTexture {
path: file.clone(),
data: crate::utils::png::encode_png(slot.texture.width, slot.texture.height, &pixels),
});
let transform_needed = slot.texture.offset.x != 0.0
|| slot.texture.offset.y != 0.0
|| slot.texture.repeat.x != 1.0
|| slot.texture.repeat.y != 1.0
|| slot.texture.rotation != 0.0;
let st_source = if transform_needed {
let node = format!("{}Transform", slot.name);
nodes.push(shader(
&node,
"UsdTransform2d",
vec![
connect("float2", "inputs:in", format!("{path}/stReader.outputs:result")),
attribute(
"float2",
"inputs:scale",
tuple2([slot.texture.repeat.x, slot.texture.repeat.y]),
),
attribute(
"float2",
"inputs:translation",
tuple2([slot.texture.offset.x, slot.texture.offset.y]),
),
attribute(
"float",
"inputs:rotation",
UsdValue::Float(slot.texture.rotation.to_degrees() as f64),
),
attribute("float2", "outputs:result", UsdValue::None),
],
));
format!("{path}/{node}.outputs:result")
} else {
format!("{path}/stReader.outputs:result")
};
reader_used = true;
let mut properties = vec![
attribute("asset", "inputs:file", UsdValue::Asset(file)),
connect("float2", "inputs:st", st_source),
token("inputs:wrapS", wrap_name(slot.texture.wrap_s)),
token("inputs:wrapT", wrap_name(slot.texture.wrap_t)),
token("inputs:sourceColorSpace", slot.color_space),
];
if slot.scale != [1.0; 4] || slot.bias != [0.0; 4] {
properties.push(attribute("float4", "inputs:scale", tuple4(slot.scale)));
properties.push(attribute("float4", "inputs:bias", tuple4(slot.bias)));
}
let out_type = if slot.channel == "rgb" { "float3" } else { "float" };
properties.push(attribute(
out_type,
&format!("outputs:{}", slot.channel),
UsdValue::None,
));
nodes.push(shader(slot.name, "UsdUVTexture", properties));
let surface = &mut prim.children[0].properties;
surface.retain(|p| p.name != slot.input);
surface.push(connect(
slot.type_name,
slot.input,
format!("{path}/{}.outputs:{}", slot.name, slot.channel),
));
}
if reader_used {
nodes.insert(
0,
shader(
"stReader",
"UsdPrimvarReader_float2",
vec![
attribute("string", "inputs:varname", UsdValue::String("st".into())),
attribute("float2", "outputs:result", UsdValue::None),
],
),
);
}
prim.children.extend(nodes);
(prim, images)
}
pub fn material_prim(material: &Material, name: &str) -> UsdPrim {
let Preview {
color,
roughness,
metallic,
emissive,
opacity,
specular,
ior,
clearcoat,
opacity_threshold,
} = preview_surface(material);
let name = sanitize(name);
let shader = UsdPrim {
specifier: Specifier::Def,
type_name: "Shader".into(),
name: "Surface".into(),
metadata: Vec::new(),
properties: vec![
UsdProperty {
qualifier: String::new(),
name: "info:id".into(),
type_name: "token".into(),
uniform: true,
relationship: false,
value: UsdValue::Token("UsdPreviewSurface".into()),
metadata: Vec::new(),
},
attribute("color3f", "inputs:diffuseColor", tuple3(color)),
attribute("color3f", "inputs:emissiveColor", tuple3(emissive)),
attribute("float", "inputs:metallic", UsdValue::Float(metallic as f64)),
attribute("float", "inputs:roughness", UsdValue::Float(roughness as f64)),
attribute("float", "inputs:opacity", UsdValue::Float(opacity as f64)),
attribute(
"token",
"outputs:surface",
UsdValue::None,
),
]
.into_iter()
.chain(specular.into_iter().flat_map(|s| {
[
attribute("int", "inputs:useSpecularWorkflow", UsdValue::Int(1)),
attribute("color3f", "inputs:specularColor", tuple3(s)),
]
}))
.chain(
ior.into_iter()
.map(|v| attribute("float", "inputs:ior", UsdValue::Float(v as f64))),
)
.chain((opacity_threshold > 0.0).then(|| {
attribute(
"float",
"inputs:opacityThreshold",
UsdValue::Float(opacity_threshold as f64),
)
}))
.chain(clearcoat.into_iter().flat_map(|(amount, rough)| {
[
attribute("float", "inputs:clearcoat", UsdValue::Float(amount as f64)),
attribute(
"float",
"inputs:clearcoatRoughness",
UsdValue::Float(rough as f64),
),
]
}))
.collect(),
children: Vec::new(),
variant_sets: Vec::new(),
};
UsdPrim {
specifier: Specifier::Def,
type_name: "Material".into(),
name: name.clone(),
metadata: Vec::new(),
properties: vec![UsdProperty {
qualifier: String::new(),
name: "outputs:surface".into(),
type_name: "token".into(),
uniform: false,
relationship: false,
value: UsdValue::Path(format!("/Root/{name}/Surface.outputs:surface")),
metadata: Vec::new(),
}],
children: vec![shader],
variant_sets: Vec::new(),
}
}
fn tuple4(v: [f32; 4]) -> UsdValue {
UsdValue::Tuple(v.iter().map(|n| UsdValue::Float(*n as f64)).collect())
}
fn tuple3(v: [f32; 3]) -> UsdValue {
UsdValue::Tuple(v.iter().map(|c| UsdValue::Float(*c as f64)).collect())
}
fn face_first_triangles(g: &BufferGeometry) -> Vec<usize> {
let grouped = g.polygon_counts().is_some();
let mut out = Vec::new();
for range in g.polygon_ranges() {
if grouped && range.len() > 1 && g.polygon_loop(range.clone()).is_some() {
out.push(range.start);
} else {
out.extend(range);
}
}
out
}
pub fn sanitize(name: &str) -> String {
let mut out = String::new();
for (i, c) in name.chars().enumerate() {
let ok = c.is_ascii_alphanumeric() || c == '_';
let leading_digit = i == 0 && c.is_ascii_digit();
out.push(if ok && !leading_digit { c } else { '_' });
}
if out.is_empty() {
out.push_str("Prim");
}
out
}
pub fn geometry_to_layer(g: &BufferGeometry, name: &str, options: &UsdExportOptions) -> UsdLayer {
let root = UsdPrim {
specifier: Specifier::Def,
type_name: "Xform".into(),
name: sanitize(&options.default_prim),
metadata: Vec::new(),
properties: Vec::new(),
children: vec![mesh_prim(g, name)],
variant_sets: Vec::new(),
};
UsdLayer {
metadata: vec![
(
"defaultPrim".into(),
UsdValue::String(sanitize(&options.default_prim)),
),
(
"metersPerUnit".into(),
UsdValue::Float(options.meters_per_unit as f64),
),
("upAxis".into(), UsdValue::String(options.up_axis.to_string())),
],
prims: vec![root],
}
}
pub fn geometry_to_usda(g: &BufferGeometry, name: &str) -> String {
layer_to_usda(&geometry_to_layer(g, name, &UsdExportOptions::default()))
}
pub fn scene_to_layer(
arena: &ObjectArena,
roots: &[ObjectId],
options: &UsdExportOptions,
) -> UsdLayer {
scene_to_layer_placed(arena, roots, options, &mut Vec::new()).0
}
pub fn scene_to_layer_with_textures(
arena: &ObjectArena,
roots: &[ObjectId],
options: &UsdExportOptions,
) -> (UsdLayer, Vec<ExportedTexture>) {
scene_to_layer_placed(arena, roots, options, &mut Vec::new())
}
#[derive(Default)]
struct Materials {
prims: Vec<UsdPrim>,
textures: Vec<ExportedTexture>,
skel: Vec<UsdPrim>,
}
fn scene_to_layer_placed(
arena: &ObjectArena,
roots: &[ObjectId],
options: &UsdExportOptions,
placed: &mut Vec<(ObjectId, String)>,
) -> (UsdLayer, Vec<ExportedTexture>) {
let root_path = format!("/{}", sanitize(&options.default_prim));
let mut materials = Materials::default();
let mut children: Vec<UsdPrim> = Vec::new();
for (i, root) in roots.iter().enumerate() {
if let Some(prim) = object_prim_at(arena, *root, i, &mut materials, &root_path, placed) {
children.push(prim);
}
}
let textures = std::mem::take(&mut materials.textures);
children.extend(materials.prims);
let root_type = if materials.skel.is_empty() { "Xform" } else { "SkelRoot" };
children.extend(materials.skel);
let root = UsdPrim {
specifier: Specifier::Def,
type_name: root_type.into(),
name: sanitize(&options.default_prim),
metadata: Vec::new(),
properties: Vec::new(),
children,
variant_sets: Vec::new(),
};
let layer = UsdLayer {
metadata: vec![
(
"defaultPrim".into(),
UsdValue::String(sanitize(&options.default_prim)),
),
(
"metersPerUnit".into(),
UsdValue::Float(options.meters_per_unit as f64),
),
("upAxis".into(), UsdValue::String(options.up_axis.to_string())),
],
prims: vec![root],
};
(layer, textures)
}
pub fn scene_to_usda(arena: &ObjectArena, roots: &[ObjectId]) -> String {
layer_to_usda(&scene_to_layer(arena, roots, &UsdExportOptions::default()))
}
fn relationship(name: &str, value: UsdValue) -> UsdProperty {
UsdProperty {
qualifier: String::new(),
name: name.into(),
type_name: String::new(),
uniform: false,
relationship: true,
value,
metadata: Vec::new(),
}
}
fn add_blend_shapes(
mesh: &crate::core::Mesh,
prim: &mut UsdPrim,
mesh_path: &str,
root: &str,
skel: &mut Vec<UsdPrim>,
) {
use crate::core::BufferAttribute;
let g = &mesh.geometry;
let Some(base) = g.get_attribute("position") else {
return;
};
let Some(targets) = g.morph_attributes.get("position").filter(|t| !t.is_empty()) else {
return;
};
let vertices = base.count();
let normal_targets = g.morph_attributes.get("normal").filter(|t| !t.is_empty());
let base_normal = g.get_attribute("normal");
let read = |a: &BufferAttribute, v: usize, k: usize| -> f32 {
if k >= a.item_size {
return 0.0;
}
a.array.get(v * a.item_size + k).copied().unwrap_or(0.0)
};
let offsets = |target: &BufferAttribute, base: Option<&BufferAttribute>| -> Vec<f32> {
let mut out = Vec::with_capacity(vertices * 3);
for v in 0..vertices {
for k in 0..3 {
let from = match (g.morph_targets_relative, base) {
(false, Some(b)) => read(b, v, k),
_ => 0.0,
};
out.push(read(target, v, k) - from);
}
}
out
};
let mut names: Vec<String> = Vec::new();
let mut paths: Vec<UsdValue> = Vec::new();
let mut prim_names: Vec<String> = Vec::new();
for (t, target) in targets.iter().enumerate() {
let mut name = g
.morph_target_names
.get(t)
.filter(|n| !n.is_empty())
.cloned()
.unwrap_or_else(|| format!("target_{t}"));
if names.contains(&name) {
name = format!("{name}_{t}");
}
let mut shape_name = sanitize(&name);
if prim_names.contains(&shape_name) || prim.children.iter().any(|c| c.name == shape_name) {
shape_name = format!("{shape_name}_{t}");
}
let position = offsets(target, Some(base));
let normal = normal_targets
.and_then(|n| n.get(t))
.map(|n| offsets(n, base_normal));
let touched: Vec<u32> = (0..vertices)
.filter(|&v| {
let moved = |d: &[f32]| d[v * 3..v * 3 + 3].iter().any(|x| *x != 0.0);
moved(&position) || normal.as_deref().is_some_and(moved)
})
.map(|v| v as u32)
.collect();
let sparse = !touched.is_empty() && touched.len() < vertices;
let pick = |d: &[f32]| -> Vec<f32> {
if sparse {
touched
.iter()
.flat_map(|&v| d[v as usize * 3..v as usize * 3 + 3].to_vec())
.collect()
} else {
d.to_vec()
}
};
let mut properties = vec![uniform(attribute(
"vector3f[]",
"offsets",
float_array(&pick(&position), 3),
))];
if let Some(n) = &normal {
properties.push(uniform(attribute(
"vector3f[]",
"normalOffsets",
float_array(&pick(n), 3),
)));
}
if sparse {
properties.push(uniform(attribute(
"int[]",
"pointIndices",
int_array(touched.into_iter()),
)));
}
prim.children.push(UsdPrim {
specifier: Specifier::Def,
type_name: "BlendShape".into(),
name: shape_name.clone(),
metadata: Vec::new(),
properties,
children: Vec::new(),
variant_sets: Vec::new(),
});
paths.push(UsdValue::Path(format!("{mesh_path}/{shape_name}")));
prim_names.push(shape_name);
names.push(name);
}
let tokens = || UsdValue::Array(names.iter().map(|n| UsdValue::Token(n.clone())).collect());
let k = skel.len() / 2;
let skeleton_path = format!("{root}/MorphSkel_{k}");
let animation_path = format!("{root}/MorphAnim_{k}");
prim.properties
.push(uniform(attribute("token[]", "skel:blendShapes", tokens())));
prim.properties
.push(relationship("skel:blendShapeTargets", UsdValue::Array(paths)));
prim.properties
.push(relationship("skel:skeleton", UsdValue::Path(skeleton_path)));
match prim
.metadata
.iter_mut()
.find(|(key, _)| key == "prepend apiSchemas")
{
Some((_, UsdValue::Array(schemas))) => {
schemas.push(UsdValue::Token("SkelBindingAPI".into()))
}
_ => prim.metadata.push((
"prepend apiSchemas".into(),
UsdValue::Array(vec![UsdValue::Token("SkelBindingAPI".into())]),
)),
}
let mut weights = mesh.morph_influences.clone();
weights.resize(names.len(), 0.0);
skel.push(UsdPrim {
specifier: Specifier::Def,
type_name: "Skeleton".into(),
name: format!("MorphSkel_{k}"),
metadata: vec![(
"prepend apiSchemas".into(),
UsdValue::Array(vec![UsdValue::Token("SkelBindingAPI".into())]),
)],
properties: vec![relationship(
"skel:animationSource",
UsdValue::Path(animation_path),
)],
children: Vec::new(),
variant_sets: Vec::new(),
});
skel.push(UsdPrim {
specifier: Specifier::Def,
type_name: "SkelAnimation".into(),
name: format!("MorphAnim_{k}"),
metadata: Vec::new(),
properties: vec![
uniform(attribute("token[]", "blendShapes", tokens())),
attribute(
"float[]",
"blendShapeWeights",
UsdValue::Array(weights.iter().map(|w| UsdValue::Float(*w as f64)).collect()),
),
],
children: Vec::new(),
variant_sets: Vec::new(),
});
}
fn object_prim_at(
arena: &ObjectArena,
id: ObjectId,
ordinal: usize,
materials: &mut Materials,
parent: &str,
placed: &mut Vec<(ObjectId, String)>,
) -> Option<UsdPrim> {
let object = arena.get(id)?;
let name = if object.name.is_empty() {
format!("Node_{ordinal}")
} else {
object.name.clone()
};
let mut prim = match &object.kind {
ObjectKind::Mesh(mesh) => {
let mut prim = mesh_prim(&mesh.geometry, &name);
let material_name = format!("Material_{}", materials.prims.len());
let root = parent.split('/').take(2).collect::<Vec<_>>().join("/");
let (material, images) =
material_prim_with_textures(&mesh.material, &material_name, &root);
materials.prims.push(material);
materials.textures.extend(images);
if mesh.material.side() == 2 {
prim.properties
.push(uniform(attribute("bool", "doubleSided", UsdValue::Bool(true))));
}
if !prim
.properties
.iter()
.any(|p| p.name == "primvars:displayColor")
{
let c = mesh.material.color();
prim.properties.push(interpolated(
attribute(
"color3f[]",
"primvars:displayColor",
UsdValue::Array(vec![tuple3([c.r, c.g, c.b])]),
),
"constant",
));
}
let opacity = mesh.material.opacity();
if opacity < 1.0 {
prim.properties.push(interpolated(
attribute(
"float[]",
"primvars:displayOpacity",
UsdValue::Array(vec![UsdValue::Float(opacity as f64)]),
),
"constant",
));
}
prim.properties.push(UsdProperty {
qualifier: String::new(),
name: "material:binding".into(),
type_name: String::new(),
uniform: false,
relationship: true,
value: UsdValue::Path(format!("/Root/{}", sanitize(&material_name))),
metadata: Vec::new(),
});
prim.metadata.push((
"prepend apiSchemas".into(),
UsdValue::Array(vec![UsdValue::Token("MaterialBindingAPI".into())]),
));
if mesh.is_multi_material() {
let face_of = face_first_triangles(&mesh.geometry);
let mut subsets = Vec::new();
for (k, g) in mesh.geometry.groups.iter().enumerate() {
let Some(m) = mesh.materials.get(g.material_index as usize) else {
continue;
};
let (lo, hi) = (g.start as usize, g.start as usize + g.count as usize);
let faces: Vec<u32> = face_of
.iter()
.enumerate()
.filter(|(_, &t)| (lo..hi).contains(&(t * 3)))
.map(|(f, _)| f as u32)
.collect();
if faces.is_empty() {
continue;
}
let material_name = format!("Material_{}", materials.prims.len());
let (material, images) =
material_prim_with_textures(m, &material_name, &root);
materials.prims.push(material);
materials.textures.extend(images);
subsets.push(UsdPrim {
specifier: Specifier::Def,
type_name: "GeomSubset".into(),
name: format!("Group_{k}"),
metadata: vec![(
"prepend apiSchemas".into(),
UsdValue::Array(vec![UsdValue::Token("MaterialBindingAPI".into())]),
)],
properties: vec![
uniform(attribute("token", "elementType", UsdValue::Token("face".into()))),
uniform(attribute(
"token",
"familyName",
UsdValue::Token("materialBind".into()),
)),
attribute("int[]", "indices", int_array(faces.into_iter())),
UsdProperty {
qualifier: String::new(),
name: "material:binding".into(),
type_name: String::new(),
uniform: false,
relationship: true,
value: UsdValue::Path(format!("/Root/{}", sanitize(&material_name))),
metadata: Vec::new(),
},
],
children: Vec::new(),
variant_sets: Vec::new(),
});
}
if !subsets.is_empty() {
prim.properties.push(uniform(attribute(
"token",
"subsetFamily:materialBind:familyType",
UsdValue::Token("nonOverlapping".into()),
)));
prim.children.extend(subsets);
}
}
let mesh_path = format!("{parent}/{}", prim.name);
add_blend_shapes(mesh, &mut prim, &mesh_path, &root, &mut materials.skel);
prim
}
_ => UsdPrim {
specifier: Specifier::Def,
type_name: "Xform".into(),
name: sanitize(&name),
metadata: Vec::new(),
properties: Vec::new(),
children: Vec::new(),
variant_sets: Vec::new(),
},
};
let p = object.position;
let q = object.quaternion;
let s = object.scale;
let mut order = Vec::new();
if p.length_sq() > 0.0 {
prim.properties.push(attribute(
"double3",
"xformOp:translate",
tuple3([p.x, p.y, p.z]),
));
order.push(UsdValue::Token("xformOp:translate".into()));
}
if (q.w - 1.0).abs() > 1e-9 || q.x != 0.0 || q.y != 0.0 || q.z != 0.0 {
prim.properties.push(attribute(
"quatf",
"xformOp:orient",
UsdValue::Tuple(
[q.w, q.x, q.y, q.z]
.iter()
.map(|v| UsdValue::Float(*v as f64))
.collect(),
),
));
order.push(UsdValue::Token("xformOp:orient".into()));
}
if (s.x - 1.0).abs() > 1e-9 || (s.y - 1.0).abs() > 1e-9 || (s.z - 1.0).abs() > 1e-9 {
prim.properties.push(attribute(
"float3",
"xformOp:scale",
tuple3([s.x, s.y, s.z]),
));
order.push(UsdValue::Token("xformOp:scale".into()));
}
if !order.is_empty() {
prim.properties.push(UsdProperty {
qualifier: String::new(),
name: "xformOpOrder".into(),
type_name: "token[]".into(),
uniform: true,
relationship: false,
value: UsdValue::Array(order),
metadata: Vec::new(),
});
}
if !object.visible {
prim.properties.push(UsdProperty {
qualifier: String::new(),
name: "visibility".into(),
type_name: "token".into(),
uniform: false,
relationship: false,
value: UsdValue::Token("invisible".into()),
metadata: Vec::new(),
});
}
let path = format!("{parent}/{}", prim.name);
placed.push((id, path.clone()));
for (i, child) in object.children.iter().enumerate() {
if let Some(c) = object_prim_at(arena, *child, i, materials, &path, placed) {
prim.children.push(c);
}
}
Some(prim)
}
#[cfg(test)]
mod tests {
#[test]
fn material_groups_round_trip_as_geom_subsets() {
use crate::core::{BufferAttribute, Mesh, Object3D, ObjectArena, ObjectKind};
use crate::materials::{Material, StandardMaterial};
use crate::math::Color;
use std::sync::Arc;
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(
vec![0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0., 2., 0., 0., 2., 1., 0.],
3,
),
);
g.set_index(vec![0, 1, 2, 0, 2, 3, 1, 4, 5, 1, 5, 2]);
g.add_group(0, 6, 1).add_group(6, 6, 0);
let red = Arc::new(Material::from(StandardMaterial::new(Color::new(1.0, 0.0, 0.0))));
let blue = Arc::new(Material::from(StandardMaterial::new(Color::new(0.0, 0.0, 1.0))));
let mut arena = ObjectArena::new();
let mut o = Object3D::mesh(Mesh::with_materials(Arc::new(g), vec![red, blue]));
o.name = "Strip".into();
let id = arena.insert(o);
let text = scene_to_usda(&arena, &[id]);
assert_eq!(text.matches("def GeomSubset").count(), 2, "{text}");
let scene = super::super::scene::to_scene(&super::super::parse::parse(&text).unwrap());
let strip = scene.arena.nodes.values().find(|n| n.name == "Strip").expect("the mesh");
let ObjectKind::Mesh(mesh) = &strip.kind else {
panic!("a mesh")
};
let groups: Vec<(u32, u32)> =
mesh.geometry.groups.iter().map(|g| (g.start, g.count)).collect();
assert_eq!(groups, [(0, 6), (6, 6)]);
let colours: Vec<[f32; 3]> = mesh
.materials
.iter()
.map(|m| {
let c = m.color();
[c.r, c.g, c.b]
})
.collect();
assert_eq!(colours, [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]);
}
fn morphed_quad() -> (crate::core::ObjectArena, crate::core::ObjectId) {
use crate::core::{BufferAttribute, Mesh, Object3D, ObjectArena};
use crate::materials::{Material, StandardMaterial};
let base = vec![0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.];
let up = [0., 0., 1.0f32].repeat(4);
let mut g = BufferGeometry::new();
g.set_attribute("position", BufferAttribute::new(base.clone(), 3));
g.set_attribute("normal", BufferAttribute::new(up.clone(), 3));
g.set_index(vec![0, 1, 2, 0, 2, 3]);
let mut smile = base.clone();
smile[7] += 0.5;
smile[10] += 0.5;
let bulge: Vec<f32> = base
.chunks(3)
.flat_map(|p| [p[0], p[1], p[2] + 0.75])
.collect();
let tilted: Vec<f32> = [0.0, 0.6, 0.8f32].repeat(4);
g.morph_targets_relative = false;
g.morph_target_names = vec!["smile".into(), "bulge".into()];
g.set_morph_attribute(
"position",
vec![BufferAttribute::new(smile, 3), BufferAttribute::new(bulge, 3)],
);
g.morph_attributes.insert(
"normal".into(),
vec![BufferAttribute::new(up, 3), BufferAttribute::new(tilted, 3)],
);
let mut mesh = Mesh::new(g, Material::Standard(StandardMaterial::default()));
mesh.morph_influences = vec![0.25, 0.5];
let mut arena = ObjectArena::new();
let mut o = Object3D::mesh(mesh);
o.name = "Face".into();
let id = arena.insert(o);
(arena, id)
}
fn posed_corners(mesh: &crate::core::Mesh) -> Vec<[i64; 6]> {
let g = mesh.posed_geometry();
let p = &g.get_attribute("position").unwrap().array;
let n = &g.get_attribute("normal").unwrap().array;
let count = p.len() / 3;
let order: Vec<usize> = match &g.index {
Some(i) => i.iter().map(|&v| v as usize).collect(),
None => (0..count).collect(),
};
let mut out: Vec<[i64; 6]> = order
.iter()
.map(|&v| {
let q = |x: f32| (x * 1e4).round() as i64;
[q(p[v * 3]), q(p[v * 3 + 1]), q(p[v * 3 + 2]), q(n[v * 3]), q(n[v * 3 + 1]), q(n[v * 3 + 2])]
})
.collect();
out.sort();
out.dedup();
out
}
fn the_face(scene: &super::super::scene::UsdScene) -> &crate::core::Mesh {
use crate::core::ObjectKind;
let face = scene.arena.nodes.values().find(|n| n.name == "Face").expect("the mesh");
let ObjectKind::Mesh(mesh) = &face.kind else {
panic!("a plain mesh, not {:?}", std::mem::discriminant(&face.kind))
};
mesh
}
#[test]
fn morph_targets_round_trip_as_blend_shapes() {
use crate::core::ObjectKind;
let (arena, id) = morphed_quad();
let ObjectKind::Mesh(original) = &arena.get(id).unwrap().kind else {
unreachable!()
};
let want = posed_corners(original);
let text = scene_to_usda(&arena, &[id]);
assert_eq!(text.matches("def BlendShape").count(), 2, "{text}");
assert!(text.contains("def SkelRoot \"Root\""), "{text}");
assert!(text.contains("skel:blendShapeTargets"), "{text}");
assert!(text.contains("blendShapeWeights"), "{text}");
assert!(text.contains("pointIndices"), "{text}");
let usdc = super::super::scene_to_usdc(&arena, &[id]);
for (form, layer) in [
("usda", super::super::parse::parse(&text).expect("usda parses")),
("usdc", super::super::UsdLoader::parse_layer(&usdc).expect("usdc parses")),
(
"usdcat usdc",
super::super::UsdLoader::parse_layer(include_bytes!(
"testdata/morph_blend_shapes.usdc"
))
.expect("usdcat's crate parses"),
),
] {
let scene = super::super::scene::to_scene(&layer);
let mesh = the_face(&scene);
assert_eq!(
mesh.geometry.morph_target_names,
["smile", "bulge"],
"{form}: target names"
);
assert_eq!(mesh.morph_influences, [0.25, 0.5], "{form}: influences");
assert_eq!(
mesh.morph_target_dictionary.get("bulge"),
Some(&1),
"{form}: dictionary"
);
assert_eq!(posed_corners(mesh), want, "{form}: posed surface");
let mut rest = mesh.clone();
rest.morph_influences = vec![0.0, 1.0];
let mut orig = original.clone();
orig.morph_influences = vec![0.0, 1.0];
assert_eq!(posed_corners(&rest), posed_corners(&orig), "{form}: bulge alone");
for n in scene.arena.nodes.values() {
assert!(
!["smile", "bulge", "Smile", "Bulge"].contains(&n.name.as_str())
&& !n.name.starts_with("Morph"),
"{form}: a node {:?} for a skel prim",
n.name
);
}
}
}
#[test]
fn a_connection_is_not_spelled_twice() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::geometries::BoxGeometry;
use crate::materials::{Material, StandardMaterial};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(
BoxGeometry::new(1.0, 1.0, 1.0),
Material::Standard(StandardMaterial::default()),
)));
let text = scene_to_usda(&arena, &[id]);
assert!(
!text.contains(".connect.connect"),
"the suffix was written twice:\n{text}"
);
assert!(text.contains("outputs:surface.connect = <"), "{text}");
let layer = super::super::parse::parse(&text).expect("what we wrote, USD can read");
let material = layer.prim_at("/Root/Material_0").expect("the material");
assert!(material.property("outputs:surface.connect").is_none());
let surface = material.property("outputs:surface").expect("the connection");
assert!(matches!(surface.value, UsdValue::Path(_)), "{:?}", surface.value);
}
#[test]
fn a_clip_round_trips_through_a_document() {
use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget};
use crate::core::Object3D;
use crate::math::{Quaternion, Vector3};
let mut arena = ObjectArena::new();
let mut object = Object3D::group();
object.name = "Mover".into();
let id = arena.insert(object);
let clip = AnimationClip::new(
"spin",
2.0,
vec![
KeyframeTrack::vector(
id,
TrackTarget::Position,
vec![0.0, 1.0, 2.0],
vec![
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(10.0, 0.0, 0.0),
Vector3::new(10.0, 10.0, 0.0),
],
),
KeyframeTrack::quaternion(
id,
TrackTarget::Quaternion,
vec![0.0, 2.0],
vec![
Quaternion::identity(),
Quaternion::from_axis_angle(Vector3::new(0.0, 0.0, 1.0), 1.0),
],
),
],
);
let text = animated_scene_to_usda(&arena, &[id], &[clip]);
let layer = super::super::parse::parse(&text).expect("what we wrote, we can read");
assert_eq!(layer.time_codes_per_second(), 24.0);
assert_eq!(layer.time_range(), Some((0.0, 48.0)));
let mover = layer.prim_at("/Root/Mover").expect("the animated prim");
let translate = mover.value("xformOp:translate").unwrap();
let samples = translate.samples().expect("animated");
assert_eq!(samples.len(), 3);
assert_eq!(samples[1].0, 24.0);
assert_eq!(samples[2].1.flat_f32(), vec![10.0, 10.0, 0.0]);
let order = mover.value("xformOpOrder").unwrap().flat_tokens();
assert!(order.contains(&"xformOp:translate"), "{order:?}");
assert!(order.contains(&"xformOp:orient"), "{order:?}");
}
#[test]
fn a_clip_survives_the_whole_round_trip() {
use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget, TrackValues};
use crate::core::Object3D;
use crate::math::Vector3;
let mut arena = ObjectArena::new();
let mut object = Object3D::group();
object.name = "Mover".into();
let id = arena.insert(object);
let clip = AnimationClip::new(
"move",
2.0,
vec![KeyframeTrack::vector(
id,
TrackTarget::Position,
vec![0.0, 2.0],
vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(4.0, 0.0, 0.0)],
)],
);
let text = animated_scene_to_usda(&arena, &[id], &[clip]);
let layer = super::super::parse::parse(&text).unwrap();
let scene = super::super::scene::to_scene(&layer);
let back = scene.animations.first().expect("a clip came back");
assert_eq!(back.duration, 2.0);
let track = back
.tracks
.iter()
.find(|t| matches!(t.target, TrackTarget::Position))
.expect("a position track");
assert_eq!(track.times, vec![0.0, 2.0]);
let TrackValues::Vector(values) = &track.values else {
panic!("expected vectors");
};
assert_eq!(values[1], Vector3::new(4.0, 0.0, 0.0));
}
#[test]
fn a_static_scene_gains_no_timing() {
use crate::core::Object3D;
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::group());
let text = animated_scene_to_usda(&arena, &[id], &[]);
assert!(!text.contains("timeCodesPerSecond"), "{text}");
assert!(!text.contains("timeSamples"), "{text}");
}
use super::super::parse::parse;
use super::super::scene::{mesh_geometry, to_scene};
use super::*;
use crate::core::{BufferAttribute, Mesh, Object3D};
use crate::materials::StandardMaterial;
use crate::math::{Color, Vector3};
fn triangle() -> BufferGeometry {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
);
g.set_attribute("uv", BufferAttribute::new(vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0], 2));
g.set_index(vec![0, 1, 2]);
g
}
#[test]
fn a_geometry_round_trips_through_usda() {
let text = geometry_to_usda(&triangle(), "Tri");
let layer = parse(&text).unwrap();
let prim = layer.prim_at("/Root/Tri").unwrap();
assert_eq!(prim.type_name, "Mesh");
let back = mesh_geometry(prim).unwrap();
assert_eq!(
back.get_attribute("position").unwrap().array,
triangle().get_attribute("position").unwrap().array
);
assert_eq!(back.index.clone().unwrap(), vec![0, 1, 2]);
assert_eq!(back.get_attribute("uv").unwrap().array.len(), 6);
}
#[test]
fn the_extent_is_written_and_is_the_bounding_box() {
let layer = parse(&geometry_to_usda(&triangle(), "Tri")).unwrap();
let extent = layer
.prim_at("/Root/Tri")
.unwrap()
.value("extent")
.unwrap()
.flat_f32();
assert_eq!(extent, vec![0.0, 0.0, 0.0, 1.0, 1.0, 0.0]);
}
#[test]
fn names_that_are_not_identifiers_are_made_into_them() {
assert_eq!(sanitize("wheel.001"), "wheel_001");
assert_eq!(sanitize("2fast"), "_fast");
assert_eq!(sanitize(""), "Prim");
let text = geometry_to_usda(&triangle(), "wheel.001");
assert!(parse(&text).unwrap().prim_at("/Root/wheel_001").is_some());
}
#[test]
fn a_scene_keeps_its_hierarchy_and_transforms() {
let mut arena = ObjectArena::new();
let mut parent = Object3D::group();
parent.name = "Parent".into();
parent.position = Vector3::new(1.0, 2.0, 3.0);
let parent_id = arena.insert(parent);
let mut child = Object3D::mesh(Mesh::new(
triangle(),
StandardMaterial::new(Color::new(1.0, 0.0, 0.0)).into(),
));
child.name = "Child".into();
child.scale = Vector3::new(2.0, 2.0, 2.0);
let child_id = arena.insert(child);
arena.add_child(parent_id, child_id);
let text = scene_to_usda(&arena, &[parent_id]);
let layer = parse(&text).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let parent = scene.arena.get(root.children[0]).unwrap();
assert_eq!(parent.name, "Parent");
assert!((parent.position.y - 2.0).abs() < 1e-6);
let child = scene.arena.get(parent.children[0]).unwrap();
assert_eq!(child.name, "Child");
assert!((child.scale.x - 2.0).abs() < 1e-6);
}
#[test]
fn every_coloured_material_exports_its_colour() {
use crate::materials::{
BasicMaterial, LambertMaterial, LineBasicMaterial, MatcapMaterial, MirrorMaterial,
PhongMaterial, PhysicalMaterial, PointsMaterial, SpriteMaterial, ToonMaterial,
};
let red = Color::new(0.9, 0.2, 0.1);
let kinds: Vec<(&str, Material)> = vec![
(
"lambert",
LambertMaterial { color: red, ..Default::default() }.into(),
),
(
"phong",
PhongMaterial { color: red, ..Default::default() }.into(),
),
(
"toon",
ToonMaterial { color: red, ..Default::default() }.into(),
),
(
"matcap",
MatcapMaterial { color: red, ..Default::default() }.into(),
),
(
"sprite",
SpriteMaterial { color: red, ..Default::default() }.into(),
),
(
"points",
PointsMaterial { color: red, ..Default::default() }.into(),
),
(
"line",
LineBasicMaterial { color: red, ..Default::default() }.into(),
),
(
"mirror",
MirrorMaterial { color: red, ..Default::default() }.into(),
),
(
"physical",
PhysicalMaterial { color: red, ..Default::default() }.into(),
),
("basic", BasicMaterial::new(red).into()),
("standard", StandardMaterial::new(red).into()),
];
for (label, material) in kinds {
let prim = material_prim(&material, "M");
let surface = &prim.children[0];
let colour = surface
.value("inputs:diffuseColor")
.expect("a diffuse colour")
.flat_f32();
assert_eq!(
colour,
vec![0.9, 0.2, 0.1],
"{label} lost its colour on the way out"
);
}
}
fn checker_texture() -> std::sync::Arc<crate::textures::Texture> {
use crate::textures::{Texture, TextureFormat, TextureWrap};
let mut t = Texture::new(
2,
2,
TextureFormat::Rgba8UnormSrgb,
vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255],
);
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::MirroredRepeat;
std::sync::Arc::new(t)
}
fn child<'a>(prim: &'a UsdPrim, name: &str) -> &'a UsdPrim {
prim.children
.iter()
.find(|c| c.name == name)
.unwrap_or_else(|| panic!("no child {name}"))
}
#[test]
fn a_map_exports_as_a_texture_network() {
let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
m.map = Some(checker_texture());
let (prim, images) = material_prim_with_textures(&m.into(), "M", "/Root");
assert_eq!(images.len(), 1);
assert_eq!(images[0].path, "textures/M_DiffuseTex.png");
assert!(images[0].data.starts_with(b"\x89PNG"), "a PNG was encoded");
let texture = child(&prim, "DiffuseTex");
assert_eq!(
texture.value("info:id").unwrap().as_str(),
Some("UsdUVTexture")
);
assert_eq!(
texture.value("inputs:file").unwrap().as_str(),
Some("textures/M_DiffuseTex.png")
);
assert_eq!(texture.value("inputs:wrapS").unwrap().as_str(), Some("repeat"));
assert_eq!(texture.value("inputs:wrapT").unwrap().as_str(), Some("mirror"));
assert_eq!(
texture.value("inputs:sourceColorSpace").unwrap().as_str(),
Some("sRGB")
);
let reader = child(&prim, "stReader");
assert_eq!(
reader.value("info:id").unwrap().as_str(),
Some("UsdPrimvarReader_float2")
);
let surface = child(&prim, "Surface");
let diffuse: Vec<&UsdProperty> = surface
.properties
.iter()
.filter(|p| p.name == "inputs:diffuseColor")
.collect();
assert_eq!(diffuse.len(), 1, "one property, not a value and a connection");
assert_eq!(
diffuse[0].value.as_str(),
Some("/Root/M/DiffuseTex.outputs:rgb")
);
}
#[test]
fn a_normal_map_carries_its_scale_and_bias() {
let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
m.normal_map = Some(checker_texture());
let (prim, _) = material_prim_with_textures(&m.into(), "M", "/Root");
let texture = child(&prim, "NormalTex");
assert_eq!(
texture.value("inputs:scale").unwrap().flat_f32(),
vec![2.0, 2.0, 2.0, 1.0]
);
assert_eq!(
texture.value("inputs:bias").unwrap().flat_f32(),
vec![-1.0, -1.0, -1.0, 0.0]
);
assert_eq!(
texture.value("inputs:sourceColorSpace").unwrap().as_str(),
Some("raw")
);
let surface = child(&prim, "Surface");
assert!(surface.properties.iter().any(|p| p.name == "inputs:normal"));
}
#[test]
fn a_uv_transform_becomes_a_transform_node_in_degrees() {
use crate::math::Vector2;
let mut texture = (*checker_texture()).clone();
texture.repeat = Vector2::new(2.0, 3.0);
texture.rotation = std::f32::consts::FRAC_PI_2;
let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
m.map = Some(std::sync::Arc::new(texture));
let (prim, _) = material_prim_with_textures(&m.into(), "M", "/Root");
let node = child(&prim, "DiffuseTexTransform");
assert_eq!(
node.value("info:id").unwrap().as_str(),
Some("UsdTransform2d")
);
assert_eq!(node.value("inputs:scale").unwrap().flat_f32(), vec![2.0, 3.0]);
let rotation = node.value("inputs:rotation").unwrap().flat_f32()[0];
assert!((rotation - 90.0).abs() < 1e-3, "{rotation} should be degrees");
assert_eq!(
child(&prim, "DiffuseTex").value("inputs:st").unwrap().as_str(),
Some("/Root/M/DiffuseTexTransform.outputs:result")
);
}
#[test]
fn a_texture_with_no_pixels_is_skipped_not_fatal() {
use crate::textures::{Texture, TextureFormat};
let mut m = StandardMaterial::new(Color::new(0.25, 0.5, 0.75));
m.map = Some(std::sync::Arc::new(Texture::new(
4,
4,
TextureFormat::Rgba8UnormSrgb,
Vec::new(),
)));
let (prim, images) = material_prim_with_textures(&m.into(), "M", "/Root");
assert!(images.is_empty());
assert_eq!(
child(&prim, "Surface")
.value("inputs:diffuseColor")
.unwrap()
.flat_f32(),
vec![0.25, 0.5, 0.75]
);
}
#[test]
fn a_usdz_packs_the_textures_its_materials_name() {
use crate::core::{Mesh, Object3D, ObjectArena};
let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
m.map = Some(checker_texture());
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
let bytes = super::super::scene_to_usdz(&arena, &[id], &[]);
let archive = super::super::usdz::read(&bytes).expect("a readable archive");
let names: Vec<&str> = archive.entries.iter().map(|e| e.name.as_str()).collect();
assert!(
names.contains(&"textures/Material_0_DiffuseTex.png"),
"{names:?}"
);
}
#[test]
fn double_sided_lands_on_the_mesh() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::materials::LambertMaterial;
for (side, expected) in [(0u32, false), (2, true)] {
let m = LambertMaterial { side, ..Default::default() };
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
let layer = scene_to_layer(&arena, &[id], &UsdExportOptions::default());
let mesh = layer.prim_at("/Root/Node_0").expect("the mesh");
assert_eq!(mesh.value("doubleSided").is_some(), expected, "side {side}");
}
}
#[test]
fn ior_and_clearcoat_are_physical_only() {
use crate::materials::PhysicalMaterial;
let p = PhysicalMaterial {
ior: 1.45,
clearcoat: 0.8,
clearcoat_roughness: 0.05,
..Default::default()
};
let surface = material_prim(&p.into(), "M").children[0].clone();
assert_eq!(surface.value("inputs:ior").unwrap().flat_f32(), vec![1.45]);
assert_eq!(
surface.value("inputs:clearcoat").unwrap().flat_f32(),
vec![0.8]
);
let plain = material_prim(&StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(), "M");
assert!(plain.children[0].value("inputs:ior").is_none());
assert!(plain.children[0].value("inputs:clearcoat").is_none());
}
#[test]
fn vertex_colours_export_as_display_colour() {
use crate::core::BufferAttribute;
let mut g = triangle();
g.set_attribute(
"color",
BufferAttribute::new(vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], 3),
);
let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
let prim = layer.prim_at("/Root/M").unwrap();
let property = prim.property("primvars:displayColor").expect("a colour");
assert_eq!(
property.value.flat_f32(),
vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
);
assert_eq!(
property.meta("interpolation").and_then(|v| v.as_str()),
Some("vertex")
);
}
#[test]
fn a_material_colour_becomes_a_constant_display_colour() {
use crate::core::{Mesh, Object3D, ObjectArena};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(
triangle(),
StandardMaterial::new(Color::new(0.25, 0.5, 0.75)).into(),
)));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let property = layer
.prim_at("/Root/Node_0")
.unwrap()
.property("primvars:displayColor")
.expect("a colour");
assert_eq!(property.value.flat_f32(), vec![0.25, 0.5, 0.75]);
assert_eq!(
property.meta("interpolation").and_then(|v| v.as_str()),
Some("constant")
);
}
#[test]
fn a_constant_display_colour_does_not_become_vertex_colours() {
use crate::loaders::usd::scene::to_scene;
let mut arena = crate::core::ObjectArena::new();
let id = arena.insert(crate::core::Object3D::mesh(crate::core::Mesh::new(
triangle(),
StandardMaterial::new(Color::new(0.25, 0.5, 0.75)).into(),
)));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let ObjectKind::Mesh(mesh) = &scene.arena.get(root.children[0]).unwrap().kind else {
panic!("not a mesh");
};
assert!(
mesh.geometry.get_attribute("color").is_none(),
"a constant colour is the material's, not the vertices'"
);
}
#[test]
fn vertex_colours_come_back() {
use crate::core::BufferAttribute;
use crate::loaders::usd::scene::to_scene;
let mut g = triangle();
let colours = vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
g.set_attribute("color", BufferAttribute::new(colours.clone(), 3));
let mut arena = crate::core::ObjectArena::new();
let id = arena.insert(crate::core::Object3D::mesh(crate::core::Mesh::new(
g,
StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(),
)));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let ObjectKind::Mesh(mesh) = &scene.arena.get(root.children[0]).unwrap().kind else {
panic!("not a mesh");
};
assert_eq!(
mesh.geometry.get_attribute("color").expect("colours").array,
colours
);
}
#[test]
fn an_alpha_test_becomes_an_opacity_threshold() {
use crate::materials::BasicMaterial;
let cutout = BasicMaterial {
alpha_test: 0.5,
..BasicMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let surface = material_prim(&cutout.into(), "M").children[0].clone();
assert_eq!(
surface.value("inputs:opacityThreshold").unwrap().flat_f32(),
vec![0.5]
);
let blended = material_prim(&BasicMaterial::new(Color::new(1.0, 1.0, 1.0)).into(), "M");
assert!(blended.children[0]
.value("inputs:opacityThreshold")
.is_none());
}
#[test]
fn every_form_keeps_the_textures() {
use super::super::{UsdExport, UsdLoader};
use crate::core::{Mesh, Object3D, ObjectArena};
let material = StandardMaterial {
map: Some(checker_texture()),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
let out = UsdExport::scene(&arena, &[id]);
assert_eq!(out.textures.len(), 1, "the export knows about its image");
assert_eq!(out.textures[0].path, "textures/Material_0_DiffuseTex.png");
let from_text = super::super::parse::parse(&out.usda()).unwrap();
let from_crate = super::super::usdc::read(&out.usdc()).unwrap();
for layer in [&from_text, &from_crate] {
let shader = layer
.prim_at("/Root/Material_0/DiffuseTex")
.expect("the texture shader");
assert_eq!(
shader.value("inputs:file").unwrap().as_str(),
Some("textures/Material_0_DiffuseTex.png")
);
}
let scene = UsdLoader::parse(&out.usdz()).expect("reads back");
let ObjectKind::Mesh(mesh) = &scene
.arena
.get(scene.arena.get(scene.roots[0]).unwrap().children[0])
.unwrap()
.kind
else {
panic!("not a mesh");
};
let Material::Standard(back) = &*mesh.material else {
panic!("{:?}", mesh.material)
};
assert!(back.map.is_some(), "the package carried its image");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_layer_written_to_disk_reads_back_with_its_images() {
use super::super::{attach_textures_from_dir, UsdExport, UsdLoader};
use crate::core::{Mesh, Object3D, ObjectArena};
let material = StandardMaterial {
map: Some(checker_texture()),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
let out = UsdExport::scene(&arena, &[id]);
let dir = std::env::temp_dir().join(format!("threers_usd_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
for name in ["disk.usda", "disk.usdc"] {
let path = dir.join(name);
out.write_to(&path, &dir).expect("writes");
assert!(
dir.join("textures/Material_0_DiffuseTex.png").exists(),
"the image landed beside {name}"
);
let bytes = std::fs::read(&path).unwrap();
let mut scene = UsdLoader::parse(&bytes).expect("reads");
assert_eq!(
scene.textures.iter().flat_map(|(_, r)| r).count(),
1,
"{name} should ask for its image"
);
assert_eq!(attach_textures_from_dir(&mut scene, &dir), 1, "{name}");
let ObjectKind::Mesh(mesh) = &scene
.arena
.get(scene.arena.get(scene.roots[0]).unwrap().children[0])
.unwrap()
.kind
else {
panic!("not a mesh");
};
let Material::Standard(back) = &*mesh.material else {
panic!("{:?}", mesh.material)
};
let map = back.map.as_ref().unwrap_or_else(|| panic!("{name} lost its map"));
assert_eq!(&map.data[..4], &[255, 0, 0, 255], "{name} pixels changed");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_texture_path_does_not_escape_its_directory() {
use super::super::{attach_textures_from_dir, UsdLoader};
let dir = std::env::temp_dir().join(format!("threers_usd_esc_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("sub")).unwrap();
std::fs::write(
dir.join("secret.png"),
crate::utils::png::encode_png(1, 1, &[9, 9, 9, 255]),
)
.unwrap();
let text = r#"#usda 1.0
def Mesh "M" (
prepend apiSchemas = ["MaterialBindingAPI"]
)
{
int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
rel material:binding = </Mat>
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
}
def Material "Mat"
{
token outputs:surface.connect = </Mat/S.outputs:surface>
def Shader "S"
{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor.connect = </Mat/T.outputs:rgb>
token outputs:surface
}
def Shader "T"
{
uniform token info:id = "UsdUVTexture"
asset inputs:file = @../secret.png@
float3 outputs:rgb
}
}
"#;
let mut scene = UsdLoader::parse(text.as_bytes()).expect("reads");
assert_eq!(
attach_textures_from_dir(&mut scene, &dir.join("sub")),
0,
"a path climbing out was followed"
);
assert_eq!(
scene.textures.iter().flat_map(|(_, r)| r).count(),
1,
"and it is still reported rather than dropped"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_package_holds_text_or_crate() {
use super::super::{UsdExport, UsdzLayer};
use crate::core::{Mesh, Object3D, ObjectArena};
let material = StandardMaterial {
map: Some(checker_texture()),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
let out = UsdExport::scene(&arena, &[id]);
for (form, stem, magic) in [
(UsdzLayer::Text, "scene.usda", &b"#usda"[..]),
(UsdzLayer::Crate, "scene.usdc", &b"PXR-USDC"[..]),
] {
let archive =
super::super::usdz::read(&out.usdz_as(form, &[])).expect("a readable archive");
let root = archive.entries.first().expect("a layer");
assert_eq!(root.name, stem);
assert!(root.data.starts_with(magic), "{stem} is the wrong form");
assert!(
archive
.entries
.iter()
.any(|e| e.name == "textures/Material_0_DiffuseTex.png"),
"the image travelled with {stem}"
);
}
}
#[test]
fn a_bottom_up_texture_is_written_the_right_way_up() {
use crate::textures::{Texture, TextureFormat};
let pixels = vec![255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 255];
let top_down = Texture::new(2, 2, TextureFormat::Rgba8UnormSrgb, pixels.clone());
assert!(top_down.flip_y, "an image texture stores the top row first");
let bottom_up = Texture {
flip_y: false,
..Texture::new(2, 2, TextureFormat::Rgba8UnormSrgb, pixels)
};
let written = |texture: Texture| {
let m = StandardMaterial {
map: Some(std::sync::Arc::new(texture)),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let (_, images) = material_prim_with_textures(&m.into(), "M", "/Root");
crate::utils::png::decode_png(&images[0].data).unwrap().rgba
};
assert_eq!(&written(top_down)[..4], &[255, 0, 0, 255]);
assert_eq!(&written(bottom_up)[..4], &[0, 0, 255, 255]);
}
#[test]
fn a_usdz_comes_back_with_its_textures_loaded() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::textures::{TextureFormat, TextureWrap};
let material = StandardMaterial {
map: Some(checker_texture()),
normal_map: Some(checker_texture()),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let mut arena = ObjectArena::new();
let mut object = Object3D::mesh(Mesh::new(triangle(), material.into()));
object.name = "Quad".into();
let id = arena.insert(object);
let bytes = super::super::scene_to_usdz(&arena, &[id], &[]);
let scene = super::super::UsdLoader::parse(&bytes).expect("reads back");
let quad = scene
.arena
.get_objects_by_name(scene.roots[0], "Quad")
.into_iter()
.next()
.expect("the quad");
let ObjectKind::Mesh(mesh) = &scene.arena.get(quad).unwrap().kind else {
panic!("not a mesh");
};
let Material::Standard(back) = &*mesh.material else {
panic!("{:?}", mesh.material);
};
let map = back.map.as_ref().expect("the colour map came back");
assert_eq!((map.width, map.height), (2, 2));
assert_eq!(
&map.data[..8],
&[255, 0, 0, 255, 0, 255, 0, 255],
"the pixels changed on the way"
);
assert_eq!(map.wrap_s, TextureWrap::Repeat);
assert_eq!(map.wrap_t, TextureWrap::MirroredRepeat);
assert_eq!(map.format, TextureFormat::Rgba8UnormSrgb);
let normal = back.normal_map.as_ref().expect("the normal map");
assert_eq!(normal.format, TextureFormat::Rgba8Unorm);
assert!(
scene.textures.iter().all(|(_, r)| r.is_empty()),
"{:?}",
scene.textures
);
}
#[test]
fn a_usda_still_reports_the_textures_it_names() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::loaders::usd::scene::to_scene;
let material = StandardMaterial {
map: Some(checker_texture()),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let asked: Vec<&str> = scene
.textures
.iter()
.flat_map(|(_, r)| r.iter())
.map(|r| r.file.as_str())
.collect();
assert_eq!(asked, ["textures/Material_0_DiffuseTex.png"]);
}
#[test]
fn a_physical_material_survives_the_round_trip() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::materials::PhysicalMaterial;
use crate::loaders::usd::scene::to_scene;
let source = PhysicalMaterial {
color: Color::new(0.3, 0.7, 0.7),
roughness: 0.1,
ior: 1.45,
clearcoat: 0.8,
clearcoat_roughness: 0.05,
side: 2,
..Default::default()
};
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), source.into())));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let mesh = scene.arena.get(root.children[0]).unwrap();
let ObjectKind::Mesh(mesh) = &mesh.kind else {
panic!("not a mesh");
};
let Material::Physical(back) = &*mesh.material else {
panic!("came back as {:?}, not physical", mesh.material);
};
assert!((back.ior - 1.45).abs() < 1e-5, "{}", back.ior);
assert!((back.clearcoat - 0.8).abs() < 1e-5);
assert!((back.clearcoat_roughness - 0.05).abs() < 1e-5);
assert!((back.roughness - 0.1).abs() < 1e-5);
assert!((back.color.g - 0.7).abs() < 1e-5);
assert_eq!(back.side, 2, "doubleSided did not come back");
}
#[test]
fn a_standard_material_stays_standard() {
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::loaders::usd::scene::to_scene;
let mut arena = ObjectArena::new();
let id = arena.insert(Object3D::mesh(Mesh::new(
triangle(),
StandardMaterial::new(Color::new(0.2, 0.4, 0.6)).into(),
)));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let mesh = scene.arena.get(root.children[0]).unwrap();
let ObjectKind::Mesh(mesh) = &mesh.kind else {
panic!("not a mesh");
};
assert!(
matches!(&*mesh.material, Material::Standard(_)),
"{:?}",
mesh.material
);
}
#[test]
fn phong_becomes_the_specular_workflow() {
use crate::materials::PhongMaterial;
let phong = PhongMaterial {
color: Color::new(0.2, 0.3, 0.9),
specular: Color::new(1.0, 1.0, 1.0),
shininess: 30.0,
..Default::default()
};
let prim = material_prim(&phong.clone().into(), "M");
let surface = &prim.children[0];
assert_eq!(
surface.value("inputs:useSpecularWorkflow").unwrap().flat_u32(),
vec![1]
);
assert_eq!(
surface.value("inputs:specularColor").unwrap().flat_f32(),
vec![1.0, 1.0, 1.0]
);
let rough = surface.value("inputs:roughness").unwrap().flat_f32()[0];
assert!((rough - 0.25).abs() < 1e-6, "{rough}");
let smoother = material_prim(&PhongMaterial { shininess: 200.0, ..phong.clone() }.into(), "M")
.children[0]
.value("inputs:roughness")
.unwrap()
.flat_f32()[0];
assert!(smoother < rough, "a higher exponent is a smoother surface");
}
#[test]
fn only_phong_carries_the_specular_workflow() {
let prim = material_prim(&StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(), "M");
assert!(prim.children[0]
.value("inputs:useSpecularWorkflow")
.is_none());
}
#[test]
fn a_material_survives_the_round_trip() {
let mut arena = ObjectArena::new();
let mut m = StandardMaterial::new(Color::new(0.2, 0.4, 0.6));
m.roughness = 0.3;
m.metalness = 0.8;
let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
let scene = to_scene(&layer);
let root = scene.arena.get(scene.roots[0]).unwrap();
let mesh = scene.arena.get(root.children[0]).unwrap();
match &mesh.kind {
ObjectKind::Mesh(mesh) => match &*mesh.material {
Material::Standard(s) => {
assert!((s.color.b - 0.6).abs() < 1e-6);
assert!((s.roughness - 0.3).abs() < 1e-6);
assert!((s.metalness - 0.8).abs() < 1e-6);
}
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
}
}
#[test]
fn unindexed_geometry_gets_an_index_written_for_it() {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0; 18], 3),
);
let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
let prim = layer.prim_at("/Root/M").unwrap();
assert_eq!(prim.value("faceVertexCounts").unwrap().flat_u32(), vec![3, 3]);
assert_eq!(
prim.value("faceVertexIndices").unwrap().flat_u32(),
vec![0, 1, 2, 3, 4, 5]
);
}
#[test]
fn polygons_round_trip_against_usdcat() {
const AUTHORED: &[u8] = include_bytes!("testdata/polygons.usdc");
const COUNTS: [u32; 3] = [4, 3, 5];
const INDICES: [u32; 12] = [0, 1, 2, 3, 1, 4, 2, 4, 5, 6, 7, 2];
let layer = super::super::crate_read::read(AUTHORED).unwrap();
let g = mesh_geometry(layer.prim_at("/Root/Faces").unwrap()).unwrap();
assert_eq!(g.polygon_counts(), Some(&[2u32, 1, 3][..]));
let text = geometry_to_usda(&g, "Faces");
let crate_bytes = super::super::geometry_to_usdc(&g, "Faces");
for layer in [
parse(&text).unwrap(),
super::super::crate_read::read(&crate_bytes).unwrap(),
] {
let prim = layer.prim_at("/Root/Faces").unwrap();
assert_eq!(prim.value("faceVertexCounts").unwrap().flat_u32(), COUNTS);
assert_eq!(prim.value("faceVertexIndices").unwrap().flat_u32(), INDICES);
}
let usdcat = std::path::Path::new("/usr/bin/usdcat");
if !usdcat.exists() {
eprintln!("no usdcat; checked against this crate's reader only");
return;
}
let dir = std::env::temp_dir().join(format!("threers-polygons-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let usda = dir.join("faces.usda");
let usdc = dir.join("faces.usdc");
std::fs::write(&usda, &text).unwrap();
std::fs::write(&usdc, &crate_bytes).unwrap();
for file in [&usda, &usdc] {
let out = std::process::Command::new(usdcat)
.arg(file)
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let flat = String::from_utf8_lossy(&out.stdout);
assert!(
flat.contains("int[] faceVertexCounts = [4, 3, 5]"),
"{flat}"
);
assert!(
flat.contains("int[] faceVertexIndices = [0, 1, 2, 3, 1, 4, 2, 4, 5, 6, 7, 2]"),
"{flat}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unrecoverable_polygon_is_written_as_triangles() {
let mut g = BufferGeometry::new();
let mut points = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
points.extend_from_slice(&[5.0, 0.0, 0.0, 6.0, 0.0, 0.0, 5.0, 1.0, 0.0]);
g.set_attribute("position", BufferAttribute::new(points, 3));
g.set_index(vec![0, 1, 2, 3, 4, 5]);
g.set_polygons(vec![2]);
assert_eq!(g.polygon_counts(), Some(&[2u32][..]));
let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
let prim = layer.prim_at("/Root/M").unwrap();
assert_eq!(
prim.value("faceVertexCounts").unwrap().flat_u32(),
vec![3, 3]
);
}
}
pub fn animated_scene_to_layer(
arena: &ObjectArena,
roots: &[ObjectId],
clips: &[AnimationClip],
options: &UsdExportOptions,
) -> UsdLayer {
animated_scene_to_layer_with_textures(arena, roots, clips, options).0
}
pub fn animated_scene_to_layer_with_textures(
arena: &ObjectArena,
roots: &[ObjectId],
clips: &[AnimationClip],
options: &UsdExportOptions,
) -> (UsdLayer, Vec<ExportedTexture>) {
let mut placed = Vec::new();
let (mut layer, textures) = scene_to_layer_placed(arena, roots, options, &mut placed);
let rate = options.time_codes_per_second.max(1.0) as f64;
let mut last = 0.0f64;
for clip in clips {
for track in &clip.tracks {
let Some((_, path)) = placed.iter().find(|(id, _)| *id == track.object) else {
continue;
};
let Some(op) = sampled_track(track, rate) else {
continue;
};
if let Some(time) = op.samples.last().map(|(t, _)| *t) {
last = last.max(time);
}
let Some(prim) = prim_at_mut(&mut layer, path) else {
continue;
};
set_op(
prim,
op.name,
op.type_name,
UsdValue::TimeSamples(op.samples),
);
}
last = last.max((clip.duration as f64) * rate);
}
if last > 0.0 {
layer.metadata.push((
"timeCodesPerSecond".into(),
UsdValue::Float(rate),
));
layer.metadata.push(("startTimeCode".into(), UsdValue::Float(0.0)));
layer.metadata.push(("endTimeCode".into(), UsdValue::Float(last)));
}
(layer, textures)
}
pub fn animated_scene_to_usda(
arena: &ObjectArena,
roots: &[ObjectId],
clips: &[AnimationClip],
) -> String {
layer_to_usda(&animated_scene_to_layer(
arena,
roots,
clips,
&UsdExportOptions::default(),
))
}
struct SampledOp {
name: &'static str,
type_name: &'static str,
samples: Vec<(f64, UsdValue)>,
}
fn sampled_track(track: &KeyframeTrack, rate: f64) -> Option<SampledOp> {
let time = |i: usize| track.times.get(i).map(|t| *t as f64 * rate).unwrap_or(0.0);
match (&track.target, &track.values) {
(TrackTarget::Position, TrackValues::Vector(values)) => Some(SampledOp {
name: "xformOp:translate",
type_name: "double3",
samples: values
.iter()
.enumerate()
.map(|(i, v)| (time(i), tuple3([v.x, v.y, v.z])))
.collect(),
}),
(TrackTarget::Scale, TrackValues::Vector(values)) => Some(SampledOp {
name: "xformOp:scale",
type_name: "float3",
samples: values
.iter()
.enumerate()
.map(|(i, v)| (time(i), tuple3([v.x, v.y, v.z])))
.collect(),
}),
(TrackTarget::Quaternion, TrackValues::Quaternion(values)) => Some(SampledOp {
name: "xformOp:orient",
type_name: "quatf",
samples: values
.iter()
.enumerate()
.map(|(i, q)| (time(i), tuple4([q.w, q.x, q.y, q.z])))
.collect(),
}),
_ => None,
}
}
fn set_op(prim: &mut UsdPrim, name: &str, type_name: &str, value: UsdValue) {
match prim.properties.iter_mut().find(|p| p.name == name) {
Some(existing) => existing.value = value,
None => prim.properties.push(attribute(type_name, name, value)),
}
let ordered = prim.properties.iter().any(|p| {
p.name == "xformOpOrder" && p.value.flat_tokens().contains(&name)
});
if ordered {
return;
}
match prim.properties.iter_mut().find(|p| p.name == "xformOpOrder") {
Some(order) => {
if let UsdValue::Array(items) = &mut order.value {
items.push(UsdValue::Token(name.into()));
}
}
None => {
let mut order = attribute(
"token[]",
"xformOpOrder",
UsdValue::Array(vec![UsdValue::Token(name.into())]),
);
order.uniform = true;
prim.properties.push(order);
}
}
}
fn prim_at_mut<'a>(layer: &'a mut UsdLayer, path: &str) -> Option<&'a mut UsdPrim> {
let mut parts = path.trim_start_matches('/').split('/');
let first = parts.next()?;
let mut current = layer.prims.iter_mut().find(|p| p.name == first)?;
for part in parts {
current = current.children.iter_mut().find(|p| p.name == part)?;
}
Some(current)
}
#[cfg(test)]
mod external {
use super::super::shade;
use super::*;
#[test]
#[ignore = "writes files for external validation"]
fn write_materials_for_openusd() {
use crate::core::{BufferAttribute, BufferGeometry, Mesh, Object3D, ObjectArena};
use crate::materials::{
BasicMaterial, LambertMaterial, Material, PhongMaterial, PhysicalMaterial,
StandardMaterial, ToonMaterial,
};
use crate::math::{Color, Vector3};
fn quad() -> BufferGeometry {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(
vec![-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.5, 0.5, 0.0, -0.5, 0.5, 0.0],
3,
),
);
g.set_attribute(
"normal",
BufferAttribute::new([0.0, 0.0, 1.0].repeat(4), 3),
);
g.set_attribute(
"uv",
BufferAttribute::new(vec![0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0], 2),
);
g.set_index(vec![0, 1, 2, 0, 2, 3]);
g
}
let dir = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp".into());
let basic = BasicMaterial {
opacity: 0.5,
..BasicMaterial::new(Color::new(0.9, 0.1, 0.1))
};
let lambert = LambertMaterial {
color: Color::new(0.1, 0.8, 0.2),
..Default::default()
};
let phong = PhongMaterial {
color: Color::new(0.2, 0.3, 0.9),
specular: Color::new(1.0, 1.0, 1.0),
..Default::default()
};
let standard = StandardMaterial {
roughness: 0.25,
metalness: 0.9,
emissive: Color::new(0.05, 0.0, 0.1),
..StandardMaterial::new(Color::new(0.8, 0.6, 0.1))
};
let physical = PhysicalMaterial {
color: Color::new(0.3, 0.7, 0.7),
roughness: 0.1,
ior: 1.45,
clearcoat: 0.8,
clearcoat_roughness: 0.05,
..Default::default()
};
let toon = ToonMaterial {
color: Color::new(0.7, 0.2, 0.7),
side: 2,
..Default::default()
};
use crate::textures::{Texture, TextureFormat, TextureWrap};
use std::sync::Arc;
let mut checker = Vec::new();
for y in 0..64u32 {
for x in 0..64u32 {
let on = ((x / 8) + (y / 8)) % 2 == 0;
let (r, g, b) = if on { (240, 240, 40) } else { (30, 30, 120) };
checker.extend_from_slice(&[r, g, b, 255]);
}
}
let map = Texture {
wrap_s: TextureWrap::Repeat,
wrap_t: TextureWrap::Repeat,
..Texture::new(64, 64, TextureFormat::Rgba8UnormSrgb, checker)
};
let normal = Texture::new(
2,
2,
TextureFormat::Rgba8Unorm,
[128, 128, 255, 255].repeat(4),
);
let textured = StandardMaterial {
roughness: 0.9,
map: Some(Arc::new(map)),
normal_map: Some(Arc::new(normal)),
..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
};
let kinds: Vec<(&str, Material)> = vec![
("Basic", basic.into()),
("Lambert", lambert.into()),
("Phong", phong.into()),
("Standard", standard.into()),
("Physical", physical.into()),
("Toon", toon.into()),
("Textured", textured.into()),
];
let mut arena = ObjectArena::new();
let mut roots = Vec::new();
for (i, (name, material)) in kinds.into_iter().enumerate() {
let mut object = Object3D::mesh(Mesh::new(quad(), material));
object.name = name.into();
object.position = Vector3::new(i as f32 * 1.2 - 3.0, 0.0, 0.0);
roots.push(arena.insert(object));
}
let out = super::super::UsdExport::scene(&arena, &roots);
let base = std::path::Path::new(&dir);
for name in ["materials.usda", "materials.usdc", "materials.usdz"] {
out.write_to(base.join(name), base).expect("writes");
}
println!(
"wrote materials.usda / .usdc / .usdz and {} texture(s) to {dir}",
out.textures.len()
);
}
#[test]
#[ignore = "reads a file produced by OpenUSD"]
fn read_materials_back_from_openusd() {
use crate::loaders::usd::scene::to_scene;
let path = std::env::var("USD_IN").expect("USD_IN=<a flattened gallery>");
let text = std::fs::read_to_string(&path).expect("readable");
let layer = super::super::parse::parse(&text).expect("parses");
let scene = to_scene(&layer);
let named = |want: &str| {
let found = scene
.arena
.get_objects_by_name(scene.roots[0], want)
.into_iter()
.next()
.unwrap_or_else(|| panic!("no object named {want}"));
scene.arena.get(found).unwrap().clone()
};
let material_of = |object: &crate::core::Object3D| match &object.kind {
ObjectKind::Mesh(mesh) => (*mesh.material).clone(),
other => panic!("{other:?} is not a mesh"),
};
match material_of(&named("Physical")) {
Material::Physical(p) => {
assert!((p.ior - 1.45).abs() < 1e-4, "ior came back {}", p.ior);
assert!((p.clearcoat - 0.8).abs() < 1e-4);
assert!((p.clearcoat_roughness - 0.05).abs() < 1e-4);
assert!((p.color.g - 0.7).abs() < 1e-4);
}
other => panic!("Physical came back as {other:?}"),
}
assert_eq!(material_of(&named("Toon")).side(), 2, "doubleSided lost");
assert!(
(material_of(&named("Lambert")).color().g - 0.8).abs() < 1e-4,
"Lambert lost its colour"
);
let textured = shade::bound_material_path(&layer, "/Root/Textured")
.and_then(|p| layer.prim_at(&p))
.map(|p| shade::resolve(p, &layer))
.expect("a bound material");
let slots: Vec<_> = textured.textures.iter().map(|t| t.slot).collect();
assert!(
slots.contains(&shade::TextureSlot::BaseColor)
&& slots.contains(&shade::TextureSlot::Normal),
"{slots:?}"
);
let normal = textured
.textures
.iter()
.find(|t| t.slot == shade::TextureSlot::Normal)
.unwrap();
assert_eq!(normal.scale, [2.0, 2.0, 2.0, 1.0]);
assert_eq!(normal.bias, [-1.0, -1.0, -1.0, 0.0]);
assert_eq!(normal.color_space, "raw");
println!("materials survived the trip through OpenUSD");
}
#[test]
#[ignore = "writes files for external validation"]
fn write_archives_for_arkit() {
use super::super::{scene_to_usdz, UsdzEntry};
use crate::core::{Mesh, Object3D, ObjectArena};
use crate::geometries::{BoxGeometry, SphereGeometry};
use crate::materials::{Material, StandardMaterial};
let dir = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp".into());
let mut arena = ObjectArena::new();
let mut roots = Vec::new();
for (i, geometry) in [
BoxGeometry::new(1.0, 2.0, 3.0),
SphereGeometry::new(1.0, 24, 12),
]
.into_iter()
.enumerate()
{
let mut object = Object3D::mesh(Mesh::new(
geometry,
Material::Standard(StandardMaterial::default()),
));
object.name = format!("Part{i}");
roots.push(arena.insert(object));
}
let png = include_bytes!("testdata/tiny.png").to_vec();
let archive = scene_to_usdz(
&arena,
&roots,
&[UsdzEntry {
name: "textures/albedo.png".into(),
data: png,
}],
);
let path = format!("{dir}/arkit_scene.usdz");
std::fs::write(&path, &archive).unwrap();
println!("wrote {path} ({} bytes)", archive.len());
}
#[test]
#[ignore = "writes a file for external validation"]
fn write_an_animated_document() {
use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget};
use crate::core::Object3D;
use crate::geometries::BoxGeometry;
use crate::math::{Quaternion, Vector3};
let mut arena = ObjectArena::new();
let mut object = Object3D::mesh(crate::core::Mesh::new(
BoxGeometry::new(1.0, 1.0, 1.0),
crate::materials::Material::Standard(Default::default()),
));
object.name = "Cube".into();
let id = arena.insert(object);
let clip = AnimationClip::new(
"spin",
2.0,
vec![
KeyframeTrack::vector(
id,
TrackTarget::Position,
vec![0.0, 1.0, 2.0],
vec![
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(3.0, 2.0, 0.0),
Vector3::new(6.0, 0.0, 0.0),
],
),
KeyframeTrack::quaternion(
id,
TrackTarget::Quaternion,
vec![0.0, 2.0],
vec![
Quaternion::identity(),
Quaternion::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
std::f32::consts::PI,
),
],
),
KeyframeTrack::vector(
id,
TrackTarget::Scale,
vec![0.0, 1.0, 2.0],
vec![
Vector3::new(1.0, 1.0, 1.0),
Vector3::new(2.0, 2.0, 2.0),
Vector3::new(1.0, 1.0, 1.0),
],
),
],
);
let text = animated_scene_to_usda(&arena, &[id], &[clip]);
let path = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp/threers_anim.usda".into());
std::fs::write(&path, text).unwrap();
println!("wrote {path}");
}
}