use super::tree::{Node, Property};
use crate::core::{BufferAttribute, BufferGeometry};
#[derive(Debug, Clone, Copy, PartialEq)]
enum Mapping {
PolygonVertex,
Vertex,
Polygon,
AllSame,
}
impl Mapping {
fn parse(name: Option<&str>) -> Self {
match name {
Some("ByVertice") | Some("ByVertex") | Some("ByVertices") => Mapping::Vertex,
Some("ByPolygon") => Mapping::Polygon,
Some("AllSame") | Some("AllSames") => Mapping::AllSame,
_ => Mapping::PolygonVertex,
}
}
}
struct Layer {
data: Vec<f32>,
indices: Vec<i32>,
mapping: Mapping,
stride: usize,
}
impl Layer {
fn read(node: &Node, data_name: &str, index_name: &str, stride: usize) -> Option<Self> {
let data = node.value(data_name)?.as_f32_array()?;
if data.is_empty() {
return None;
}
let reference = node
.value("ReferenceInformationType")
.and_then(Property::as_str)
.unwrap_or("Direct");
let indices = if reference == "Direct" {
Vec::new()
} else {
node.value(index_name)
.and_then(Property::as_i32_array)
.unwrap_or_default()
};
Some(Layer {
data,
indices,
mapping: Mapping::parse(
node.value("MappingInformationType").and_then(Property::as_str),
),
stride,
})
}
fn at(&self, corner: usize, control_point: usize, polygon: usize) -> Vec<f32> {
let slot = match self.mapping {
Mapping::PolygonVertex => corner,
Mapping::Vertex => control_point,
Mapping::Polygon => polygon,
Mapping::AllSame => 0,
};
let slot = if self.indices.is_empty() {
slot
} else {
match self.indices.get(slot) {
Some(&i) if i >= 0 => i as usize,
_ => return vec![0.0; self.stride],
}
};
let at = slot * self.stride;
self.data
.get(at..at + self.stride)
.map(<[f32]>::to_vec)
.unwrap_or_else(|| vec![0.0; self.stride])
}
}
pub fn material_slots(node: &Node) -> Vec<i32> {
node.child("LayerElementMaterial")
.and_then(|l| l.value("Materials").and_then(Property::as_i32_array))
.unwrap_or_default()
}
pub fn material_mapping_is_all_same(node: &Node) -> bool {
node.child("LayerElementMaterial")
.and_then(|l| l.value("MappingInformationType"))
.and_then(Property::as_str)
.is_none_or(|m| m == "AllSame")
}
pub fn corner_control_points(node: &Node) -> Vec<usize> {
let corners = node
.value("PolygonVertexIndex")
.and_then(Property::as_i32_array)
.unwrap_or_default();
let mut out = Vec::new();
let mut polygon: Vec<usize> = Vec::with_capacity(4);
for &raw in &corners {
polygon.push(if raw < 0 { !raw as usize } else { raw as usize });
if raw >= 0 {
continue;
}
for i in 1..polygon.len().saturating_sub(1) {
out.extend_from_slice(&[polygon[0], polygon[i], polygon[i + 1]]);
}
polygon.clear();
}
out
}
pub fn build(node: &Node) -> Option<(BufferGeometry, Vec<i32>)> {
let points = node.value("Vertices")?.as_f32_array()?;
if points.is_empty() {
return None;
}
let corners = node
.value("PolygonVertexIndex")
.and_then(Property::as_i32_array)
.unwrap_or_default();
let normals = node
.child("LayerElementNormal")
.and_then(|l| Layer::read(l, "Normals", "NormalsIndex", 3));
let uvs = node
.child("LayerElementUV")
.and_then(|l| Layer::read(l, "UV", "UVIndex", 2));
let colours = node
.child("LayerElementColor")
.and_then(|l| Layer::read(l, "Colors", "ColorIndex", 4));
let slots = material_slots(node);
let mut position = Vec::new();
let mut normal = Vec::new();
let mut uv = Vec::new();
let mut colour = Vec::new();
let mut triangle_slots = Vec::new();
let mut polygons: Vec<u32> = Vec::new();
let mut polygon: Vec<(usize, usize)> = Vec::with_capacity(4);
let mut polygon_index = 0usize;
for (corner, &raw) in corners.iter().enumerate() {
let control_point = if raw < 0 { !raw as usize } else { raw as usize };
polygon.push((corner, control_point));
if raw >= 0 {
continue;
}
if polygon.len() >= 3 {
polygons.push(polygon.len() as u32 - 2);
}
for i in 1..polygon.len().saturating_sub(1) {
for &(corner, point) in &[polygon[0], polygon[i], polygon[i + 1]] {
let at = point * 3;
match points.get(at..at + 3) {
Some(p) => position.extend_from_slice(p),
None => position.extend_from_slice(&[0.0, 0.0, 0.0]),
}
if let Some(layer) = &normals {
normal.extend_from_slice(&layer.at(corner, point, polygon_index));
}
if let Some(layer) = &uvs {
uv.extend_from_slice(&layer.at(corner, point, polygon_index));
}
if let Some(layer) = &colours {
colour.extend_from_slice(&layer.at(corner, point, polygon_index));
}
}
triangle_slots.push(slots.get(polygon_index).copied().unwrap_or(0));
}
polygon.clear();
polygon_index += 1;
}
if position.is_empty() {
position = points;
}
let mut geometry = BufferGeometry::new();
geometry.set_attribute("position", BufferAttribute::new(position, 3));
if !normal.is_empty() {
geometry.set_attribute("normal", BufferAttribute::new(normal, 3));
}
if !uv.is_empty() {
geometry.set_attribute("uv", BufferAttribute::new(uv, 2));
}
if !colour.is_empty() {
let rgb: Vec<f32> = colour
.chunks_exact(4)
.flat_map(|c| [c[0], c[1], c[2]])
.collect();
geometry.set_attribute("color", BufferAttribute::new(rgb, 3));
}
if geometry.get_attribute("normal").is_none() {
crate::compute_vertex_normals(&mut geometry);
}
geometry.set_polygons(polygons);
Some((geometry, triangle_slots))
}