use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub enum Property {
Bool(bool),
Short(i16),
Int(i32),
Long(i64),
Float(f32),
Double(f64),
String(String),
Raw(Vec<u8>),
Floats(Vec<f32>),
Doubles(Vec<f64>),
Ints(Vec<i32>),
Longs(Vec<i64>),
Bools(Vec<bool>),
}
impl Property {
pub fn as_f64(&self) -> Option<f64> {
match self {
Property::Float(v) => Some(*v as f64),
Property::Double(v) => Some(*v),
Property::Int(v) => Some(*v as f64),
Property::Long(v) => Some(*v as f64),
Property::Short(v) => Some(*v as f64),
Property::Bool(v) => Some(*v as u8 as f64),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Property::Int(v) => Some(*v as i64),
Property::Long(v) => Some(*v),
Property::Short(v) => Some(*v as i64),
Property::Double(v) => Some(*v as i64),
Property::Float(v) => Some(*v as i64),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Property::String(s) => Some(s),
_ => None,
}
}
pub fn as_f32_array(&self) -> Option<Vec<f32>> {
match self {
Property::Floats(v) => Some(v.clone()),
Property::Doubles(v) => Some(v.iter().map(|d| *d as f32).collect()),
Property::Ints(v) => Some(v.iter().map(|i| *i as f32).collect()),
Property::Longs(v) => Some(v.iter().map(|i| *i as f32).collect()),
_ => None,
}
}
pub fn as_i32_array(&self) -> Option<Vec<i32>> {
match self {
Property::Ints(v) => Some(v.clone()),
Property::Longs(v) => Some(v.iter().map(|i| *i as i32).collect()),
_ => None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Node {
pub name: String,
pub properties: Vec<Property>,
pub children: Vec<Node>,
}
impl Node {
pub fn child(&self, name: &str) -> Option<&Node> {
self.children.iter().find(|c| c.name == name)
}
pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Node> + 'a {
self.children.iter().filter(move |c| c.name == name)
}
pub fn value(&self, name: &str) -> Option<&Property> {
self.child(name)?.properties.first()
}
pub fn property70(&self, name: &str) -> Option<&[Property]> {
let bag = self
.child("Properties70")
.or_else(|| self.child("Properties60"))?;
for p in bag.children_named("P") {
if p.properties.first().and_then(Property::as_str) == Some(name) {
return p.properties.get(4..);
}
}
None
}
pub fn property70_vec3(&self, name: &str) -> Option<[f32; 3]> {
let values = self.property70(name)?;
if values.len() < 3 {
return None;
}
Some([
values[0].as_f64()? as f32,
values[1].as_f64()? as f32,
values[2].as_f64()? as f32,
])
}
pub fn by_id(&self) -> HashMap<i64, &Node> {
let mut out = HashMap::new();
if let Some(objects) = self.child("Objects") {
for node in &objects.children {
if let Some(id) = node.properties.first().and_then(Property::as_i64) {
out.insert(id, node);
}
}
}
out
}
}