Skip to main content

ifc_geometry/lower/tessellated/
texture.rs

1//! Texture coordinates for a lowered `IfcTriangulatedFaceSet` (#30).
2//!
3//! # Per corner, not per vertex
4//!
5//! `IfcIndexedTriangleTextureMap.TexCoordIndex[i][k]` is the texture vertex
6//! for corner `k` of `CoordIndex` triangle `i`. One position can carry a
7//! different coordinate in each triangle that uses it: in the IFC4 ADD2 TC1
8//! Figure 415 box, every corner has three. The values therefore become a
9//! corner-indexed `AttributeChannel`, so positions stay shared and the mesh
10//! stays closed; a per-vertex channel could not hold them.
11//!
12//! # Coverage
13//!
14//! - A shorter `TexCoordIndex` maps the leading triangles; the rest are
15//!   [`AttributeChannel::UNMAPPED`]. Real files texture only some faces.
16//! - A longer one, a 0 index, or an index past `TexCoordsList` is an error:
17//!   the map disagrees with the face set it names.
18//! - An omitted `TexCoordIndex` adds no channel. The schema does not define
19//!   what it means, so guessing a pairing would invent data.
20//!
21//! Coordinates are not transformed: they live in texture space, not model
22//! space, so the product frame never applies to them.
23//!
24//! Slots are read by position. They are the same in IFC4 ADD2 TC1 and IFC4X3
25//! ADD2 (`MappedTo` 1, `TexCoords` 2, `TexCoordIndex` 3; `TexCoordsList` 0).
26
27use axiolid_mesh::{AttributeChannel, Blend};
28use ifc_model::{EntityId, Value};
29
30use crate::error::{GeometryError, GeometryResult};
31use crate::lower::session::LoweringSession;
32
33/// Name of the texture-coordinate channel on the lowered mesh.
34///
35/// A face set with several triangle texture maps gets `uv`, `uv1`, `uv2`, ...
36/// in file order, so no map is silently dropped.
37pub const UV_CHANNEL: &str = "uv";
38
39const TYPE: &str = "IFCINDEXEDTRIANGLETEXTUREMAP";
40const TEX_COORDS: usize = 2;
41const TEX_COORD_INDEX: usize = 3;
42
43/// One corner-indexed `uv` channel per triangle texture map on `face_set`.
44pub(super) fn channels(
45    session: &mut LoweringSession<'_>,
46    face_set: EntityId,
47    triangle_count: usize,
48) -> GeometryResult<Vec<AttributeChannel>> {
49    let maps = session.triangle_texture_maps(face_set).to_vec();
50    let mut out = Vec::with_capacity(maps.len());
51    for map in maps {
52        if let Some(values) = channel(session, face_set, map, triangle_count)? {
53            let name = match out.len() {
54                0 => UV_CHANNEL.to_string(),
55                n => format!("{UV_CHANNEL}{n}"),
56            };
57            out.push(AttributeChannel::corner_indexed(
58                name,
59                values.0,
60                2,
61                Blend::Linear,
62                values.1,
63            ));
64        }
65    }
66    Ok(out)
67}
68
69/// Values and corner indices for one map, or `None` when `TexCoordIndex` is
70/// omitted.
71fn channel(
72    session: &mut LoweringSession<'_>,
73    face_set: EntityId,
74    map: EntityId,
75    triangle_count: usize,
76) -> GeometryResult<Option<(Vec<f64>, Vec<u32>)>> {
77    let entity = session.entity(face_set, map)?;
78    let index = match entity.attributes.get(TEX_COORD_INDEX) {
79        None | Some(Value::Null) => return Ok(None),
80        Some(value) => triangles(map, value)?,
81    };
82    if index.len() > triangle_count {
83        return Err(invalid(
84            map,
85            "TexCoordIndex",
86            format!(
87                "maps {} triangles, but the face set has {triangle_count}",
88                index.len()
89            ),
90        ));
91    }
92    let list = entity
93        .attributes
94        .get(TEX_COORDS)
95        .and_then(Value::as_ref_id)
96        .ok_or_else(|| missing(map, TYPE, "TexCoords"))?;
97    let values = texture_vertices(session, map, list)?;
98    let pool = values.len() / 2;
99
100    let mut corners = Vec::with_capacity(triangle_count * 3);
101    for triangle in &index {
102        for &raw in triangle {
103            // 1-based in the file; 0 and past-the-end both name nothing.
104            let slot = usize::try_from(raw)
105                .ok()
106                .filter(|&s| (1..=pool).contains(&s));
107            let Some(slot) = slot else {
108                return Err(invalid(
109                    map,
110                    "TexCoordIndex",
111                    format!("holds {raw}; TexCoordsList has {pool} entries (1-based)"),
112                ));
113            };
114            corners.push((slot - 1) as u32);
115        }
116    }
117    corners.resize(triangle_count * 3, AttributeChannel::UNMAPPED);
118    Ok(Some((values, corners)))
119}
120
121/// `TexCoordIndex` as rows of three raw (1-based) integers.
122fn triangles(map: EntityId, value: &Value) -> GeometryResult<Vec<[i64; 3]>> {
123    let rows = value
124        .unwrap_typed()
125        .as_list()
126        .ok_or_else(|| invalid(map, "TexCoordIndex", "is not a list".to_string()))?;
127    rows.iter()
128        .map(|row| {
129            let row = row.unwrap_typed().as_list();
130            let ints: Option<Vec<i64>> = row.map(|r| {
131                r.iter()
132                    .map(|v| v.unwrap_typed().as_i64())
133                    .collect::<Option<Vec<_>>>()
134            })?;
135            match ints.as_deref() {
136                Some(&[a, b, c]) => Some([a, b, c]),
137                _ => None,
138            }
139        })
140        .collect::<Option<Vec<_>>>()
141        .ok_or_else(|| {
142            invalid(
143                map,
144                "TexCoordIndex",
145                "every entry must be exactly three integers".to_string(),
146            )
147        })
148}
149
150/// `IfcTextureVertexList.TexCoordsList` flattened to `s, t, s, t, ...`.
151fn texture_vertices(
152    session: &mut LoweringSession<'_>,
153    map: EntityId,
154    list: EntityId,
155) -> GeometryResult<Vec<f64>> {
156    let entity = session.entity(map, list)?;
157    let rows = entity
158        .attributes
159        .first()
160        .and_then(|v| v.unwrap_typed().as_list())
161        .ok_or_else(|| missing(list, "IFCTEXTUREVERTEXLIST", "TexCoordsList"))?;
162    let mut out = Vec::with_capacity(rows.len() * 2);
163    for row in rows {
164        let pair = row.unwrap_typed().as_list().and_then(|p| match p {
165            [s, t] => Some([s.unwrap_typed().as_f64()?, t.unwrap_typed().as_f64()?]),
166            _ => None,
167        });
168        let Some([s, t]) = pair else {
169            return Err(GeometryError::Degenerate {
170                entity: list,
171                type_name: "IFCTEXTUREVERTEXLIST".to_string(),
172                detail: "TexCoordsList entries must be (s, t) pairs of numbers".to_string(),
173            });
174        };
175        out.extend([s, t]);
176    }
177    Ok(out)
178}
179
180fn invalid(map: EntityId, attribute: &str, detail: String) -> GeometryError {
181    GeometryError::Degenerate {
182        entity: map,
183        type_name: TYPE.to_string(),
184        detail: format!("{attribute} {detail}"),
185    }
186}
187
188fn missing(entity: EntityId, type_name: &str, attribute: &'static str) -> GeometryError {
189    GeometryError::MissingAttribute {
190        entity,
191        type_name: type_name.to_string(),
192        attribute,
193    }
194}
195
196#[cfg(test)]
197mod tests;