mod accessor;
mod animation;
mod decode;
mod material;
mod mesh;
mod repair;
mod rig;
#[cfg(all(test, feature = "fs"))]
#[allow(clippy::cast_precision_loss, reason = "test grids are small")]
mod tests;
pub(crate) use animation::{sample_after, width};
pub(crate) use repair::repaired;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Map, Value};
#[cfg(doc)]
use crate::document::Keep;
use crate::document::{Bounds, Counts, Document, Pose};
use crate::mesh::Mesh;
use crate::num::{f32_of, usize_of};
use crate::quat;
use crate::{Context as _, ErrorKind, Result};
use accessor::Tabs;
impl Document {
pub fn flatten(&self, pose: Pose) -> Result<Option<Mesh>> {
let mut r = Reader::new(self)?;
r.bind = pose == Pose::Bind;
r.pose(pose)?;
r.mesh()
}
pub fn flatten_nodes(&self, nodes: &[crate::rig::Trs]) -> Result<Option<Mesh>> {
let mut r = Reader::new(self)?;
for (p, n) in r.posed.iter_mut().zip(nodes) {
p.translation = Some(n.translation.map(f64::from));
p.rotation = Some(n.rotation.map(f64::from));
p.scale = Some(n.scale.map(f64::from));
p.given = true;
}
r.mesh()
}
pub fn read_floats(&self, accessor: usize) -> Result<(usize, Vec<f32>)> {
let mut r = Reader::bare(self);
r.draco_holding(accessor)?;
let a = r.acc(accessor)?;
let values = match a.n {
1 => r.read_acc(&a, [0.0])?.into_flattened(),
2 => r.read_acc(&a, [0.0; 2])?.into_flattened(),
3 => r.read_acc(&a, [0.0; 3])?.into_flattened(),
4 => r.read_acc(&a, [0.0; 4])?.into_flattened(),
9 => r.read_acc(&a, [0.0; 9])?.into_flattened(),
_ => r.read_acc(&a, [0.0; 16])?.into_flattened(),
};
Ok((a.n, values))
}
pub fn read_indices(&self, accessor: usize) -> Result<Vec<u32>> {
let mut r = Reader::bare(self);
r.draco_holding(accessor)?;
r.read_indices(accessor)
}
#[must_use]
pub fn counts(&self) -> Counts {
counts(&self.base, Tabs::of(self))
}
pub fn bounds(&self, pose: Pose) -> Result<Option<Bounds>> {
let mut r = Reader::new(self)?;
r.bind = pose == Pose::Bind;
r.pose(pose)?;
r.bounds()
}
#[must_use]
pub fn triangles(&self) -> usize {
self.counts().triangles
}
#[allow(clippy::cast_precision_loss, reason = "sample numbers are small")]
pub fn animation_bounds(&self, index: usize, samples: usize) -> Result<Option<Bounds>> {
let (first, last) = Reader::whole(self).span(index)?;
let n = samples.max(1);
let mut out: Option<Bounds> = None;
for k in 0..n {
let time = if k == 0 {
first
} else {
first + (last - first) * (k as f32 / (n - 1) as f32)
};
let Some(b) = self.bounds(Pose::Animation { index, time })? else {
continue;
};
out = Some(out.map_or(b, |o| Bounds {
min: std::array::from_fn(|c| o.min[c].min(b.min[c])),
max: std::array::from_fn(|c| o.max[c].max(b.max[c])),
}));
}
Ok(out)
}
}
fn counts(json: &Map<String, Value>, tabs: Tabs<'_>) -> Counts {
let mut c = Counts::default();
let Ok(order) = scene_order(json) else {
return c;
};
let meshes = list(json, "meshes");
let count = |a: usize| tabs.accessor_count(a).map_or(0, usize_of);
let mut add = |mesh: &Value, k: usize| {
for p in list(mesh.as_object().unwrap_or(&Map::new()), "primitives") {
let Some(pos) = p.get("attributes").and_then(|a| index(a, "POSITION")) else {
continue;
};
c.vertices += count(pos) * k;
let n = index(p, "indices").map_or_else(|| count(pos), count);
match p.get("mode").and_then(Value::as_u64).unwrap_or(4) {
0 => c.points += n * k,
1 => c.lines += n / 2 * k,
2 => c.lines += n * k,
3 => c.lines += n.saturating_sub(1) * k,
4 => c.triangles += n / 3 * k,
5 | 6 => c.triangles += n.saturating_sub(2) * k,
_ => {}
}
}
};
let Some(order) = order else {
for m in meshes {
add(m, 1);
}
return c;
};
let nodes = list(json, "nodes");
let mut skinned: HashSet<(usize, usize, Vec<u32>)> = HashSet::new();
for i in order {
let n = &nodes[i];
let Some(m) = index(n, "mesh") else { continue };
let Some(mesh) = meshes.get(m) else { continue };
let k = if let Some(skin) = index(n, "skin") {
let w: Vec<u32> = default_weights(n, mesh).iter().map(|x| x.to_bits()).collect();
if !skinned.insert((m, skin, w)) {
continue;
}
1
} else {
match instancing(n) {
None => 1,
Some(attrs) => ["TRANSLATION", "ROTATION", "SCALE"]
.iter()
.filter_map(|k| index(attrs, k))
.map(count)
.min()
.unwrap_or(0),
}
};
add(mesh, k);
}
c
}
fn instancing(node: &Value) -> Option<&Value> {
node.get("extensions")?
.get("EXT_mesh_gpu_instancing")?
.get("attributes")
}
fn default_weights(node: &Value, mesh: &Value) -> Vec<f32> {
weights_of(node.get("weights").or_else(|| mesh.get("weights")))
}
fn weights_of(w: Option<&Value>) -> Vec<f32> {
w.and_then(Value::as_array)
.map(|w| w.iter().map(|x| f32_of(x.as_f64().unwrap_or(0.0))).collect())
.unwrap_or_default()
}
#[derive(Default, Clone, Copy)]
struct NodeView<'v> {
mesh: Option<&'v Value>,
skin: Option<&'v Value>,
children: Option<&'v Value>,
matrix: Option<&'v Value>,
translation: Option<&'v Value>,
rotation: Option<&'v Value>,
scale: Option<&'v Value>,
weights: Option<&'v Value>,
extensions: Option<&'v Value>,
}
impl<'v> NodeView<'v> {
fn of(node: &'v Value) -> Self {
let mut v = Self::default();
for (k, x) in node.as_object().into_iter().flatten() {
let slot = match k.as_str() {
"mesh" => &mut v.mesh,
"skin" => &mut v.skin,
"children" => &mut v.children,
"matrix" => &mut v.matrix,
"translation" => &mut v.translation,
"rotation" => &mut v.rotation,
"scale" => &mut v.scale,
"weights" => &mut v.weights,
"extensions" => &mut v.extensions,
_ => continue,
};
*slot = Some(x);
}
v
}
fn children(&self) -> impl Iterator<Item = usize> + 'v {
self.children
.and_then(Value::as_array)
.map_or(&[][..], Vec::as_slice)
.iter()
.filter_map(Value::as_u64)
.map(usize_of)
}
}
fn children(nodes: &[Value]) -> Vec<bool> {
let mut child = vec![false; nodes.len()];
for n in nodes {
for c in ids(n, "children") {
if let Some(f) = child.get_mut(c) {
*f = true;
}
}
}
child
}
fn scene_order(json: &Map<String, Value>) -> Result<Option<Vec<usize>>> {
let nodes = list(json, "nodes");
let scenes = list(json, "scenes");
let roots: Vec<usize> = if scenes.is_empty() {
if nodes.is_empty() {
return Ok(None);
}
let child = children(nodes);
(0..nodes.len()).filter(|&i| !child[i]).collect()
} else {
let s = json.get("scene").and_then(Value::as_u64).map_or(0, usize_of);
list_of(
scenes
.get(s)
.context(ErrorKind::Corrupt, "glTF default scene doesn't exist")?,
"nodes",
)
};
let mut seen = vec![false; nodes.len()];
let mut order = Vec::new();
let mut stack: Vec<usize> = roots.into_iter().rev().collect();
while let Some(i) = stack.pop() {
if i >= nodes.len() || seen[i] {
continue;
}
seen[i] = true;
let visible = nodes[i]
.get("extensions")
.and_then(|e| e.get("KHR_node_visibility"))
.and_then(|v| v.get("visible"));
if visible == Some(&Value::Bool(false)) {
continue;
}
order.push(i);
if let Some(kids) = nodes[i].get("children").and_then(Value::as_array) {
stack.extend(kids.iter().rev().filter_map(Value::as_u64).map(usize_of));
}
}
Ok(Some(order))
}
pub(crate) use crate::formats::xform::col::{IDENTITY, M4, mul};
struct Use {
mesh: usize,
weights: Vec<f32>,
skin: Option<usize>,
transforms: Vec<M4>,
}
struct Reader<'d> {
doc: &'d Document,
json: &'d Map<String, Value>,
tabs: Tabs<'d>,
meshes: &'d [Value],
nodes: &'d [Value],
materials_json: &'d [Value],
textures: &'d [Value],
samplers: &'d [Value],
images_json: &'d [Value],
scratch: Vec<u8>,
meshopt: HashMap<usize, Vec<u8>>,
materials: Vec<Option<usize>>,
default_material: Option<usize>,
#[allow(clippy::option_option, reason = "untried and tried-but-failed are both cached")]
images: Vec<Option<Option<usize>>>,
world: Vec<M4>,
posed: Vec<Posed>,
bind: bool,
bound: Vec<Option<M4>>,
budget: usize,
point_budget: usize,
max_vertices: usize,
draco: Vec<(usize, Arc<[u8]>, u64, usize)>,
}
#[derive(Default, Clone)]
struct Posed {
translation: Option<[f64; 3]>,
rotation: Option<[f64; 4]>,
scale: Option<[f64; 3]>,
weights: Option<Vec<f32>>,
given: bool,
}
fn missing(key: &str, i: usize) -> String {
format!("glTF {key}[{i}] doesn't exist")
}
fn shape(kind: Option<&str>) -> Option<(usize, usize)> {
Some(match kind? {
"SCALAR" => (1, 1),
"VEC2" => (2, 2),
"VEC3" => (3, 3),
"VEC4" => (4, 4),
"MAT2" => (4, 2),
"MAT3" => (9, 3),
"MAT4" => (16, 4),
_ => return None,
})
}
fn list<'v>(obj: &'v Map<String, Value>, key: &str) -> &'v [Value] {
obj.get(key).and_then(Value::as_array).map_or(&[], Vec::as_slice)
}
fn at<'v>(v: &'v Value, path: &[&str]) -> Option<&'v Value> {
path.iter().try_fold(v, |v, k| v.get(k))
}
fn items<'v>(v: &'v Value, key: &str) -> &'v [Value] {
v.get(key).and_then(Value::as_array).map_or(&[], Vec::as_slice)
}
fn index(v: &Value, key: &str) -> Option<usize> {
v.get(key)?.as_u64().map(usize_of)
}
fn floats<const N: usize>(v: Option<&Value>, default: [f64; N]) -> [f64; N] {
let mut out = default;
if let Some(a) = v.and_then(Value::as_array).filter(|a| a.len() == N) {
for (o, x) in out.iter_mut().zip(a) {
*o = x.as_f64().unwrap_or(*o);
}
}
out
}
fn drawable(extension: &str) -> bool {
const DECODED: &[&str] = &[
"KHR_draco_mesh_compression",
"EXT_meshopt_compression",
"KHR_meshopt_compression",
"KHR_mesh_quantization",
"EXT_mesh_gpu_instancing",
"KHR_animation_pointer",
"KHR_node_visibility",
"KHR_gaussian_splatting",
];
const LOOKS: &[&str] = &[
"VRMC_",
"KHR_materials_",
"KHR_texture_",
"EXT_texture_",
"KHR_lights_",
"KHR_xmp",
"EXT_materials_",
"EXT_lights_",
"MSFT_texture_",
"MSFT_packing_",
"ADOBE_materials_",
"KHR_technique",
];
const ALSO: &[&str] = &["MSFT_lod", "VRM"];
DECODED.contains(&extension) || ALSO.contains(&extension) || LOOKS.iter().any(|p| extension.starts_with(p))
}
fn f32s<const N: usize>(v: Option<&Value>, default: [f32; N]) -> [f32; N] {
floats(v, default.map(f64::from)).map(f32_of)
}
impl<'d> Reader<'d> {
#[allow(clippy::unnecessary_wraps, reason = "it fails without the draco feature")]
fn new(doc: &'d Document) -> Result<Self> {
let json = doc.json();
#[cfg(not(feature = "draco"))]
ensure!(
!list(json, "extensionsRequired")
.iter()
.any(|e| e.as_str() == Some("KHR_draco_mesh_compression")),
FeatureDisabled,
"glTF uses Draco compression, which needs Polysmelt's `draco` feature"
);
if let Some(e) = list(json, "extensionsRequired")
.iter()
.filter_map(Value::as_str)
.find(|e| !drawable(e))
{
bail!(
Unsupported,
"glTF requires the `{e}` extension, which polysmelt can't draw"
);
}
Ok(Self::whole(doc))
}
fn bare(doc: &'d Document) -> Self {
Self::over(doc, &doc.base, Tabs::of(doc))
}
fn whole(doc: &'d Document) -> Self {
let json = doc.json();
Self::over(doc, json, Tabs::json(json))
}
fn over(doc: &'d Document, json: &'d Map<String, Value>, tabs: Tabs<'d>) -> Self {
let n = |key| list(json, key).len();
Self {
doc,
json,
tabs,
meshes: list(json, "meshes"),
nodes: list(json, "nodes"),
materials_json: list(json, "materials"),
textures: list(json, "textures"),
samplers: list(json, "samplers"),
images_json: list(json, "images"),
scratch: Vec::new(),
meshopt: HashMap::new(),
materials: vec![None; n("materials")],
default_material: None,
images: vec![None; n("images")],
world: Vec::new(),
posed: vec![Posed::default(); n("nodes")],
bind: false,
bound: Vec::new(),
budget: doc.max_triangles,
point_budget: doc.max_points,
max_vertices: doc.max_triangles.saturating_mul(3).max(if doc.lines_and_points {
doc.max_points
} else {
0
}),
draco: Vec::new(),
}
}
fn uses(&mut self) -> Result<Vec<Use>> {
let nodes = self.nodes;
let views: Vec<NodeView<'_>> = nodes.iter().map(NodeView::of).collect();
let mut world = vec![None::<M4>; nodes.len()];
let mut child = vec![false; nodes.len()];
for v in &views {
for c in v.children() {
if let Some(f) = child.get_mut(c) {
*f = true;
}
}
}
let mut stack: Vec<(usize, M4)> = (0..nodes.len()).filter(|&i| !child[i]).map(|i| (i, IDENTITY)).collect();
while let Some((i, parent)) = stack.pop() {
if world[i].is_some() {
continue;
}
let m = mul(&parent, &self.local(i, &views[i]));
world[i] = Some(m);
for c in views[i].children() {
if c < nodes.len() && world[c].is_none() {
stack.push((c, m));
}
}
}
let Some(order) = scene_order(self.json)? else {
return Ok((0..self.meshes.len())
.map(|mesh| Use {
mesh,
weights: Vec::new(),
skin: None,
transforms: vec![IDENTITY],
})
.collect());
};
let mut uses: Vec<Use> = Vec::new();
let mut seen: HashMap<(usize, Option<usize>, Vec<u32>), usize> = HashMap::new();
for i in order {
let n = &views[i];
let Some(mesh) = n.mesh.and_then(Value::as_u64).map(usize_of) else {
continue;
};
let skin = n.skin.and_then(Value::as_u64).map(usize_of);
let weights = match &self.posed[i].weights {
Some(w) => w.clone(),
None => weights_of(
n.weights
.or_else(|| self.meshes.get(mesh).and_then(|m| m.get("weights"))),
),
};
let w = world[i].unwrap_or(IDENTITY);
let transforms = if skin.is_some() {
vec![IDENTITY]
} else {
self.instances(n.extensions, &w)?
};
let key = (mesh, skin, weights.iter().map(|x| x.to_bits()).collect());
match seen.get(&key) {
Some(_) if skin.is_some() => {}
Some(&u) => uses[u].transforms.extend(transforms),
None => {
seen.insert(key, uses.len());
uses.push(Use {
mesh,
weights,
skin,
transforms,
});
}
}
}
self.world = world.into_iter().map(|w| w.unwrap_or(IDENTITY)).collect();
Ok(uses)
}
fn instances(&mut self, extensions: Option<&Value>, world: &M4) -> Result<Vec<M4>> {
let Some(attrs) = extensions
.and_then(|e| e.get("EXT_mesh_gpu_instancing"))
.and_then(|e| e.get("attributes"))
else {
return Ok(vec![*world]);
};
let get = |k: &str| index(attrs, k);
let t = get("TRANSLATION").map(|a| self.read(a, [0.0; 3])).transpose()?;
let r = get("ROTATION")
.map(|a| self.read(a, [0.0, 0.0, 0.0, 1.0]))
.transpose()?;
let s = get("SCALE").map(|a| self.read(a, [1.0; 3])).transpose()?;
let count = [
t.as_ref().map(Vec::len),
r.as_ref().map(Vec::len),
s.as_ref().map(Vec::len),
]
.into_iter()
.flatten()
.min()
.unwrap_or(0);
ensure!(
count <= self.doc.max_triangles,
LimitExceeded,
"glTF node has {count} instances"
);
Ok((0..count)
.map(|k| {
let t = t.as_ref().map_or([0.0; 3], |v| v[k].map(f64::from));
let r = r.as_ref().map_or([0.0, 0.0, 0.0, 1.0], |v| v[k].map(f64::from));
let s = s.as_ref().map_or([1.0; 3], |v| v[k].map(f64::from));
mul(world, &trs(t, r, s))
})
.collect())
}
}
fn ids<'v>(v: &'v Value, key: &str) -> impl Iterator<Item = usize> + 'v {
items(v, key).iter().filter_map(Value::as_u64).map(usize_of)
}
fn list_of(v: &Value, key: &str) -> Vec<usize> {
v.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_u64).map(usize_of).collect())
.unwrap_or_default()
}
pub(crate) fn trs(t: [f64; 3], q: [f64; 4], s: [f64; 3]) -> M4 {
let q = if quat::length(q) > 0.0 {
quat::unit_unchecked(q)
} else {
quat::IDENTITY
};
let r = quat::matrix(q);
let mut m = IDENTITY;
for col in 0..3 {
for row in 0..3 {
m[col * 4 + row] = r[col * 3 + row] * s[col];
}
}
m[12..15].copy_from_slice(&t);
m
}
pub(crate) fn affine_inverse(m: &M4) -> Option<M4> {
let det = det3(m);
if !(det.abs() > 1e-30 && det.is_finite()) {
return None;
}
let a = |r: usize, c: usize| m[c * 4 + r];
let mut out = IDENTITY;
for r in 0..3 {
for c in 0..3 {
let (r1, r2) = ((r + 1) % 3, (r + 2) % 3);
let (c1, c2) = ((c + 1) % 3, (c + 2) % 3);
out[r * 4 + c] = (a(r1, c1) * a(r2, c2) - a(r1, c2) * a(r2, c1)) / det;
}
}
for r in 0..3 {
out[12 + r] = -(0..3).map(|k| out[k * 4 + r] * m[12 + k]).sum::<f64>();
}
Some(out)
}
pub(crate) fn decompose(m: &M4) -> ([f64; 3], [f64; 4], [f64; 3]) {
let t = [m[12], m[13], m[14]];
let col = |c: usize| [m[c * 4], m[c * 4 + 1], m[c * 4 + 2]];
let len = |v: [f64; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
let mut s = [len(col(0)), len(col(1)), len(col(2))];
if det3(m) < 0.0 {
s[0] = -s[0];
}
if s.iter().any(|&x| !(x.abs() > 1e-30 && x.is_finite())) {
return (t, [0.0, 0.0, 0.0, 1.0], s.map(|x| if x.is_finite() { x } else { 0.0 }));
}
let q = quat::unit(quat::of_rotation_reciprocal(|row, c| m[c * 4 + row] / s[c]));
(t, q, s)
}
fn det3(m: &M4) -> f64 {
m[0] * (m[5] * m[10] - m[9] * m[6]) - m[4] * (m[1] * m[10] - m[9] * m[2]) + m[8] * (m[1] * m[6] - m[5] * m[2])
}
fn normal_matrix(m: &M4) -> [[f64; 3]; 3] {
let a = |r: usize, c: usize| m[c * 4 + r];
let sign = if det3(m) < 0.0 { -1.0 } else { 1.0 };
let mut n = [[0.0; 3]; 3];
for (r, row) in n.iter_mut().enumerate() {
for (c, x) in row.iter_mut().enumerate() {
let (r1, r2) = ((r + 1) % 3, (r + 2) % 3);
let (c1, c2) = ((c + 1) % 3, (c + 2) % 3);
*x = sign * (a(r1, c1) * a(r2, c2) - a(r1, c2) * a(r2, c1));
}
}
n
}