use ifc_lite_core::{DecodedEntity, EntityDecoder, EntityScanner, IfcType};
mod raster;
pub use raster::decode_step_binary;
use raster::{decode_raster_image, MAX_TEX_DIM};
use rustc_hash::FxHashMap;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct MeshTexture {
pub rgba: std::sync::Arc<Vec<u8>>,
pub width: u32,
pub height: u32,
pub repeat_s: bool,
pub repeat_t: bool,
}
#[derive(Debug, Clone)]
pub enum TextureSource {
Decoded(Arc<MeshTexture>),
Image(ImageTextureRef),
}
#[derive(Debug, Clone)]
pub struct ImageTextureRef {
pub url: String,
pub repeat_s: bool,
pub repeat_t: bool,
}
#[derive(Debug, Clone)]
pub struct TextureAttachment {
pub texture_id: u32,
pub source: TextureSource,
}
#[derive(Debug, Clone)]
pub struct ResolvedTextureMap {
pub texture_id: u32,
pub texture: TextureSource,
pub tex_coords: Vec<[f32; 2]>,
pub tex_coord_index: Option<Vec<[u32; 3]>>,
}
impl ResolvedTextureMap {
pub fn attachment(&self) -> TextureAttachment {
TextureAttachment {
texture_id: self.texture_id,
source: self.texture.clone(),
}
}
}
fn decode_blob_texture(entity: &DecodedEntity) -> Option<MeshTexture> {
let raster_code = entity.get(6).and_then(|a| a.as_string())?;
let bytes = decode_step_binary(raster_code);
if bytes.len() < 8 {
return None;
}
let (rgba, width, height) = decode_raster_image(&bytes)?;
Some(MeshTexture {
rgba: Arc::new(rgba),
width,
height,
repeat_s: read_bool(entity, 0).unwrap_or(true),
repeat_t: read_bool(entity, 1).unwrap_or(true),
})
}
fn decode_pixel_texture(entity: &DecodedEntity) -> Option<MeshTexture> {
let width = entity.get(5).and_then(|a| a.as_int())?;
let height = entity.get(6).and_then(|a| a.as_int())?;
let components = entity.get(7).and_then(|a| a.as_int())?;
let max_dim = MAX_TEX_DIM as i64;
if width <= 0
|| height <= 0
|| width > max_dim
|| height > max_dim
|| !(1..=4).contains(&components)
{
return None;
}
let width = width as u32;
let height = height as u32;
let components = components as usize;
let pixels = entity.get(8).and_then(|a| a.as_list())?;
let expected = (width as usize) * (height as usize);
if pixels.len() != expected {
return None;
}
let mut rgba = Vec::with_capacity(expected * 4);
for px in pixels.iter() {
let s = px.as_string()?;
let comp = decode_step_binary(s);
if comp.len() < components {
return None;
}
let (r, g, b, a) = match components {
1 => (comp[0], comp[0], comp[0], 255),
2 => (comp[0], comp[0], comp[0], comp[1]),
3 => (comp[0], comp[1], comp[2], 255),
_ => (comp[0], comp[1], comp[2], comp[3]),
};
rgba.extend_from_slice(&[r, g, b, a]);
}
if rgba.len() != expected * 4 {
return None;
}
Some(MeshTexture {
rgba: Arc::new(rgba),
width,
height,
repeat_s: read_bool(entity, 0).unwrap_or(true),
repeat_t: read_bool(entity, 1).unwrap_or(true),
})
}
fn read_bool(entity: &DecodedEntity, idx: usize) -> Option<bool> {
entity.get(idx).and_then(|a| a.as_enum()).map(|v| v == "T")
}
fn read_image_texture(entity: &DecodedEntity) -> Option<ImageTextureRef> {
let url = entity.get(5).and_then(|a| a.as_string())?.trim().to_string();
if url.is_empty() {
return None;
}
Some(ImageTextureRef {
url,
repeat_s: read_bool(entity, 0).unwrap_or(true),
repeat_t: read_bool(entity, 1).unwrap_or(true),
})
}
fn resolve_surface_texture(
texture_id: u32,
decoder: &mut EntityDecoder,
cache: &mut FxHashMap<u32, Option<TextureSource>>,
) -> Option<TextureSource> {
if let Some(cached) = cache.get(&texture_id) {
return cached.clone();
}
let resolved = decoder.decode_by_id(texture_id).ok().and_then(|entity| {
match entity.ifc_type {
IfcType::IfcBlobTexture => decode_blob_texture(&entity)
.map(|t| TextureSource::Decoded(Arc::new(t))),
IfcType::IfcPixelTexture => decode_pixel_texture(&entity)
.map(|t| TextureSource::Decoded(Arc::new(t))),
IfcType::IfcImageTexture => read_image_texture(&entity).map(TextureSource::Image),
_ => None,
}
});
cache.insert(texture_id, resolved.clone());
resolved
}
fn resolve_triangle_texture_map(
entity: &DecodedEntity,
decoder: &mut EntityDecoder,
texture_cache: &mut FxHashMap<u32, Option<TextureSource>>,
) -> Option<(u32, ResolvedTextureMap)> {
let face_set_id = entity.get_ref(1)?;
let maps = entity.get(0)?.as_list()?;
let texture_id = maps.iter().find_map(|m| m.as_entity_ref())?;
let texture = resolve_surface_texture(texture_id, decoder, texture_cache)?;
let tvl_id = entity.get_ref(2)?;
let tvl = decoder.decode_by_id(tvl_id).ok()?;
let coord_list = tvl.get(0)?.as_list()?;
let tex_coords: Vec<[f32; 2]> = coord_list
.iter()
.map(|c| {
let uv = c.as_list()?;
let u = uv.first().and_then(|v| v.as_float())? as f32;
let v = uv.get(1).and_then(|v| v.as_float())? as f32;
Some([u, v])
})
.collect::<Option<Vec<_>>>()?;
if tex_coords.is_empty() {
return None;
}
let tex_coord_index: Option<Vec<[u32; 3]>> = match entity.get(3) {
Some(attr) if !attr.is_null() => {
let index_attr = attr.as_list()?;
let idx: Vec<[u32; 3]> = index_attr
.iter()
.map(|tri| {
let t = tri.as_list()?;
let a = t.first().and_then(|v| v.as_int())? as u32;
let b = t.get(1).and_then(|v| v.as_int())? as u32;
let c = t.get(2).and_then(|v| v.as_int())? as u32;
Some([a, b, c])
})
.collect::<Option<Vec<_>>>()?;
if idx.is_empty() {
return None;
}
Some(idx)
}
_ => None,
};
Some((
face_set_id,
ResolvedTextureMap {
texture_id,
texture,
tex_coords,
tex_coord_index,
},
))
}
pub fn build_texture_index(
content: &[u8],
decoder: &mut EntityDecoder,
) -> FxHashMap<u32, ResolvedTextureMap> {
let mut index = FxHashMap::default();
if memchr::memmem::find(content, b"IFCINDEXEDTRIANGLETEXTUREMAP").is_none() {
return index;
}
let mut texture_cache: FxHashMap<u32, Option<TextureSource>> = FxHashMap::default();
let mut scanner = EntityScanner::new(content);
while let Some((id, type_name, start, end)) = scanner.next_entity() {
if type_name != "IFCINDEXEDTRIANGLETEXTUREMAP" {
continue;
}
if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
if let Some((face_set_id, resolved)) =
resolve_triangle_texture_map(&entity, decoder, &mut texture_cache)
{
index.entry(face_set_id).or_insert(resolved);
}
}
}
index
}