Skip to main content

ifc_style/authoring/
light.rs

1//! Light sources and the remaining surface-style elements.
2//!
3//! # Normalised ratios are bounded, and the bound is load-bearing
4//!
5//! `AmbientIntensity`, `Intensity` and `Transparency` are all
6//! `IfcNormalisedRatioMeasure`, which IFC defines as 0.0 to 1.0
7//! inclusive. A renderer handed 2.5 either clamps it or blows out the
8//! image, and neither is what the file said. The existing
9//! [`super::validate_ratio`] helper already enforces this for
10//! shading, so the light sources reuse it rather than restating the
11//! bound.
12//!
13//! # A spot light's two angles are not interchangeable
14//!
15//! `SpreadAngle` is the cone the light fills; `BeamWidthAngle` is the
16//! cone at full intensity. Both are `IfcPositivePlaneAngleMeasure`, so
17//! neither may be zero, and the schema does not require one to be
18//! larger than the other -- some exporters write a beam wider than the
19//! spread to mean "no falloff". Refusing that would reject valid
20//! files, so the writer checks positivity and leaves the relationship
21//! alone.
22
23use ifc_model::{EntityId, Model, Transaction, Value};
24use ifc_schema::Schema;
25
26use crate::authoring::{build_named, invalid_authoring, validate_ratio, validate_ref};
27use crate::StyleResult;
28
29/// The four attributes every `IfcLightSource` carries.
30#[derive(Debug, Clone, Copy)]
31#[non_exhaustive]
32pub struct LightSourceDraft<'a> {
33    /// `Name`.
34    pub name: Option<&'a str>,
35    /// `LightColour`: an `IfcColourRgb`. Required.
36    pub light_colour: EntityId,
37    /// `AmbientIntensity`, a normalised ratio.
38    pub ambient_intensity: Option<f64>,
39    /// `Intensity`, a normalised ratio.
40    pub intensity: Option<f64>,
41}
42
43impl<'a> LightSourceDraft<'a> {
44    /// Starts a draft from its required `light_colour`; every other field is
45    /// unset.
46    #[must_use]
47    pub fn new(light_colour: EntityId) -> Self {
48        Self {
49            name: None,
50            light_colour,
51            ambient_intensity: None,
52            intensity: None,
53        }
54    }
55
56    /// Sets `name`.
57    ///
58    /// `Name`.
59    #[must_use]
60    pub fn name(mut self, value: &'a str) -> Self {
61        self.name = Some(value);
62        self
63    }
64
65    /// Sets `ambient_intensity`.
66    ///
67    /// `AmbientIntensity`, a normalised ratio.
68    #[must_use]
69    pub fn ambient_intensity(mut self, value: f64) -> Self {
70        self.ambient_intensity = Some(value);
71        self
72    }
73
74    /// Sets `intensity`.
75    ///
76    /// `Intensity`, a normalised ratio.
77    #[must_use]
78    pub fn intensity(mut self, value: f64) -> Self {
79        self.intensity = Some(value);
80        self
81    }
82}
83
84/// Attenuation over distance, as three coefficients.
85///
86/// The renderer divides by `constant + distance * d + quadric * d^2`.
87/// All three being zero makes that divisor zero, so the combination is
88/// refused.
89#[derive(Debug, Clone, Copy)]
90pub struct Attenuation {
91    /// `ConstantAttenuation`.
92    pub constant: f64,
93    /// `DistanceAttenuation`.
94    pub distance: f64,
95    /// `QuadricAttenuation`.
96    pub quadric: f64,
97}
98
99fn check_light(entity: &'static str, draft: &LightSourceDraft<'_>) -> StyleResult<()> {
100    if let Some(value) = draft.ambient_intensity {
101        validate_ratio(entity, "AmbientIntensity", value)?;
102    }
103    if let Some(value) = draft.intensity {
104        validate_ratio(entity, "Intensity", value)?;
105    }
106    Ok(())
107}
108
109fn light_values<'a>(draft: &LightSourceDraft<'a>) -> Vec<(&'static str, Value)> {
110    let mut values = vec![("LightColour", Value::Ref(draft.light_colour))];
111    if let Some(name) = draft.name {
112        values.push(("Name", Value::Text(name.into())));
113    }
114    if let Some(value) = draft.ambient_intensity {
115        values.push(("AmbientIntensity", Value::Real(value)));
116    }
117    if let Some(value) = draft.intensity {
118        values.push(("Intensity", Value::Real(value)));
119    }
120    values
121}
122
123fn check_attenuation(entity: &'static str, attenuation: &Attenuation) -> StyleResult<()> {
124    let all = [
125        ("ConstantAttenuation", attenuation.constant),
126        ("DistanceAttenuation", attenuation.distance),
127        ("QuadricAttenuation", attenuation.quadric),
128    ];
129    for (attribute, value) in all {
130        if !value.is_finite() {
131            return Err(invalid_authoring(
132                entity,
133                attribute,
134                format!("expected a finite coefficient, got {value}"),
135            ));
136        }
137    }
138    if all.iter().all(|(_, value)| *value == 0.0) {
139        return Err(invalid_authoring(
140            entity,
141            "ConstantAttenuation",
142            "all three coefficients zero leaves no attenuation function",
143        ));
144    }
145    Ok(())
146}
147
148/// Stage an `IfcLightSourceAmbient`: light with no position or direction.
149///
150/// # Errors
151///
152/// Refuses an out-of-range normalised ratio and a `light_colour` that
153/// does not resolve to an `IfcColourRgb`.
154pub fn create_light_source_ambient(
155    tx: &mut Transaction,
156    model: &Model,
157    schema: &Schema,
158    draft: LightSourceDraft<'_>,
159) -> StyleResult<EntityId> {
160    check_light("IfcLightSourceAmbient", &draft)?;
161    validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
162    Ok(tx.create(build_named(
163        schema,
164        "IfcLightSourceAmbient",
165        light_values(&draft),
166    )?))
167}
168
169/// Stage an `IfcLightSourceDirectional`: parallel rays, no position.
170///
171/// # Errors
172///
173/// Refuses an out-of-range normalised ratio, and references that do
174/// not resolve to their declared types.
175pub fn create_light_source_directional(
176    tx: &mut Transaction,
177    model: &Model,
178    schema: &Schema,
179    draft: LightSourceDraft<'_>,
180    orientation: EntityId,
181) -> StyleResult<EntityId> {
182    check_light("IfcLightSourceDirectional", &draft)?;
183    validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
184    validate_ref(tx, model, schema, orientation, "IfcDirection")?;
185
186    let mut values = light_values(&draft);
187    values.push(("Orientation", Value::Ref(orientation)));
188    Ok(tx.create(build_named(schema, "IfcLightSourceDirectional", values)?))
189}
190
191/// Stage an `IfcLightSourcePositional`: a point light with falloff.
192///
193/// # Errors
194///
195/// Refuses an out-of-range normalised ratio, a non-positive radius,
196/// a non-finite or all-zero attenuation, and references that do not
197/// resolve to their declared types.
198pub fn create_light_source_positional(
199    tx: &mut Transaction,
200    model: &Model,
201    schema: &Schema,
202    draft: LightSourceDraft<'_>,
203    point: PointLight,
204) -> StyleResult<EntityId> {
205    let PointLight {
206        position,
207        radius,
208        attenuation,
209    } = point;
210    check_light("IfcLightSourcePositional", &draft)?;
211    if !radius.is_finite() || radius <= 0.0 {
212        return Err(invalid_authoring(
213            "IfcLightSourcePositional",
214            "Radius",
215            format!("expected a positive length, got {radius}"),
216        ));
217    }
218    check_attenuation("IfcLightSourcePositional", &attenuation)?;
219    validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
220    validate_ref(tx, model, schema, position, "IfcCartesianPoint")?;
221
222    let mut values = light_values(&draft);
223    values.extend([
224        ("Position", Value::Ref(position)),
225        ("Radius", Value::Real(radius)),
226        ("ConstantAttenuation", Value::Real(attenuation.constant)),
227        ("DistanceAttenuation", Value::Real(attenuation.distance)),
228        ("QuadricAttenuation", Value::Real(attenuation.quadric)),
229    ]);
230    Ok(tx.create(build_named(schema, "IfcLightSourcePositional", values)?))
231}
232
233/// Where a light sits and how it falls off.
234///
235/// Position, radius and attenuation are not independent knobs: they
236/// together describe one point emitter, and every entity carrying one
237/// carries all three. Grouping them keeps the spot-light signature
238/// honest rather than a seven-argument list where two adjacent `f64`
239/// parameters invite transposition.
240#[derive(Debug, Clone, Copy)]
241pub struct PointLight {
242    /// `Position`: an `IfcCartesianPoint`.
243    pub position: EntityId,
244    /// `Radius`: a positive length.
245    pub radius: f64,
246    /// The three attenuation coefficients.
247    pub attenuation: Attenuation,
248}
249
250impl Default for Attenuation {
251    /// No falloff: intensity is constant with distance.
252    ///
253    /// Deriving `Default` would give all three zeros, which makes the
254    /// attenuation polynomial evaluate to zero at every distance: a
255    /// light that emits nothing. The neutral value is constant = 1.
256    fn default() -> Self {
257        Self {
258            constant: 1.0,
259            distance: 0.0,
260            quadric: 0.0,
261        }
262    }
263}
264
265/// The cone geometry of a spot light.
266#[derive(Debug, Clone, Copy)]
267pub struct SpotCone {
268    /// `Orientation`: an `IfcDirection`.
269    pub orientation: EntityId,
270    /// `SpreadAngle`: the full cone, a positive plane angle.
271    pub spread_angle: f64,
272    /// `BeamWidthAngle`: the full-intensity cone, a positive angle.
273    pub beam_width_angle: f64,
274    /// `ConcentrationExponent`: falloff sharpness.
275    pub concentration_exponent: Option<f64>,
276}
277
278/// Stage an `IfcLightSourceSpot`.
279///
280/// # Errors
281///
282/// Everything [`create_light_source_positional`] refuses, plus a
283/// non-positive spread or beam width angle.
284pub fn create_light_source_spot(
285    tx: &mut Transaction,
286    model: &Model,
287    schema: &Schema,
288    draft: LightSourceDraft<'_>,
289    point: PointLight,
290    cone: SpotCone,
291) -> StyleResult<EntityId> {
292    let PointLight {
293        position,
294        radius,
295        attenuation,
296    } = point;
297    check_light("IfcLightSourceSpot", &draft)?;
298    if !radius.is_finite() || radius <= 0.0 {
299        return Err(invalid_authoring(
300            "IfcLightSourceSpot",
301            "Radius",
302            format!("expected a positive length, got {radius}"),
303        ));
304    }
305    check_attenuation("IfcLightSourceSpot", &attenuation)?;
306
307    for (attribute, value) in [
308        ("SpreadAngle", cone.spread_angle),
309        ("BeamWidthAngle", cone.beam_width_angle),
310    ] {
311        if !value.is_finite() || value <= 0.0 {
312            return Err(invalid_authoring(
313                "IfcLightSourceSpot",
314                attribute,
315                format!("expected a positive plane angle, got {value}"),
316            ));
317        }
318    }
319
320    validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
321    validate_ref(tx, model, schema, position, "IfcCartesianPoint")?;
322    validate_ref(tx, model, schema, cone.orientation, "IfcDirection")?;
323
324    let mut values = light_values(&draft);
325    values.extend([
326        ("Position", Value::Ref(position)),
327        ("Radius", Value::Real(radius)),
328        ("ConstantAttenuation", Value::Real(attenuation.constant)),
329        ("DistanceAttenuation", Value::Real(attenuation.distance)),
330        ("QuadricAttenuation", Value::Real(attenuation.quadric)),
331        ("Orientation", Value::Ref(cone.orientation)),
332        ("SpreadAngle", Value::Real(cone.spread_angle)),
333        ("BeamWidthAngle", Value::Real(cone.beam_width_angle)),
334    ]);
335    if let Some(value) = cone.concentration_exponent {
336        values.push(("ConcentrationExponent", Value::Real(value)));
337    }
338    Ok(tx.create(build_named(schema, "IfcLightSourceSpot", values)?))
339}
340
341/// Stage an `IfcSurfaceStyleLighting`: the four physical colour terms.
342///
343/// # Errors
344///
345/// Refuses any colour that does not resolve to an `IfcColourRgb`.
346pub fn create_surface_style_lighting(
347    tx: &mut Transaction,
348    model: &Model,
349    schema: &Schema,
350    diffuse_transmission: EntityId,
351    diffuse_reflection: EntityId,
352    transmission: EntityId,
353    reflectance: EntityId,
354) -> StyleResult<EntityId> {
355    for colour in [
356        diffuse_transmission,
357        diffuse_reflection,
358        transmission,
359        reflectance,
360    ] {
361        validate_ref(tx, model, schema, colour, "IfcColourRgb")?;
362    }
363
364    let values = vec![
365        (
366            "DiffuseTransmissionColour",
367            Value::Ref(diffuse_transmission),
368        ),
369        ("DiffuseReflectionColour", Value::Ref(diffuse_reflection)),
370        ("TransmissionColour", Value::Ref(transmission)),
371        ("ReflectanceColour", Value::Ref(reflectance)),
372    ];
373    Ok(tx.create(build_named(schema, "IfcSurfaceStyleLighting", values)?))
374}
375
376/// Stage an `IfcSurfaceStyleRefraction`.
377///
378/// # Errors
379///
380/// Refuses a refraction index below 1.0: no physical medium refracts
381/// less than a vacuum, and a value below one inverts the bend.
382pub fn create_surface_style_refraction(
383    tx: &mut Transaction,
384    schema: &Schema,
385    refraction_index: Option<f64>,
386    dispersion_factor: Option<f64>,
387) -> StyleResult<EntityId> {
388    if let Some(value) = refraction_index {
389        if !value.is_finite() || value < 1.0 {
390            return Err(invalid_authoring(
391                "IfcSurfaceStyleRefraction",
392                "RefractionIndex",
393                format!("expected at least 1.0, the vacuum index, got {value}"),
394            ));
395        }
396    }
397    if let Some(value) = dispersion_factor {
398        if !value.is_finite() {
399            return Err(invalid_authoring(
400                "IfcSurfaceStyleRefraction",
401                "DispersionFactor",
402                format!("expected a finite factor, got {value}"),
403            ));
404        }
405    }
406
407    let mut values = Vec::new();
408    if let Some(value) = refraction_index {
409        values.push(("RefractionIndex", Value::Real(value)));
410    }
411    if let Some(value) = dispersion_factor {
412        values.push(("DispersionFactor", Value::Real(value)));
413    }
414    Ok(tx.create(build_named(schema, "IfcSurfaceStyleRefraction", values)?))
415}
416
417/// The goniometric-only attributes of an `IfcLightSourceGoniometric`.
418#[derive(Debug, Clone, Copy)]
419pub struct GoniometricLight {
420    /// `Position`, an `IfcAxis2Placement3D`.
421    pub position: EntityId,
422    /// `ColourAppearance`, an `IfcColourRgb`.
423    pub colour_appearance: Option<EntityId>,
424    /// `ColourTemperature`, in kelvin.
425    pub colour_temperature: f64,
426    /// `LuminousFlux`, in lumen.
427    pub luminous_flux: f64,
428    /// `LightEmissionSource`, an `IfcLightEmissionSourceEnum` token.
429    pub emission_source: &'static str,
430    /// `LightDistributionDataSource`: an `IfcLightIntensityDistribution`
431    /// or an `IfcExternalReference`.
432    pub distribution_data_source: EntityId,
433}
434
435/// Stage an `IfcLightSourceGoniometric`.
436///
437/// A photometrically defined luminaire: rather than a radius or a
438/// cone, it carries a measured intensity distribution, which is what a
439/// lighting calculation actually needs.
440///
441/// # Errors
442///
443/// Refuses an out-of-range intensity, a colour reference that is not an
444/// `IfcColourRgb`, a non-positive colour temperature or luminous flux
445/// (both are absolute physical measures), and an emission-source token
446/// the schema does not declare.
447pub fn create_light_source_goniometric(
448    tx: &mut Transaction,
449    model: &Model,
450    schema: &Schema,
451    draft: LightSourceDraft<'_>,
452    light: GoniometricLight,
453) -> StyleResult<EntityId> {
454    const ENTITY: &str = "IfcLightSourceGoniometric";
455    check_light(ENTITY, &draft)?;
456    validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
457    if let Some(colour) = light.colour_appearance {
458        validate_ref(tx, model, schema, colour, "IfcColourRgb")?;
459    }
460    for (value, attribute) in [
461        (light.colour_temperature, "ColourTemperature"),
462        (light.luminous_flux, "LuminousFlux"),
463    ] {
464        // Both are absolute measures: zero kelvin or zero lumen is not
465        // a dim light, it is a light that cannot exist.
466        if !value.is_finite() || value <= 0.0 {
467            return Err(invalid_authoring(
468                ENTITY,
469                attribute,
470                format!("expected a positive measure, got {value}"),
471            ));
472        }
473    }
474    let declared = schema
475        .attributes(ENTITY)
476        .iter()
477        .find(|a| a.name.eq_ignore_ascii_case("LightEmissionSource"))
478        .and_then(|a| schema.type_def(&a.type_name))
479        .is_some_and(|def| match &def.kind {
480            ifc_schema::TypeKind::Enumeration(values) => values
481                .iter()
482                .any(|v| v.eq_ignore_ascii_case(light.emission_source)),
483            _ => false,
484        });
485    if !declared {
486        return Err(invalid_authoring(
487            ENTITY,
488            "LightEmissionSource",
489            light.emission_source,
490        ));
491    }
492
493    let mut values = light_values(&draft);
494    values.push(("Position", Value::Ref(light.position)));
495    if let Some(colour) = light.colour_appearance {
496        values.push(("ColourAppearance", Value::Ref(colour)));
497    }
498    values.push(("ColourTemperature", Value::Real(light.colour_temperature)));
499    values.push(("LuminousFlux", Value::Real(light.luminous_flux)));
500    values.push((
501        "LightEmissionSource",
502        Value::Enum(light.emission_source.into()),
503    ));
504    values.push((
505        "LightDistributionDataSource",
506        Value::Ref(light.distribution_data_source),
507    ));
508    Ok(tx.create(build_named(schema, ENTITY, values)?))
509}