use std::cell::{OnceCell, RefCell};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use serde_json::Value;
use crate::animation::{AnimationClip, InterpolationMode, KeyframeTrack, SceneResolver};
use crate::core::{BufferAttribute, BufferGeometry, Index, Object3D, ObjectRef};
use crate::error::{Error, GltfError};
use crate::loaders::draco::{
self, DracoArray, DracoArrayType, DracoAttribute, DracoPrimitive, Request as DracoRequest,
};
use crate::loaders::meshopt::{self, Filter as MeshoptFilter, Mode as MeshoptMode};
use crate::loaders::{Ktx2Loader, TextureLoader};
use crate::materials::{MeshBasicNodeMaterial, Side};
use crate::math::ColorSpace;
use crate::math::{Color, Matrix4, Vector2};
use crate::objects::{Bone, Mesh, Skeleton, SkinnedMesh};
use crate::textures::{MinFilter, Texture, TextureFilter, Wrapping};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ComponentType {
Byte,
UnsignedByte,
Short,
UnsignedShort,
UnsignedInt,
Float,
}
impl ComponentType {
fn from_gl(value: i64) -> Result<Self, Error> {
Ok(match value {
5120 => Self::Byte,
5121 => Self::UnsignedByte,
5122 => Self::Short,
5123 => Self::UnsignedShort,
5125 => Self::UnsignedInt,
5126 => Self::Float,
other => return Err(GltfError::UnsupportedComponentType(other).into()),
})
}
pub fn byte_size(self) -> usize {
match self {
Self::Byte | Self::UnsignedByte => 1,
Self::Short | Self::UnsignedShort => 2,
Self::UnsignedInt | Self::Float => 4,
}
}
fn normalized_scale(self) -> f64 {
match self {
Self::Byte => 1.0 / 127.0,
Self::UnsignedByte => 1.0 / 255.0,
Self::Short => 1.0 / 32767.0,
Self::UnsignedShort => 1.0 / 65535.0,
Self::UnsignedInt | Self::Float => 1.0,
}
}
fn read(self, bytes: &[u8]) -> f64 {
match self {
Self::Byte => bytes[0] as i8 as f64,
Self::UnsignedByte => bytes[0] as f64,
Self::Short => i16::from_le_bytes([bytes[0], bytes[1]]) as f64,
Self::UnsignedShort => u16::from_le_bytes([bytes[0], bytes[1]]) as f64,
Self::UnsignedInt => {
u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f64
}
Self::Float => f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f64,
}
}
}
fn type_size(name: &str) -> Result<usize, Error> {
Ok(match name {
"SCALAR" => 1,
"VEC2" => 2,
"VEC3" => 3,
"VEC4" => 4,
"MAT2" => 4,
"MAT3" => 9,
"MAT4" => 16,
other => return Err(GltfError::UnsupportedAccessorType(other.to_string()).into()),
})
}
fn attribute_name(semantic: &str) -> String {
match semantic {
"POSITION" => "position".into(),
"NORMAL" => "normal".into(),
"TANGENT" => "tangent".into(),
"TEXCOORD_0" => "uv".into(),
"TEXCOORD_1" => "uv1".into(),
"TEXCOORD_2" => "uv2".into(),
"TEXCOORD_3" => "uv3".into(),
"COLOR_0" => "color".into(),
"WEIGHTS_0" => "skinWeight".into(),
"JOINTS_0" => "skinIndex".into(),
other => other.to_lowercase(),
}
}
fn path_property(path: &str) -> Option<&'static str> {
match path {
"scale" => Some("scale"),
"translation" => Some("position"),
"rotation" => Some("quaternion"),
"weights" => Some("morphTargetInfluences"),
_ => None,
}
}
pub(crate) fn sanitize_node_name(name: &str) -> String {
name.chars()
.map(|c| if c.is_whitespace() { '_' } else { c })
.filter(|c| !matches!(c, '[' | ']' | '.' | ':' | '/'))
.collect()
}
#[derive(Clone, Debug, Default)]
pub struct GltfMaterial {
pub name: String,
pub base_color_factor: [f64; 4],
pub base_color_texture: Option<GltfTextureRef>,
pub metallic_factor: f64,
pub roughness_factor: f64,
pub metallic_roughness_texture: Option<GltfTextureRef>,
pub normal_texture: Option<GltfTextureRef>,
pub normal_scale: f64,
pub occlusion_texture: Option<GltfTextureRef>,
pub occlusion_strength: Option<f64>,
pub emissive_texture: Option<GltfTextureRef>,
pub emissive_factor: [f64; 3],
pub alpha_mode: String,
pub alpha_cutoff: f64,
pub double_sided: bool,
pub extensions: Vec<String>,
pub ior: Option<f64>,
pub specular_factor: Option<f64>,
pub specular_color_factor: [f64; 3],
pub specular_color_texture: Option<GltfTextureRef>,
pub sheen: Option<GltfSheen>,
pub diffuse_roughness_factor: Option<f64>,
pub emissive_strength: Option<f64>,
pub anisotropy_strength: Option<f64>,
pub anisotropy_rotation: f64,
pub anisotropy_texture: Option<GltfTextureRef>,
pub iridescence: Option<GltfIridescence>,
pub iridescence_texture: Option<GltfTextureRef>,
pub iridescence_thickness_texture: Option<GltfTextureRef>,
pub clearcoat_factor: Option<f64>,
pub clearcoat_roughness_factor: f64,
pub clearcoat_texture: Option<GltfTextureRef>,
pub clearcoat_roughness_texture: Option<GltfTextureRef>,
pub clearcoat_normal_texture: Option<GltfTextureRef>,
pub clearcoat_normal_scale: f64,
pub transmission_factor: Option<f64>,
pub transmission_texture: Option<GltfTextureRef>,
pub thickness_factor: Option<f64>,
pub thickness_texture: Option<GltfTextureRef>,
pub attenuation_distance: f64,
pub attenuation_color: [f64; 3],
}
#[derive(Clone, Copy, Debug)]
pub struct GltfIridescence {
pub factor: f64,
pub ior: f64,
pub thickness_range: [f64; 2],
}
#[derive(Clone, Copy, Debug)]
pub struct GltfSheen {
pub color_factor: [f64; 3],
pub roughness_factor: f64,
}
#[derive(Clone, Debug)]
pub struct GltfTextureRef {
pub index: usize,
pub tex_coord: Option<usize>,
pub transform: Option<GltfTextureTransform>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct GltfTextureTransform {
pub offset: Option<[f64; 2]>,
pub rotation: Option<f64>,
pub scale: Option<[f64; 2]>,
pub tex_coord: Option<usize>,
}
impl GltfTextureRef {
fn parse(def: Option<&Value>) -> Option<Self> {
let def = def?;
let index = def.get("index").and_then(Value::as_u64)? as usize;
let transform =
def.pointer("/extensions/KHR_texture_transform")
.map(|t| GltfTextureTransform {
offset: pair(t.get("offset")),
rotation: t.get("rotation").and_then(Value::as_f64),
scale: pair(t.get("scale")),
tex_coord: t
.get("texCoord")
.and_then(Value::as_u64)
.map(|v| v as usize),
});
Some(Self {
index,
tex_coord: def
.get("texCoord")
.and_then(Value::as_u64)
.map(|v| v as usize),
transform,
})
}
}
fn pair(value: Option<&Value>) -> Option<[f64; 2]> {
let array = value?.as_array()?;
Some([
array.first().and_then(Value::as_f64)?,
array.get(1).and_then(Value::as_f64)?,
])
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct MaterialVariant {
material: usize,
use_derivative_tangents: bool,
use_vertex_colors: bool,
use_flat_shading: bool,
}
#[derive(Clone, Debug)]
pub struct GltfImage {
pub name: String,
pub mime_type: Option<String>,
pub uri: Option<String>,
pub data: Vec<u8>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct GltfTexture {
pub source: Option<usize>,
pub sampler: Option<usize>,
pub basisu_source: Option<usize>,
}
pub struct GltfPrimitive {
pub node: ObjectRef,
pub geometry: Rc<BufferGeometry>,
pub material: Option<usize>,
pub skin: Option<usize>,
pub morph_target_influences: Rc<RefCell<Vec<f64>>>,
pub morph_target_dictionary: Vec<(String, usize)>,
}
pub struct Gltf {
pub scene: ObjectRef,
pub scenes: Vec<ObjectRef>,
pub nodes: Vec<ObjectRef>,
pub animations: Vec<AnimationClip>,
pub skins: Vec<Rc<RefCell<Skeleton>>>,
pub primitives: Vec<GltfPrimitive>,
pub skinned_meshes: Vec<ObjectRef>,
pub materials: Vec<GltfMaterial>,
pub textures: Vec<GltfTexture>,
pub images: Vec<GltfImage>,
pub asset: Value,
pub json: Value,
}
impl Gltf {
pub fn scene_resolver(&self) -> SceneResolver {
let mut resolver = SceneResolver::new(self.scene.clone());
for primitive in &self.primitives {
resolver.add_morph_target_influences(
&primitive.node,
primitive.morph_target_influences.clone(),
);
}
resolver
}
pub fn primitive(&self, node: &ObjectRef) -> Option<&GltfPrimitive> {
self.primitives
.iter()
.find(|primitive| ObjectRef::ptr_eq(&primitive.node, node))
}
}
pub struct GltfLoader {
json: Value,
glb_buffer: Option<Vec<u8>>,
buffers: Vec<Vec<u8>>,
meshopt_views: Vec<OnceCell<Vec<u8>>>,
base: PathBuf,
node_names_used: HashMap<String, usize>,
ktx2_loader: Ktx2Loader,
}
impl GltfLoader {
pub fn load(path: impl AsRef<Path>) -> Result<Gltf, Error> {
Self::open(path.as_ref(), true)?.build()
}
pub fn load_with_ktx2(path: impl AsRef<Path>, ktx2_loader: &Ktx2Loader) -> Result<Gltf, Error> {
let mut loader = Self::open(path.as_ref(), true)?;
loader.ktx2_loader = ktx2_loader.clone();
loader.build()
}
pub fn parse(data: &[u8], base: PathBuf) -> Result<Gltf, Error> {
Self::read(data, base, true)?.build()
}
pub fn parse_with_ktx2(
data: &[u8],
base: PathBuf,
ktx2_loader: &Ktx2Loader,
) -> Result<Gltf, Error> {
let mut loader = Self::read(data, base, true)?;
loader.ktx2_loader = ktx2_loader.clone();
loader.build()
}
fn open(path: &Path, check_extensions: bool) -> Result<Self, Error> {
let data = crate::io::read(path)?;
let base = path.parent().unwrap_or(Path::new(".")).to_path_buf();
Self::read(&data, base, check_extensions)
}
fn read(data: &[u8], base: PathBuf, check_extensions: bool) -> Result<Self, Error> {
let (json, glb_buffer) = if data.len() >= 4 && &data[0..4] == b"glTF" {
let (json, bin) = parse_glb(data)?;
(json, bin)
} else {
let text = std::str::from_utf8(data).map_err(|_| GltfError::NotUtf8)?;
let json: Value =
serde_json::from_str(text).map_err(|source| Error::Json { path: None, source })?;
(json, None)
};
if let Some(version) = json
.pointer("/asset/version")
.and_then(Value::as_str)
.and_then(|v| v.split('.').next().map(str::to_string))
{
if version != "2" {
return Err(GltfError::UnsupportedVersion(version).into());
}
}
if check_extensions {
check_required_extensions(&json)?;
}
let view_count = json
.get("bufferViews")
.and_then(Value::as_array)
.map_or(0, Vec::len);
let mut loader = Self {
json,
glb_buffer,
buffers: Vec::new(),
meshopt_views: (0..view_count).map(|_| OnceCell::new()).collect(),
base,
node_names_used: HashMap::new(),
ktx2_loader: Ktx2Loader::new(),
};
loader.load_buffers()?;
Ok(loader)
}
fn load_buffers(&mut self) -> Result<(), Error> {
let buffers = self
.json
.get("buffers")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
for buffer in &buffers {
match buffer.get("uri").and_then(Value::as_str) {
None if buffer.pointer("/extensions/EXT_meshopt_compression/fallback")
== Some(&Value::Bool(true)) =>
{
self.buffers.push(Vec::new());
}
None => {
let bin = self.glb_buffer.clone().ok_or(GltfError::NoBinChunk)?;
self.buffers.push(bin);
}
Some(uri) if uri.starts_with("data:") => {
self.buffers.push(decode_data_uri(uri)?);
}
Some(uri) => {
let path = self.base.join(uri);
self.buffers.push(crate::io::read(&path)?);
}
}
}
Ok(())
}
fn buffer_view(&self, index: usize) -> Result<&[u8], Error> {
let view =
self.json
.pointer(&format!("/bufferViews/{index}"))
.ok_or(GltfError::MissingIndex {
kind: "bufferView",
index,
})?;
if let Some(extension) = view.pointer("/extensions/EXT_meshopt_compression") {
return self.meshopt_buffer_view(index, extension);
}
self.buffer_range(
index,
json_usize(view, "buffer").unwrap_or(0),
json_usize(view, "byteOffset").unwrap_or(0),
json_usize(view, "byteLength").unwrap_or(0),
)
}
fn buffer_range(
&self,
index: usize,
buffer: usize,
offset: usize,
length: usize,
) -> Result<&[u8], Error> {
let buffer = self.buffers.get(buffer).ok_or(GltfError::MissingIndex {
kind: "buffer",
index: buffer,
})?;
offset
.checked_add(length)
.and_then(|end| buffer.get(offset..end))
.ok_or_else(|| GltfError::BufferViewOutOfRange { index }.into())
}
fn meshopt_buffer_view(&self, index: usize, extension: &Value) -> Result<&[u8], Error> {
let cell = &self.meshopt_views[index];
if let Some(decoded) = cell.get() {
return Ok(decoded);
}
let error = |reason: String| -> Error {
GltfError::Meshopt {
buffer_view: index,
reason,
}
.into()
};
let field = |key: &'static str| {
json_usize(extension, key).ok_or(GltfError::MissingField {
what: match key {
"buffer" => "EXT_meshopt_compression.buffer",
"count" => "EXT_meshopt_compression.count",
_ => "EXT_meshopt_compression.byteStride",
},
})
};
let source = self.buffer_range(
index,
field("buffer")?,
json_usize(extension, "byteOffset").unwrap_or(0),
json_usize(extension, "byteLength").unwrap_or(0),
)?;
let mode = extension.get("mode").and_then(Value::as_str).unwrap_or("");
let mode =
MeshoptMode::parse(mode).ok_or_else(|| error(format!("unknown mode {mode:?}")))?;
let filter = extension
.get("filter")
.and_then(Value::as_str)
.unwrap_or("NONE");
let filter = MeshoptFilter::parse(filter)
.ok_or_else(|| error(format!("unknown filter {filter:?}")))?;
let decoded = meshopt::decode_gltf_buffer(
field("count")?,
field("byteStride")?,
source,
mode,
filter,
)
.map_err(error)?;
Ok(cell.get_or_init(|| decoded))
}
#[doc(hidden)]
pub fn meshopt_buffer_views(path: impl AsRef<Path>) -> Result<Vec<(usize, Vec<u8>)>, Error> {
let loader = Self::open(path.as_ref(), false)?;
let mut out = Vec::new();
for (index, view) in loader
.json
.get("bufferViews")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
{
if view
.pointer("/extensions/EXT_meshopt_compression")
.is_some()
{
out.push((index, loader.buffer_view(index)?.to_vec()));
}
}
Ok(out)
}
#[doc(hidden)]
pub fn accessors(path: impl AsRef<Path>) -> Result<Vec<(Vec<f64>, usize)>, Error> {
let loader = Self::open(path.as_ref(), false)?;
let count = loader
.json
.get("accessors")
.and_then(Value::as_array)
.map_or(0, Vec::len);
(0..count).map(|index| loader.accessor(index)).collect()
}
fn buffer_view_stride(&self, index: usize) -> Option<usize> {
self.json
.pointer(&format!("/bufferViews/{index}"))
.and_then(|view| json_usize(view, "byteStride"))
}
pub(crate) fn accessor(&self, index: usize) -> Result<(Vec<f64>, usize), Error> {
let accessor = self
.json
.pointer(&format!("/accessors/{index}"))
.ok_or(GltfError::MissingIndex {
kind: "accessor",
index,
})?
.clone();
let item_size = type_size(accessor.get("type").and_then(Value::as_str).ok_or(
GltfError::MissingField {
what: "accessor type",
},
)?)?;
let component_type = ComponentType::from_gl(
accessor
.get("componentType")
.and_then(Value::as_i64)
.ok_or(GltfError::MissingField {
what: "accessor componentType",
})?,
)?;
let count = json_usize(&accessor, "count").unwrap_or(0);
let normalized = accessor
.get("normalized")
.and_then(Value::as_bool)
.unwrap_or(false);
let mut values = vec![0.0; count * item_size];
if let Some(view_index) = json_usize(&accessor, "bufferView") {
let bytes = self.buffer_view(view_index)?;
let element_size = component_type.byte_size();
let default_stride = element_size * item_size;
let stride = self
.buffer_view_stride(view_index)
.unwrap_or(default_stride);
let offset = json_usize(&accessor, "byteOffset").unwrap_or(0);
for i in 0..count {
for c in 0..item_size {
let at = offset + i * stride + c * element_size;
values[i * item_size + c] = component_type.read(&bytes[at..at + element_size]);
}
}
}
if let Some(sparse) = accessor.get("sparse") {
let sparse_count = json_usize(sparse, "count").unwrap_or(0);
let indices_type = ComponentType::from_gl(
sparse
.pointer("/indices/componentType")
.and_then(Value::as_i64)
.ok_or(GltfError::MissingField {
what: "sparse indices componentType",
})?,
)?;
let indices_view = sparse
.pointer("/indices/bufferView")
.and_then(Value::as_u64)
.ok_or(GltfError::MissingField {
what: "sparse indices bufferView",
})? as usize;
let indices_offset = sparse
.pointer("/indices/byteOffset")
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let values_view = sparse
.pointer("/values/bufferView")
.and_then(Value::as_u64)
.ok_or(GltfError::MissingField {
what: "sparse values bufferView",
})? as usize;
let values_offset = sparse
.pointer("/values/byteOffset")
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let index_bytes = self.buffer_view(indices_view)?.to_vec();
let value_bytes = self.buffer_view(values_view)?.to_vec();
let index_size = indices_type.byte_size();
let value_size = component_type.byte_size();
for i in 0..sparse_count {
let at = indices_offset + i * index_size;
let target = indices_type.read(&index_bytes[at..at + index_size]) as usize;
for c in 0..item_size {
let at = values_offset + (i * item_size + c) * value_size;
values[target * item_size + c] =
component_type.read(&value_bytes[at..at + value_size]);
}
}
}
if normalized {
let scale = component_type.normalized_scale();
for value in &mut values {
*value *= scale;
}
}
Ok((values, item_size))
}
pub(crate) fn attribute(&self, index: usize) -> Result<BufferAttribute, Error> {
let (values, item_size) = self.accessor(index)?;
Ok(BufferAttribute::new(
values.iter().map(|&v| v as f32).collect(),
item_size,
))
}
fn index_attribute(&self, index: usize) -> Result<Index, Error> {
let (values, _) = self.accessor(index)?;
let component_type = self
.json
.pointer(&format!("/accessors/{index}/componentType"))
.and_then(Value::as_i64)
.map(ComponentType::from_gl)
.transpose()?;
Ok(match component_type {
Some(ComponentType::UnsignedInt) => {
Index::U32(values.iter().map(|&v| v as u32).collect())
}
_ => Index::U16(values.iter().map(|&v| v as u16).collect()),
})
}
fn build(&mut self) -> Result<Gltf, Error> {
let materials = self.load_materials();
let textures = self.load_textures();
let images = self.load_images()?;
let node_defs = self
.json
.get("nodes")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut joints = vec![false; node_defs.len()];
if let Some(skins) = self.json.get("skins").and_then(Value::as_array) {
for skin in skins {
for joint in skin
.get("joints")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
if let Some(joint) = joint.as_u64() {
joints[joint as usize] = true;
}
}
}
}
let mut nodes = Vec::with_capacity(node_defs.len());
for (index, node_def) in node_defs.iter().enumerate() {
let name = match node_def.get("name").and_then(Value::as_str) {
Some(name) if !name.is_empty() => self.create_unique_name(Some(name)),
_ => String::new(),
};
let node = if joints[index] {
Bone::new()
} else {
Object3D::new_node()
};
{
let mut object = node.borrow_mut();
object.name = name;
apply_node_transform(&mut object, node_def);
}
nodes.push(node);
}
for (index, node_def) in node_defs.iter().enumerate() {
for child in node_def
.get("children")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
if let Some(child) = child.as_u64() {
nodes[index].add(&nodes[child as usize]);
}
}
}
let mut skins = Vec::new();
for skin_def in self
.json
.get("skins")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
{
let inverse_bind_matrices = match json_usize(&skin_def, "inverseBindMatrices") {
Some(accessor) => Some(self.accessor(accessor)?.0),
None => None,
};
let mut bones = Vec::new();
let mut bone_inverses = Vec::new();
for (i, joint) in skin_def
.get("joints")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
.iter()
.enumerate()
{
let Some(joint) = joint.as_u64().map(|j| j as usize) else {
continue;
};
let Some(node) = nodes.get(joint) else {
continue;
};
bones.push(node.clone());
let mut matrix = Matrix4::identity();
if let Some(values) = &inverse_bind_matrices {
matrix.from_array(values, i * 16);
}
bone_inverses.push(matrix);
}
skins.push(Rc::new(RefCell::new(Skeleton::new(
bones,
Some(bone_inverses),
))));
}
let mut primitives = Vec::new();
for (index, node_def) in node_defs.iter().enumerate() {
let Some(mesh) = json_usize(node_def, "mesh") else {
continue;
};
let skin = json_usize(node_def, "skin");
primitives.extend(self.load_mesh(mesh, &nodes[index], skin)?);
}
let scenes = self.load_scenes(&nodes);
for scene in &scenes {
scene.update_matrix_world(true);
}
let mut skinned_meshes = Vec::new();
let mut texture_cache: HashMap<usize, Texture> = HashMap::new();
let mut material_cache: HashMap<MaterialVariant, MeshBasicNodeMaterial> = HashMap::new();
for primitive in &primitives {
let material = self.final_material(
&mut texture_cache,
&mut material_cache,
primitive,
&materials,
&textures,
&images,
)?;
let node = primitive.node.clone();
let Some(skin) = primitive.skin else {
let mut mesh = Mesh::of(primitive.geometry.clone(), material);
mesh.morph_target_influences = primitive.morph_target_influences.borrow().clone();
let mut object = node.borrow_mut();
object.object_type = "Mesh";
object.payload = crate::objects::Payload::Mesh(mesh);
continue;
};
let mut mesh = SkinnedMesh::of(primitive.geometry.clone(), material);
mesh.morph_target_influences = primitive.morph_target_influences.clone();
mesh.morph_target_dictionary = primitive.morph_target_dictionary.clone();
mesh.normalize_skin_weights();
{
let mut object = node.borrow_mut();
object.object_type = "SkinnedMesh";
object.payload = crate::objects::Payload::SkinnedMesh(Box::new(mesh));
}
SkinnedMesh::bind(&node, skins[skin].clone(), Some(Matrix4::identity()));
skinned_meshes.push(node);
}
let animations = self.load_animations(&nodes)?;
let scene_index = json_usize(&self.json, "scene").unwrap_or(0);
let scene = scenes
.get(scene_index)
.cloned()
.ok_or(GltfError::MissingField { what: "scenes" })?;
Ok(Gltf {
scene,
scenes,
nodes,
animations,
skins,
primitives,
skinned_meshes,
materials,
textures,
images,
asset: self.json.get("asset").cloned().unwrap_or(Value::Null),
json: self.json.clone(),
})
}
fn create_unique_name(&mut self, original: Option<&str>) -> String {
let sanitized = sanitize_node_name(original.unwrap_or(""));
match self.node_names_used.get_mut(&sanitized) {
Some(count) => {
*count += 1;
format!("{sanitized}_{count}")
}
None => {
self.node_names_used.insert(sanitized.clone(), 1);
sanitized
}
}
}
fn load_scenes(&self, nodes: &[ObjectRef]) -> Vec<ObjectRef> {
let mut scenes = Vec::new();
for scene_def in self
.json
.get("scenes")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
let scene = Object3D::new_node();
if let Some(name) = scene_def.get("name").and_then(Value::as_str) {
scene.borrow_mut().name = sanitize_node_name(name);
}
scene.borrow_mut().object_type = "Group";
for node in scene_def
.get("nodes")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
if let Some(node) = node.as_u64().and_then(|i| nodes.get(i as usize)) {
scene.add(node);
}
}
scenes.push(scene);
}
scenes
}
fn load_mesh(
&self,
index: usize,
node: &ObjectRef,
skin: Option<usize>,
) -> Result<Vec<GltfPrimitive>, Error> {
let mesh_def = self
.json
.pointer(&format!("/meshes/{index}"))
.ok_or(GltfError::MissingIndex {
kind: "mesh",
index,
})?
.clone();
let primitive_defs = mesh_def
.get("primitives")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let weights: Vec<f64> = mesh_def
.get("weights")
.and_then(Value::as_array)
.map(|w| w.iter().filter_map(Value::as_f64).collect())
.unwrap_or_default();
let target_names: Vec<String> = mesh_def
.pointer("/extras/targetNames")
.and_then(Value::as_array)
.map(|names| {
names
.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default();
let mut out = Vec::new();
let mesh_name = node.borrow().name.clone();
for (i, primitive) in primitive_defs.iter().enumerate() {
let mut geometry = BufferGeometry::new();
if let Some(draco) = self.draco_primitive(index, i, primitive)? {
for attribute in &draco.attributes {
geometry.set_attribute(&attribute.name, draco_buffer_attribute(attribute));
}
geometry.index = draco.index.map(Index::U32);
}
for (semantic, accessor) in primitive
.get("attributes")
.and_then(Value::as_object)
.cloned()
.unwrap_or_default()
{
let Some(accessor) = accessor.as_u64() else {
continue;
};
let name = attribute_name(&semantic);
if geometry.get_attribute(&name).is_some() {
continue;
}
let mut attribute = self.attribute(accessor as usize)?;
if name == "skinIndex" {
let values = attribute.array().iter().map(|v| *v as u32).collect();
attribute = BufferAttribute::uint32(values, attribute.item_size, false);
}
geometry.set_attribute(&name, attribute);
}
if let (Some(accessor), None) = (json_usize(primitive, "indices"), &geometry.index) {
geometry.index = Some(self.index_attribute(accessor)?);
}
let targets = primitive
.get("targets")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
if !targets.is_empty() {
geometry.morph_targets_relative = true;
for semantic in ["POSITION", "NORMAL", "TANGENT"] {
if !targets.iter().any(|target| target.get(semantic).is_some()) {
continue;
}
let mut attributes = Vec::new();
for target in &targets {
match json_usize(target, semantic) {
Some(accessor) => attributes.push(self.attribute(accessor)?),
None => {
let item_size = match semantic {
"TANGENT" => 4,
_ => 3,
};
let count = geometry
.get_attribute(&attribute_name(semantic))
.map(BufferAttribute::count)
.unwrap_or(0);
attributes.push(BufferAttribute::new(
vec![0.0; count * item_size],
item_size,
));
}
}
}
geometry.set_morph_attribute(&attribute_name(semantic), attributes);
}
}
let primitive_node = if primitive_defs.len() == 1 {
node.clone()
} else {
let child = Object3D::new_node();
child.borrow_mut().name = format!("{mesh_name}_{i}");
node.add(&child);
child
};
let morph_target_influences = if targets.is_empty() {
Vec::new()
} else if weights.is_empty() {
vec![0.0; targets.len()]
} else {
weights.clone()
};
out.push(GltfPrimitive {
node: primitive_node,
geometry: Rc::new(geometry),
material: json_usize(primitive, "material"),
skin,
morph_target_influences: Rc::new(RefCell::new(morph_target_influences)),
morph_target_dictionary: target_names
.iter()
.cloned()
.enumerate()
.map(|(i, name)| (name, i))
.collect(),
});
}
Ok(out)
}
fn draco_primitive(
&self,
mesh: usize,
index: usize,
primitive: &Value,
) -> Result<Option<DracoPrimitive>, Error> {
let Some(extension) = primitive.pointer("/extensions/KHR_draco_mesh_compression") else {
return Ok(None);
};
let draco_error = |reason: String| -> Error {
GltfError::Draco {
mesh,
primitive: index,
reason,
}
.into()
};
let buffer_view = json_usize(extension, "bufferView").ok_or(GltfError::MissingField {
what: "KHR_draco_mesh_compression.bufferView",
})?;
let accessors = primitive.get("attributes").and_then(Value::as_object);
let mut requests = Vec::new();
for (semantic, unique_id) in extension
.get("attributes")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
let name = attribute_name(semantic);
let unique_id = unique_id
.as_u64()
.and_then(|id| u32::try_from(id).ok())
.ok_or_else(|| draco_error(format!("bad unique id for {semantic}")))?;
let accessor = accessors
.and_then(|accessors| accessors.get(semantic))
.and_then(Value::as_u64)
.and_then(|accessor| self.json.pointer(&format!("/accessors/{accessor}")))
.ok_or_else(|| {
draco_error(format!("{semantic} has no accessor to take a type from"))
})?;
let component_type = accessor
.get("componentType")
.and_then(Value::as_u64)
.unwrap_or(0);
let array_type = DracoArrayType::from_component_type(component_type)
.ok_or(GltfError::UnsupportedComponentType(component_type as i64))?;
requests.push(DracoRequest {
name,
unique_id,
array_type,
normalized: accessor.get("normalized").and_then(Value::as_bool) == Some(true),
});
}
let data = self.buffer_view(buffer_view)?;
draco::decode_primitive(data, &requests)
.map(Some)
.map_err(draco_error)
}
#[doc(hidden)]
pub fn draco_primitives(
path: impl AsRef<Path>,
) -> Result<Vec<(usize, usize, DracoPrimitive)>, Error> {
let loader = Self::open(path.as_ref(), false)?;
let mut out = Vec::new();
for (m, mesh) in loader
.json
.get("meshes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
{
for (p, primitive) in mesh
.get("primitives")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
{
if let Some(draco) = loader.draco_primitive(m, p, primitive)? {
out.push((m, p, draco));
}
}
}
Ok(out)
}
fn load_materials(&self) -> Vec<GltfMaterial> {
let mut materials = Vec::new();
for material_def in self
.json
.get("materials")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
let pbr = material_def.get("pbrMetallicRoughness");
let base_color_factor = pbr
.and_then(|pbr| pbr.get("baseColorFactor"))
.and_then(Value::as_array)
.map(|v| {
let mut out = [1.0; 4];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(value) = v.get(i).and_then(Value::as_f64) {
*slot = value;
}
}
out
})
.unwrap_or([1.0; 4]);
let emissive_factor = material_def
.get("emissiveFactor")
.and_then(Value::as_array)
.map(|v| {
let mut out = [0.0; 3];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(value) = v.get(i).and_then(Value::as_f64) {
*slot = value;
}
}
out
})
.unwrap_or([0.0; 3]);
materials.push(GltfMaterial {
name: material_def
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
base_color_factor,
base_color_texture: GltfTextureRef::parse(
pbr.and_then(|pbr| pbr.get("baseColorTexture")),
),
metallic_factor: pbr
.and_then(|pbr| pbr.get("metallicFactor"))
.and_then(Value::as_f64)
.unwrap_or(1.0),
roughness_factor: pbr
.and_then(|pbr| pbr.get("roughnessFactor"))
.and_then(Value::as_f64)
.unwrap_or(1.0),
metallic_roughness_texture: GltfTextureRef::parse(
pbr.and_then(|pbr| pbr.get("metallicRoughnessTexture")),
),
normal_texture: GltfTextureRef::parse(material_def.get("normalTexture")),
normal_scale: material_def
.pointer("/normalTexture/scale")
.and_then(Value::as_f64)
.unwrap_or(1.0),
occlusion_texture: GltfTextureRef::parse(material_def.get("occlusionTexture")),
occlusion_strength: material_def
.pointer("/occlusionTexture/strength")
.and_then(Value::as_f64),
emissive_texture: GltfTextureRef::parse(material_def.get("emissiveTexture")),
emissive_factor,
alpha_mode: material_def
.get("alphaMode")
.and_then(Value::as_str)
.unwrap_or("OPAQUE")
.to_string(),
alpha_cutoff: material_def
.get("alphaCutoff")
.and_then(Value::as_f64)
.unwrap_or(0.5),
double_sided: material_def
.get("doubleSided")
.and_then(Value::as_bool)
.unwrap_or(false),
extensions: material_def
.get("extensions")
.and_then(Value::as_object)
.map(|map| map.keys().cloned().collect())
.unwrap_or_default(),
ior: material_def
.pointer("/extensions/KHR_materials_ior/ior")
.and_then(Value::as_f64),
specular_factor: material_def
.pointer("/extensions/KHR_materials_specular")
.map(|specular| {
specular
.get("specularFactor")
.and_then(Value::as_f64)
.unwrap_or(1.0)
}),
specular_color_factor: material_def
.pointer("/extensions/KHR_materials_specular/specularColorFactor")
.and_then(Value::as_array)
.map(|v| {
let mut out = [1.0; 3];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(value) = v.get(i).and_then(Value::as_f64) {
*slot = value;
}
}
out
})
.unwrap_or([1.0; 3]),
specular_color_texture: GltfTextureRef::parse(
material_def.pointer("/extensions/KHR_materials_specular/specularColorTexture"),
),
sheen: material_def
.pointer("/extensions/KHR_materials_sheen")
.map(|sheen| GltfSheen {
color_factor: sheen
.get("sheenColorFactor")
.and_then(Value::as_array)
.map(|v| {
let mut out = [0.0; 3];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(value) = v.get(i).and_then(Value::as_f64) {
*slot = value;
}
}
out
})
.unwrap_or([0.0; 3]),
roughness_factor: sheen
.get("sheenRoughnessFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0),
}),
diffuse_roughness_factor: material_def
.pointer("/extensions/KHR_materials_diffuse_roughness")
.map(|extension| {
extension
.get("diffuseRoughnessFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0)
}),
emissive_strength: material_def
.pointer("/extensions/KHR_materials_emissive_strength/emissiveStrength")
.and_then(Value::as_f64),
anisotropy_strength: material_def
.pointer("/extensions/KHR_materials_anisotropy")
.map(|ext| {
ext.get("anisotropyStrength")
.and_then(Value::as_f64)
.unwrap_or(0.0)
}),
anisotropy_rotation: material_def
.pointer("/extensions/KHR_materials_anisotropy/anisotropyRotation")
.and_then(Value::as_f64)
.unwrap_or(0.0),
anisotropy_texture: GltfTextureRef::parse(
material_def.pointer("/extensions/KHR_materials_anisotropy/anisotropyTexture"),
),
iridescence: material_def
.pointer("/extensions/KHR_materials_iridescence")
.map(|ext| {
let field = |name: &str, default: f64| {
ext.get(name).and_then(Value::as_f64).unwrap_or(default)
};
GltfIridescence {
factor: field("iridescenceFactor", 0.0),
ior: field("iridescenceIor", 1.3),
thickness_range: [
field("iridescenceThicknessMinimum", 100.0),
field("iridescenceThicknessMaximum", 400.0),
],
}
}),
iridescence_texture: GltfTextureRef::parse(
material_def
.pointer("/extensions/KHR_materials_iridescence/iridescenceTexture"),
),
iridescence_thickness_texture: GltfTextureRef::parse(
material_def.pointer(
"/extensions/KHR_materials_iridescence/iridescenceThicknessTexture",
),
),
clearcoat_factor: material_def
.pointer("/extensions/KHR_materials_clearcoat")
.map(|ext| {
ext.get("clearcoatFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0)
}),
clearcoat_roughness_factor: material_def
.pointer("/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0),
clearcoat_texture: GltfTextureRef::parse(
material_def.pointer("/extensions/KHR_materials_clearcoat/clearcoatTexture"),
),
clearcoat_roughness_texture: GltfTextureRef::parse(
material_def
.pointer("/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture"),
),
clearcoat_normal_texture: GltfTextureRef::parse(
material_def
.pointer("/extensions/KHR_materials_clearcoat/clearcoatNormalTexture"),
),
clearcoat_normal_scale: material_def
.pointer("/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale")
.and_then(Value::as_f64)
.unwrap_or(1.0),
transmission_factor: material_def
.pointer("/extensions/KHR_materials_transmission")
.map(|ext| {
ext.get("transmissionFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0)
}),
transmission_texture: GltfTextureRef::parse(
material_def
.pointer("/extensions/KHR_materials_transmission/transmissionTexture"),
),
thickness_factor: material_def
.pointer("/extensions/KHR_materials_volume")
.map(|ext| {
ext.get("thicknessFactor")
.and_then(Value::as_f64)
.unwrap_or(0.0)
}),
thickness_texture: GltfTextureRef::parse(
material_def.pointer("/extensions/KHR_materials_volume/thicknessTexture"),
),
attenuation_distance: material_def
.pointer("/extensions/KHR_materials_volume/attenuationDistance")
.and_then(Value::as_f64)
.unwrap_or(f64::INFINITY),
attenuation_color: material_def
.pointer("/extensions/KHR_materials_volume/attenuationColor")
.and_then(Value::as_array)
.map(|v| {
let mut out = [1.0; 3];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(value) = v.get(i).and_then(Value::as_f64) {
*slot = value;
}
}
out
})
.unwrap_or([1.0; 3]),
});
}
materials
}
fn load_textures(&self) -> Vec<GltfTexture> {
self.json
.get("textures")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
.iter()
.map(|texture| GltfTexture {
source: texture.pointer("/extensions/EXT_texture_webp").map_or_else(
|| json_usize(texture, "source"),
|webp| json_usize(webp, "source"),
),
sampler: json_usize(texture, "sampler"),
basisu_source: texture
.pointer("/extensions/KHR_texture_basisu")
.and_then(|extension| json_usize(extension, "source")),
})
.collect()
}
fn load_images(&self) -> Result<Vec<GltfImage>, Error> {
let mut images = Vec::new();
for image_def in self
.json
.get("images")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
{
let uri = image_def
.get("uri")
.and_then(Value::as_str)
.map(str::to_string);
let data = match (&uri, json_usize(&image_def, "bufferView")) {
(Some(uri), _) if uri.starts_with("data:") => decode_data_uri(uri)?,
(Some(uri), _) => crate::io::read(&self.base.join(uri)).unwrap_or_default(),
(None, Some(view)) => self.buffer_view(view)?.to_vec(),
(None, None) => Vec::new(),
};
images.push(GltfImage {
name: image_def
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
mime_type: image_def
.get("mimeType")
.and_then(Value::as_str)
.map(str::to_string),
uri,
data,
});
}
Ok(images)
}
fn load_texture(
&self,
cache: &mut HashMap<usize, Texture>,
textures: &[GltfTexture],
images: &[GltfImage],
index: usize,
) -> Result<Option<Texture>, Error> {
if let Some(texture) = cache.get(&index) {
return Ok(Some(texture.clone()));
}
let Some(def) = textures.get(index) else {
return Ok(None);
};
let texture = if let Some(image) = def.basisu_source.and_then(|source| images.get(source)) {
self.ktx2_loader.parse(&image.data)?.into_texture()?
} else {
let Some(image) = def.source.and_then(|source| images.get(source)) else {
return Ok(None);
};
TextureLoader::new().from_bytes(&image.data, image.mime_type.as_deref())?
};
texture.set_flip_y(false);
let sampler = def
.sampler
.and_then(|i| self.json.pointer(&format!("/samplers/{i}")))
.cloned()
.unwrap_or(Value::Null);
let wrap = |name: &str| match sampler.get(name).and_then(Value::as_u64) {
Some(33071) => Wrapping::ClampToEdge,
_ => Wrapping::Repeat,
};
texture.set_wrapping(wrap("wrapS"), wrap("wrapT"));
if let Some(9728) = sampler.get("magFilter").and_then(Value::as_u64) {
texture.set_mag_filter(TextureFilter::Nearest);
}
match sampler.get("minFilter").and_then(Value::as_u64) {
Some(9728) => texture.set_min_filter(MinFilter::Nearest),
Some(9729) => texture.set_min_filter(MinFilter::Linear),
_ => texture.set_min_filter(MinFilter::LinearMipmapLinear),
}
cache.insert(index, texture.clone());
Ok(Some(texture))
}
fn assign_texture(
&self,
cache: &mut HashMap<usize, Texture>,
textures: &[GltfTexture],
images: &[GltfImage],
map_def: &GltfTextureRef,
color_space: ColorSpace,
) -> Result<Option<Texture>, Error> {
let Some(mut texture) = self.load_texture(cache, textures, images, map_def.index)? else {
return Ok(None);
};
if let Some(tex_coord) = map_def.tex_coord.filter(|&n| n > 0) {
texture = texture.clone_texture();
texture.set_channel(tex_coord);
}
if let Some(transform) = &map_def.transform {
let no_op = transform.tex_coord.is_none_or(|n| n == texture.channel())
&& transform.offset.is_none()
&& transform.rotation.is_none()
&& transform.scale.is_none();
if !no_op {
texture = texture.clone_texture();
if let Some(tex_coord) = transform.tex_coord {
texture.set_channel(tex_coord);
}
if let Some([x, y]) = transform.offset {
texture.set_offset(x, y);
}
if let Some(rotation) = transform.rotation {
texture.set_rotation(rotation);
}
if let Some([x, y]) = transform.scale {
texture.set_repeat(x, y);
}
if let Some(rotation) = transform.rotation {
let (c, sin) = (rotation.cos(), rotation.sin());
let repeat = transform.scale.unwrap_or([1.0, 1.0]);
let offset = transform.offset.unwrap_or([0.0, 0.0]);
let mut matrix = crate::math::Matrix3::identity();
matrix.set(
repeat[0] * c,
repeat[1] * sin,
offset[0],
-repeat[0] * sin,
repeat[1] * c,
offset[1],
0.0,
0.0,
1.0,
);
texture.set_matrix(matrix);
}
}
}
if color_space == ColorSpace::Srgb {
texture.set_color_space(color_space);
}
Ok(Some(texture))
}
fn final_material(
&self,
texture_cache: &mut HashMap<usize, Texture>,
material_cache: &mut HashMap<MaterialVariant, MeshBasicNodeMaterial>,
primitive: &GltfPrimitive,
materials: &[GltfMaterial],
textures: &[GltfTexture],
images: &[GltfImage],
) -> Result<Option<MeshBasicNodeMaterial>, Error> {
let Some(index) = primitive.material else {
return Ok(None);
};
let Some(def) = materials.get(index) else {
return Ok(None);
};
let variant = MaterialVariant {
material: index,
use_derivative_tangents: !primitive.geometry.has_attribute("tangent"),
use_vertex_colors: primitive.geometry.has_attribute("color"),
use_flat_shading: !primitive.geometry.has_attribute("normal"),
};
if let Some(cached) = material_cache.get(&variant) {
return Ok(Some(cached.clone()));
}
let unlit = def
.extensions
.iter()
.any(|name| name == "KHR_materials_unlit");
let mut material = if unlit {
self.build_unlit_material(texture_cache, def, textures, images)?
} else {
self.build_material(texture_cache, def, textures, images)?
};
if variant.use_vertex_colors {
material.vertex_colors = true;
}
if variant.use_flat_shading {
material.flat_shading = true;
}
if variant.use_derivative_tangents && !unlit {
material.normal_scale.y *= -1.0;
if material.kind == crate::materials::MaterialKind::Physical {
material.clearcoat_normal_scale.y *= -1.0;
}
}
material_cache.insert(variant, material.clone());
Ok(Some(material))
}
fn build_unlit_material(
&self,
cache: &mut HashMap<usize, Texture>,
material: &GltfMaterial,
textures: &[GltfTexture],
images: &[GltfImage],
) -> Result<MeshBasicNodeMaterial, Error> {
let mut out = MeshBasicNodeMaterial::new();
let [r, g, b, a] = material.base_color_factor;
out.color = Color::new(r, g, b);
out.opacity = a;
out.side = if material.double_sided {
Side::Double
} else {
Side::Front
};
if material.alpha_mode == "BLEND" {
out.transparent = true;
out.depth_write = false;
} else {
out.transparent = false;
}
if let Some(map_def) = &material.base_color_texture {
out.map = self.assign_texture(cache, textures, images, map_def, ColorSpace::Srgb)?;
}
Ok(out)
}
fn build_material(
&self,
cache: &mut HashMap<usize, Texture>,
material: &GltfMaterial,
textures: &[GltfTexture],
images: &[GltfImage],
) -> Result<MeshBasicNodeMaterial, Error> {
let [r, g, b, a] = material.base_color_factor;
let physical = material.ior.is_some()
|| material.specular_factor.is_some()
|| material.sheen.is_some()
|| material.diffuse_roughness_factor.is_some()
|| material.anisotropy_strength.is_some()
|| material.iridescence.is_some()
|| material.clearcoat_factor.is_some()
|| material.transmission_factor.is_some()
|| material.thickness_factor.is_some();
let mut out = if physical {
MeshBasicNodeMaterial::physical(
Color::new(r, g, b),
material.roughness_factor,
material.metallic_factor,
)
} else {
MeshBasicNodeMaterial::standard(
Color::new(r, g, b),
material.roughness_factor,
material.metallic_factor,
)
};
out.opacity = a;
out.side = if material.double_sided {
Side::Double
} else {
Side::Front
};
if material.alpha_mode == "BLEND" {
out.transparent = true;
out.depth_write = false;
} else {
out.transparent = false;
if material.alpha_mode == "MASK" {
out.alpha_test = material.alpha_cutoff;
}
}
let [er, eg, eb] = material.emissive_factor;
out.emissive = Color::new(er, eg, eb);
if let Some(strength) = material.emissive_strength {
out.emissive_intensity = strength;
}
if let Some(map_def) = &material.base_color_texture {
out.map = self.assign_texture(cache, textures, images, map_def, ColorSpace::Srgb)?;
}
if let Some(map_def) = &material.metallic_roughness_texture {
let map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
out.metalness_map = map.clone();
out.roughness_map = map;
}
if let Some(map_def) = &material.emissive_texture {
out.emissive_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::Srgb)?;
}
if let Some(map_def) = &material.occlusion_texture {
out.ao_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
if let Some(strength) = material.occlusion_strength {
out.ao_map_intensity = strength;
}
}
if let Some(map_def) = &material.normal_texture {
out.normal_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
out.normal_scale = Vector2::new(material.normal_scale, material.normal_scale);
}
if let Some(ior) = material.ior {
out.ior = ior;
}
if let Some(factor) = material.specular_factor {
out.specular_intensity = factor;
}
let [sr, sg, sb] = material.specular_color_factor;
out.specular_color = Color::new(sr, sg, sb);
if let Some(map_def) = &material.specular_color_texture {
out.specular_color_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::Srgb)?;
}
if let Some(sheen) = material.sheen {
out.sheen = 1.0;
let [r, g, b] = sheen.color_factor;
out.sheen_color = Color::new(r, g, b);
out.sheen_roughness = sheen.roughness_factor;
}
if let Some(factor) = material.diffuse_roughness_factor {
out.diffuse_roughness = factor;
}
if let Some(strength) = material.anisotropy_strength {
out.anisotropy = strength;
out.anisotropy_rotation = material.anisotropy_rotation;
}
if let Some(map_def) = &material.anisotropy_texture {
out.anisotropy_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
if let Some(iridescence) = material.iridescence {
out.iridescence = iridescence.factor;
out.iridescence_ior = iridescence.ior;
out.iridescence_thickness_range = iridescence.thickness_range;
}
if let Some(map_def) = &material.iridescence_thickness_texture {
out.iridescence_thickness_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
if let Some(factor) = material.clearcoat_factor {
out.clearcoat = factor;
out.clearcoat_roughness = material.clearcoat_roughness_factor;
}
if let Some(map_def) = &material.clearcoat_texture {
out.clearcoat_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
if let Some(map_def) = &material.clearcoat_roughness_texture {
out.clearcoat_roughness_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
if let Some(map_def) = &material.clearcoat_normal_texture {
out.clearcoat_normal_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
let scale = material.clearcoat_normal_scale;
out.clearcoat_normal_scale = Vector2::new(scale, scale);
}
if let Some(factor) = material.transmission_factor {
out.transmission = factor;
}
if let Some(map_def) = &material.transmission_texture {
out.transmission_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
if let Some(factor) = material.thickness_factor {
out.thickness = factor;
out.attenuation_distance = material.attenuation_distance;
let [ar, ag, ab] = material.attenuation_color;
out.attenuation_color = Color::new(ar, ag, ab);
}
if let Some(map_def) = &material.thickness_texture {
out.thickness_map =
self.assign_texture(cache, textures, images, map_def, ColorSpace::NoColorSpace)?;
}
Ok(out)
}
fn load_animations(&self, nodes: &[ObjectRef]) -> Result<Vec<AnimationClip>, Error> {
let mut clips = Vec::new();
for (index, animation_def) in self
.json
.get("animations")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
.iter()
.enumerate()
{
let name = animation_def
.get("name")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("animation_{index}"));
let samplers = animation_def
.get("samplers")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut tracks = Vec::new();
for channel in animation_def
.get("channels")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[])
{
let Some(sampler) = json_usize(channel, "sampler").and_then(|i| samplers.get(i))
else {
continue;
};
let Some(target) = channel.get("target") else {
continue;
};
let Some(node_index) = json_usize(target, "node") else {
continue;
};
let Some(node) = nodes.get(node_index) else {
continue;
};
let Some(path) = target.get("path").and_then(Value::as_str) else {
continue;
};
let Some(property) = path_property(path) else {
continue;
};
let input = json_usize(sampler, "input").ok_or(GltfError::MissingField {
what: "sampler input",
})?;
let output = json_usize(sampler, "output").ok_or(GltfError::MissingField {
what: "sampler output",
})?;
let (times, _) = self.accessor(input)?;
let (mut values, _) = self.accessor(output)?;
let interpolation = match sampler
.get("interpolation")
.and_then(Value::as_str)
.unwrap_or("LINEAR")
{
"STEP" => InterpolationMode::Discrete,
"CUBICSPLINE" => {
let stride = values.len() / (times.len() * 3);
let mut linear = Vec::with_capacity(times.len() * stride);
for i in 0..times.len() {
let at = i * stride * 3 + stride;
linear.extend_from_slice(&values[at..at + stride]);
}
values = linear;
InterpolationMode::Linear
}
_ => InterpolationMode::Linear,
};
let track_name = format!("{}.{}", node.borrow().name, property);
let track = match property {
"quaternion" => {
KeyframeTrack::quaternion(&track_name, times, values, Some(interpolation))
}
"morphTargetInfluences" => {
KeyframeTrack::number(&track_name, times, values, Some(interpolation))
}
_ => KeyframeTrack::vector(&track_name, times, values, Some(interpolation)),
};
match track {
Ok(track) => tracks.push(track),
Err(_) => continue,
}
}
clips.push(AnimationClip::from_tracks(
&sanitize_node_name(&name),
tracks,
));
}
Ok(clips)
}
}
fn apply_node_transform(object: &mut Object3D, node_def: &Value) {
if let Some(matrix) = node_def.get("matrix").and_then(Value::as_array) {
let values: Vec<f64> = matrix.iter().filter_map(Value::as_f64).collect();
let mut m = Matrix4::identity();
m.from_array(&values, 0);
object.apply_matrix4(&m);
return;
}
if let Some(values) = node_def.get("translation").and_then(Value::as_array) {
let values: Vec<f64> = values.iter().filter_map(Value::as_f64).collect();
object.position.from_array(&values, 0);
}
if let Some(values) = node_def.get("rotation").and_then(Value::as_array) {
let values: Vec<f64> = values.iter().filter_map(Value::as_f64).collect();
object.quaternion.from_array(&values, 0);
object.sync_rotation_from_quaternion();
}
if let Some(values) = node_def.get("scale").and_then(Value::as_array) {
let values: Vec<f64> = values.iter().filter_map(Value::as_f64).collect();
object.scale.from_array(&values, 0);
}
}
fn parse_glb(data: &[u8]) -> Result<(Value, Option<Vec<u8>>), Error> {
if data.len() < 12 {
return Err(GltfError::BadHeader.into());
}
let version = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
if version < 2 {
return Err(GltfError::LegacyBinary.into());
}
let mut json = None;
let mut bin = None;
let mut at = 12;
while at + 8 <= data.len() {
let length =
u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;
let chunk_type =
u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]);
at += 8;
let chunk = data.get(at..at + length).ok_or(GltfError::TruncatedChunk)?;
match chunk_type {
0x4E4F_534A => {
let text = std::str::from_utf8(chunk).map_err(|_| GltfError::NotUtf8)?;
json = Some(
serde_json::from_str(text)
.map_err(|source| Error::Json { path: None, source })?,
);
}
0x004E_4942 => bin = Some(chunk.to_vec()),
_ => {}
}
at += length;
}
let json = json.ok_or(GltfError::NoJsonChunk)?;
Ok((json, bin))
}
fn decode_data_uri(uri: &str) -> Result<Vec<u8>, Error> {
let (header, payload) = uri
.split_once(',')
.ok_or_else(|| GltfError::BadDataUri(uri.to_string()))?;
if header.ends_with(";base64") {
decode_base64(payload)
} else {
Ok(payload.as_bytes().to_vec())
}
}
fn decode_base64(input: &str) -> Result<Vec<u8>, Error> {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::with_capacity(input.len() / 4 * 3);
let mut accumulator: u32 = 0;
let mut bits = 0;
for c in input.bytes() {
if c == b'=' || c.is_ascii_whitespace() {
continue;
}
let value = TABLE
.iter()
.position(|&t| t == c)
.ok_or(GltfError::BadBase64(c as char))? as u32;
accumulator = (accumulator << 6) | value;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((accumulator >> bits) as u8);
}
}
Ok(out)
}
fn draco_buffer_attribute(attribute: &DracoAttribute) -> BufferAttribute {
let scale = if attribute.normalized {
match attribute.array {
DracoArray::I8(_) => ComponentType::Byte,
DracoArray::U8(_) => ComponentType::UnsignedByte,
DracoArray::I16(_) => ComponentType::Short,
DracoArray::U16(_) => ComponentType::UnsignedShort,
DracoArray::U32(_) => ComponentType::UnsignedInt,
DracoArray::F32(_) => ComponentType::Float,
}
.normalized_scale()
} else {
1.0
};
let values: Vec<f32> = attribute
.array
.to_f64()
.into_iter()
.map(|value| (value * scale) as f32)
.collect();
if attribute.name == "skinIndex" {
let values = values.iter().map(|v| *v as u32).collect();
BufferAttribute::uint32(values, attribute.item_size, false)
} else {
BufferAttribute::new(values, attribute.item_size)
}
}
fn json_usize(value: &Value, key: &str) -> Option<usize> {
value.get(key).and_then(Value::as_u64).map(|v| v as usize)
}
const SUPPORTED_EXTENSIONS: &[&str] = &[
"EXT_meshopt_compression",
"EXT_texture_webp",
"KHR_draco_mesh_compression",
"KHR_materials_anisotropy",
"KHR_materials_clearcoat",
"KHR_materials_diffuse_roughness",
"KHR_materials_emissive_strength",
"KHR_materials_ior",
"KHR_materials_iridescence",
"KHR_materials_sheen",
"KHR_materials_specular",
"KHR_materials_transmission",
"KHR_materials_unlit",
"KHR_materials_volume",
"KHR_mesh_quantization",
"KHR_texture_basisu",
"KHR_texture_transform",
];
fn check_required_extensions(json: &Value) -> Result<(), Error> {
let required = json
.get("extensionsRequired")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or_default();
for name in required.iter().filter_map(Value::as_str) {
if !SUPPORTED_EXTENSIONS.contains(&name) {
return Err(GltfError::UnsupportedRequiredExtension(name.to_string()).into());
}
}
Ok(())
}