Skip to main content

ifc_style/authoring/
texture.rs

1//! Textures: the image source, its coordinates, and generated maps.
2//!
3//! # Why a texture needs a face to mean anything
4//!
5//! `IfcTextureMap` carries `Vertices : LIST [3:?] OF IfcTextureVertex`
6//! and `MappedTo : IfcFace`. The vertex list is a correspondence: the
7//! nth texture vertex belongs to the nth vertex of the face's bound.
8//! A list shorter than the face's loop leaves vertices unmapped, and a
9//! longer one carries coordinates for vertices that do not exist.
10//!
11//! The writer cannot check that correspondence without walking the
12//! face's loop, which is geometry this crate deliberately does not
13//! depend on -- `ifc-style` may reference a representation item's id
14//! but never inspects its shape. So the cardinality floor of three is
15//! enforced here and the correspondence is left to the consumer that
16//! owns the geometry. Claiming otherwise would be a writer asserting
17//! something it cannot see.
18
19use ifc_model::{EntityId, Model, Transaction, Value};
20use ifc_schema::Schema;
21
22use crate::authoring::{build_named, invalid_authoring, validate_ref};
23use crate::StyleResult;
24
25/// What to stage for an `IfcImageTexture`.
26#[derive(Debug, Clone, Copy)]
27#[non_exhaustive]
28pub struct ImageTextureDraft<'a> {
29    /// `RepeatS`: does the texture tile along the s axis?
30    pub repeat_s: bool,
31    /// `RepeatT`: does the texture tile along the t axis?
32    pub repeat_t: bool,
33    /// `Mode`: how the texture combines with the underlying colour.
34    pub mode: Option<&'a str>,
35    /// `TextureTransform`: an `IfcCartesianTransformationOperator2D`.
36    pub texture_transform: Option<EntityId>,
37    /// `URLReference`: where the image lives.
38    pub url_reference: &'a str,
39}
40
41impl<'a> ImageTextureDraft<'a> {
42    /// Starts a draft from its required `url_reference`; every other field is
43    /// unset.
44    #[must_use]
45    pub fn new(url_reference: &'a str) -> Self {
46        Self {
47            repeat_s: false,
48            repeat_t: false,
49            mode: None,
50            texture_transform: None,
51            url_reference,
52        }
53    }
54
55    /// Sets `repeat_s`.
56    ///
57    /// `RepeatS`: does the texture tile along the s axis?
58    #[must_use]
59    pub fn repeat_s(mut self, value: bool) -> Self {
60        self.repeat_s = value;
61        self
62    }
63
64    /// Sets `repeat_t`.
65    ///
66    /// `RepeatT`: does the texture tile along the t axis?
67    #[must_use]
68    pub fn repeat_t(mut self, value: bool) -> Self {
69        self.repeat_t = value;
70        self
71    }
72
73    /// Sets `mode`.
74    ///
75    /// `Mode`: how the texture combines with the underlying colour.
76    #[must_use]
77    pub fn mode(mut self, value: &'a str) -> Self {
78        self.mode = Some(value);
79        self
80    }
81
82    /// Sets `texture_transform`.
83    ///
84    /// `TextureTransform`: an `IfcCartesianTransformationOperator2D`.
85    #[must_use]
86    pub fn texture_transform(mut self, value: EntityId) -> Self {
87        self.texture_transform = Some(value);
88        self
89    }
90}
91
92/// Stage an `IfcImageTexture`.
93///
94/// # The URL is required and must not be blank
95///
96/// `URLReference` is the only attribute that says what the texture
97/// actually is. An empty string satisfies the schema's type but names
98/// no image, producing a texture that resolves to nothing -- so it is
99/// refused rather than written.
100///
101/// # Errors
102///
103/// Refuses a blank `URLReference`, and a `TextureTransform` that does
104/// not resolve to an `IfcCartesianTransformationOperator2D`.
105pub fn create_image_texture(
106    tx: &mut Transaction,
107    model: &Model,
108    schema: &Schema,
109    draft: ImageTextureDraft<'_>,
110) -> StyleResult<EntityId> {
111    if draft.url_reference.trim().is_empty() {
112        return Err(invalid_authoring(
113            "IfcImageTexture",
114            "URLReference",
115            "expected a reference to an image, found nothing",
116        ));
117    }
118
119    if let Some(transform) = draft.texture_transform {
120        validate_ref(
121            tx,
122            model,
123            schema,
124            transform,
125            "IfcCartesianTransformationOperator2D",
126        )?;
127    }
128
129    let mut values = vec![
130        ("RepeatS", Value::Bool(draft.repeat_s)),
131        ("RepeatT", Value::Bool(draft.repeat_t)),
132        ("URLReference", Value::Text(draft.url_reference.into())),
133    ];
134    if let Some(mode) = draft.mode {
135        values.push(("Mode", Value::Text(mode.into())));
136    }
137    if let Some(transform) = draft.texture_transform {
138        values.push(("TextureTransform", Value::Ref(transform)));
139    }
140
141    Ok(tx.create(build_named(schema, "IfcImageTexture", values)?))
142}
143
144/// Stage an `IfcTextureMap`: explicit texture coordinates on a face.
145///
146/// # Errors
147///
148/// Refuses fewer than three vertices, since a mapped area needs at
149/// least a triangle; an empty `maps` list, since the record exists to
150/// carry those textures; and a `mapped_to` that does not resolve to an
151/// `IfcFace`.
152pub fn create_texture_map(
153    tx: &mut Transaction,
154    model: &Model,
155    schema: &Schema,
156    maps: &[EntityId],
157    vertices: &[EntityId],
158    mapped_to: EntityId,
159) -> StyleResult<EntityId> {
160    if maps.is_empty() {
161        return Err(invalid_authoring(
162            "IfcTextureMap",
163            "Maps",
164            "expected at least one surface texture, found none",
165        ));
166    }
167    if vertices.len() < 3 {
168        return Err(invalid_authoring(
169            "IfcTextureMap",
170            "Vertices",
171            format!("expected at least 3 vertices, found {}", vertices.len()),
172        ));
173    }
174
175    validate_ref(tx, model, schema, mapped_to, "IfcFace")?;
176
177    let values = vec![
178        (
179            "Maps",
180            Value::List(maps.iter().copied().map(Value::Ref).collect()),
181        ),
182        (
183            "Vertices",
184            Value::List(vertices.iter().copied().map(Value::Ref).collect()),
185        ),
186        ("MappedTo", Value::Ref(mapped_to)),
187    ];
188
189    Ok(tx.create(build_named(schema, "IfcTextureMap", values)?))
190}
191
192/// Stage an `IfcTextureCoordinateGenerator`: coordinates computed, not listed.
193///
194/// `mode` names the generating function (`SPHERE`, `CYLINDER`, and so
195/// on). Unlike [`create_texture_map`] there are no vertices: the
196/// consumer derives them from the mode and parameters.
197///
198/// # Errors
199///
200/// Refuses an empty `maps` list, a blank `mode` -- which would leave
201/// the generator with no function to apply -- and a non-finite
202/// parameter.
203pub fn create_texture_coordinate_generator(
204    tx: &mut Transaction,
205    schema: &Schema,
206    maps: &[EntityId],
207    mode: &str,
208    parameters: &[f64],
209) -> StyleResult<EntityId> {
210    if maps.is_empty() {
211        return Err(invalid_authoring(
212            "IfcTextureCoordinateGenerator",
213            "Maps",
214            "expected at least one surface texture, found none",
215        ));
216    }
217    if mode.trim().is_empty() {
218        return Err(invalid_authoring(
219            "IfcTextureCoordinateGenerator",
220            "Mode",
221            "expected a generating function, found nothing",
222        ));
223    }
224    if let Some(value) = parameters.iter().find(|value| !value.is_finite()) {
225        return Err(invalid_authoring(
226            "IfcTextureCoordinateGenerator",
227            "Parameter",
228            format!("expected finite parameters, found {value}"),
229        ));
230    }
231
232    let mut values = vec![
233        (
234            "Maps",
235            Value::List(maps.iter().copied().map(Value::Ref).collect()),
236        ),
237        ("Mode", Value::Text(mode.into())),
238    ];
239    if !parameters.is_empty() {
240        values.push((
241            "Parameter",
242            Value::List(parameters.iter().copied().map(Value::Real).collect()),
243        ));
244    }
245
246    Ok(tx.create(build_named(
247        schema,
248        "IfcTextureCoordinateGenerator",
249        values,
250    )?))
251}