gldf-rs 0.5.0

GLDF (General Lighting Data Format) parser and writer for Rust, specifically for the Rust/WASM target as such designed for JSON format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Photometric file export and variant-aware patching.
//!
//! Pure-eulumdat helpers extracted from the WASM viewer so any consumer
//! (CLI, FFI, Python, server) can produce per-variant LDT/IES/ATLA
//! downloads with the variant's resolved lumens/watts patched onto the
//! source photometry.
//!
//! Requires the `eulumdat` feature.

use eulumdat::Eulumdat;

use crate::gldf::general_definitions::GeneralDefinitions;
use crate::gldf::product_definitions::{ProductDefinitions, Variant};

/// Export format for per-variant photometry downloads.
///
/// LDT/IES are the industry-standard photometric formats; ATLA JSON/XML
/// carry richer metadata (lossless-ish round-trip via the eulumdat-rs
/// `atla` module). LDT↔IES round-trips lose some details, so prefer the
/// source format when the downstream tool accepts it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PhotometryExportFormat {
    /// EULUMDAT (`.ldt`) — European industry standard.
    Ldt,
    /// IES LM-63 (`.ies`) — North American industry standard.
    Ies,
    /// ATLA JSON — richer-metadata photometric exchange format.
    AtlaJson,
    /// ATLA XML — richer-metadata photometric exchange format.
    AtlaXml,
}

impl PhotometryExportFormat {
    /// Recommended filename extension (without leading dot).
    pub fn extension(self) -> &'static str {
        match self {
            Self::Ldt => "ldt",
            Self::Ies => "ies",
            Self::AtlaJson => "json",
            Self::AtlaXml => "xml",
        }
    }

    /// MIME type for HTTP responses / `Blob` construction.
    pub fn mime(self) -> &'static str {
        match self {
            Self::Ldt | Self::Ies => "text/plain",
            Self::AtlaJson => "application/json",
            Self::AtlaXml => "application/xml",
        }
    }

    /// Human-readable label suitable for dropdown menus.
    pub fn label(self) -> &'static str {
        match self {
            Self::Ldt => "LDT (EULUMDAT)",
            Self::Ies => "IES",
            Self::AtlaJson => "ATLA JSON",
            Self::AtlaXml => "ATLA XML",
        }
    }

    /// Parse a stable identifier (`"ldt"`, `"ies"`, `"atla_json"`,
    /// `"atla_xml"`). Returns `None` for unrecognized values.
    // Public API returning `Option`; `FromStr` would need an error type.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "ldt" => Some(Self::Ldt),
            "ies" => Some(Self::Ies),
            "atla_json" => Some(Self::AtlaJson),
            "atla_xml" => Some(Self::AtlaXml),
            _ => None,
        }
    }

    /// Stable identifier (inverse of [`Self::from_str`]). Suitable for
    /// `<select>` option values, query strings, etc.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ldt => "ldt",
            Self::Ies => "ies",
            Self::AtlaJson => "atla_json",
            Self::AtlaXml => "atla_xml",
        }
    }

    /// Smart default based on the source filename's extension. `.ies`
    /// input → [`Self::Ies`]; everything else → [`Self::Ldt`]. JSON/XML
    /// never auto-default — they're explicit user choices.
    pub fn default_for_source(filename: Option<&str>) -> Self {
        let lower = filename.map(|n| n.to_lowercase()).unwrap_or_default();
        if lower.ends_with(".ies") {
            Self::Ies
        } else {
            Self::Ldt
        }
    }
}

/// Render the chosen format from a parsed [`Eulumdat`]. Returns the
/// serialized bytes, or `None` if ATLA serialization fails.
///
/// All four formats round-trip the *patched* `Eulumdat` object, so a 50 W
/// variant downloaded as IES carries the 50 W wattage even when the
/// source LDT had 0 W. ATLA JSON/XML preserve fields LDT/IES drop, so
/// prefer them when the downstream tool can consume them.
pub fn export_photometry(ldt: &Eulumdat, format: PhotometryExportFormat) -> Option<Vec<u8>> {
    match format {
        PhotometryExportFormat::Ldt => Some(ldt.to_ldt().into_bytes()),
        PhotometryExportFormat::Ies => Some(eulumdat::IesExporter::export(ldt).into_bytes()),
        PhotometryExportFormat::AtlaJson => {
            let doc = eulumdat::atla::LuminaireOpticalData::from(ldt);
            eulumdat::atla::json::write(&doc)
                .ok()
                .map(String::into_bytes)
        }
        PhotometryExportFormat::AtlaXml => {
            let doc = eulumdat::atla::LuminaireOpticalData::from(ldt);
            eulumdat::atla::xml::write(&doc)
                .ok()
                .map(String::into_bytes)
        }
    }
}

/// Per-emitter photometry resolution for a single variant.
///
/// One variant can have multiple emitters (multi-emitter floodlights,
/// mixed direct/indirect, etc.), so [`resolve_variant_photometries`]
/// returns a `Vec` of these. Each entry binds together:
///
/// * which photometry (LDT shape) the emitter uses,
/// * the variant-resolved lumens / watts (walking
///   `FixedLightEmitter → LightSourceReference → FixedLightSource`), and
/// * driver / emergency metadata needed by viewer chrome.
///
/// `lumens` / `watts` may be `None` when the file doesn't declare them at
/// the resolved level — the LDT-native value is the fallback in that case.
#[derive(Debug, Clone)]
pub struct VariantPhotometryResolution {
    /// Photometry id this emitter resolves to (the LDT shape).
    pub photometry_id: String,
    /// Variant-level rated luminous flux, if `FixedLightEmitter.RatedLuminousFlux`
    /// or `ChangeableLightEmitter`'s nominal flux is set.
    ///
    /// For `EmergencyOnly` emitters the XSD's `RatedLuminousFlux` is the
    /// *emergency-mode* flux (those emitters have no normal mode), so we
    /// don't surface it as a normal-operation lumens override — `lumens`
    /// stays `None` for that case to avoid claiming `100 lm / 81 W = 1.2
    /// lm/W` as the variant's efficacy.
    pub lumens: Option<i32>,
    /// Variant-level rated input power, walked through the
    /// `LightSourceReference` to `FixedLightSource.RatedInputPower`.
    /// Suppressed for `EmergencyOnly` emitters (same reason as `lumens`).
    pub watts: Option<f64>,
    /// Light source id that supplied the wattage (for display / tooltip).
    pub light_source_id: Option<String>,
    /// `FixedLightEmitter.@emergencyBehaviour` — `None` (no attribute),
    /// `"None"` (explicit normal), `"Combined"` (normal + emergency), or
    /// `"EmergencyOnly"`. Drives viewer chrome and suppresses the
    /// calc/patch for `EmergencyOnly`.
    pub emergency_behaviour: Option<String>,
    /// `FixedLightEmitter.ControlGearReference.@controlGearId` — points at
    /// the driver in `GeneralDefinitions/ControlGears`. Used by the
    /// Electrical viewer to render driver details per variant.
    pub control_gear_id: Option<String>,
    /// `EmitterReference.EmitterObjectExternalName` — the name of the
    /// emitter object inside the referenced 3D geometry (e.g. the L3D LEO
    /// `partName` "LEO0"/"LEO1"). Lets a consumer match this photometry to
    /// a specific light-emitting object when a luminaire has several (e.g.
    /// the two heads of a twin spotlight). Empty when the reference didn't
    /// name one.
    pub emitter_external_name: String,
}

impl VariantPhotometryResolution {
    /// `true` when this emitter only operates during emergency conditions.
    /// Callers typically skip the calc column and the patch for these —
    /// emergency flux against full-load wattage is a meaningless ratio.
    pub fn is_emergency_only(&self) -> bool {
        matches!(self.emergency_behaviour.as_deref(), Some("EmergencyOnly"))
    }
}

/// Resolve every emitter chain on a single variant to its
/// `(photometry_id, lumens, watts)` tuple plus driver / emergency
/// metadata.
///
/// Walks all three emitter-reference branches the XSD allows:
/// `Variant > Geometry > EmitterReference` (bare),
/// `... > SimpleGeometryReference` (with `@emitterId`),
/// `... > ModelGeometryReference > EmitterReference` (nested form).
///
/// `product` is currently reserved for future use (Equipment lookups for
/// `ChangeableLightEmitter` driver wiring). `general` carries the
/// `<Emitters>` and `<LightSources>` pools that the resolver dereferences.
pub fn resolve_variant_photometries(
    product: &ProductDefinitions,
    variant: &Variant,
    general: &GeneralDefinitions,
) -> Vec<VariantPhotometryResolution> {
    let _ = product; // Reserved for future use (Equipment lookups, etc.)

    // Keep each emitter id paired with the EmitterObjectExternalName from the
    // reference that named it (the L3D LEO partName), so a multi-emitter
    // luminaire can map each photometry back to its specific emitter object.
    // SimpleGeometryReference has no external-name child, so it pairs with "".
    let mut emitter_refs: Vec<(String, String)> = Vec::new();
    if let Some(ref geom) = variant.geometry {
        // Bare Variant>Geometry>EmitterReference has no external-name child.
        for er in &geom.emitter_reference {
            emitter_refs.push((er.emitter_id.clone(), String::new()));
        }
        if let Some(ref sgr) = geom.simple_geometry_reference {
            emitter_refs.push((sgr.emitter_id.clone(), String::new()));
        }
        if let Some(ref mgr) = geom.model_geometry_reference {
            for er in &mgr.emitter_reference {
                emitter_refs.push((
                    er.emitter_id.clone(),
                    er.emitter_object_external_name.clone(),
                ));
            }
        }
    }

    let emitters = match general.emitters.as_ref() {
        Some(e) => &e.emitter,
        None => return Vec::new(),
    };
    let light_sources = general.light_sources.as_ref();

    let mut out = Vec::new();
    for (eid, external_name) in &emitter_refs {
        let Some(emitter) = emitters.iter().find(|e| &e.id == eid) else {
            continue;
        };
        // FixedLightEmitter: variant-level lumens + light_source_reference for watts.
        for fle in &emitter.fixed_light_emitter {
            let photometry_id = fle.photometry_reference.photometry_id.clone();
            let is_emergency_only =
                matches!(fle.emergency_behaviour.as_deref(), Some("EmergencyOnly"));
            // For EmergencyOnly emitters, RatedLuminousFlux is the emergency
            // flux and there is no normal-mode wattage on the
            // light_source_reference (the LightSource it points at carries
            // the *full-load* W, not the emergency W). Pairing those two
            // gives a meaningless ratio (100 lm / 81 W ≈ 1.2 lm/W on the
            // SLV Tria 2). Skip the override entirely; the LDT-native calc
            // is similarly off but viewers suppress Calc for these.
            let lumens = if is_emergency_only {
                None
            } else {
                fle.rated_luminous_flux
            };
            let (light_source_id, watts) = if is_emergency_only {
                (
                    fle.light_source_reference.fixed_light_source_id.clone(),
                    None,
                )
            } else {
                match (
                    fle.light_source_reference.fixed_light_source_id.as_ref(),
                    light_sources,
                ) {
                    (Some(ls_id), Some(ls)) => {
                        let watts = ls
                            .fixed_light_source
                            .iter()
                            .find(|s| &s.id == ls_id)
                            .and_then(|s| s.rated_input_power);
                        (Some(ls_id.clone()), watts)
                    }
                    _ => (None, None),
                }
            };
            out.push(VariantPhotometryResolution {
                photometry_id,
                lumens,
                watts,
                light_source_id,
                emergency_behaviour: fle.emergency_behaviour.clone(),
                control_gear_id: fle
                    .control_gear_reference
                    .as_ref()
                    .map(|cgr| cgr.control_gear_id.clone()),
                emitter_external_name: external_name.clone(),
            });
        }
        // ChangeableLightEmitter has no light_source_reference at the emitter
        // level (the XSD pairs Changeable bulbs with control gear via
        // Equipment, not at the emitter). Phase 1: surface them with
        // photometry_id only — wattage shows as None and the calc falls
        // back to the LDT value, which is correct for replaceable bulbs.
        for cle in &emitter.changeable_light_emitter {
            out.push(VariantPhotometryResolution {
                photometry_id: cle.photometry_reference.photometry_id.clone(),
                lumens: None,
                watts: None,
                light_source_id: None,
                emergency_behaviour: cle.emergency_behaviour.clone(),
                // ChangeableLightEmitter has no ControlGearReference at
                // the emitter level (XSD wires gear via Equipment for
                // replaceable bulbs). Phase 1 leaves this None.
                control_gear_id: None,
                emitter_external_name: external_name.clone(),
            });
        }
    }
    out
}

/// Re-emit an LDT with the variant-resolved lumens / watts patched onto
/// `lamp_sets[0]`. This is what makes downstream eulumdat consumers
/// report the correct lm/W instead of the LDT-native 0.0 lm/W when the
/// GLDF variant overrides them.
///
/// Why `[0]` only: most LDT fixtures carry one lamp_set; multi-set LDTs
/// (stacked driver options) are rare and the GLDF variant model already
/// disambiguates them via per-variant references, so each variant
/// effectively pins one lamp_set anyway.
///
/// Returns `None` when the bytes don't parse, or when neither override
/// is supplied (no work to do — caller should keep the original).
///
/// **Always emits LDT bytes**, regardless of the source format. This
/// matches the pre-multi-format behaviour but is a footgun when the
/// source was TM-33 XML — the consumer ends up with `.xml`-named LDT
/// bytes. New code should call [`patch_photometry_for_variant`]
/// instead, which lets the caller choose the output format.
pub fn patch_ldt_for_variant(
    raw_bytes: &[u8],
    lumens: Option<i32>,
    watts: Option<f64>,
) -> Option<Vec<u8>> {
    let ldt = parse_and_overlay(raw_bytes, lumens, watts)?;
    Some(ldt.to_ldt().into_bytes())
}

/// Parse photometric bytes (LDT / IES / TM-33 XML), overlay the
/// variant's lumens + watts onto `lamp_sets[0]`, and serialise the
/// result in `format`. The single entry-point that variant downloads
/// in WASM / CLI should call when they want format-explicit output.
///
/// Returns `None` when:
///   * neither override is supplied (no work to do), OR
///   * bytes don't parse as any supported format, OR
///   * ATLA JSON/XML emit fails (unreachable in practice).
///
/// The format choice is orthogonal to the source — patching a TM-33
/// XML to LDT works fine, as does LDT → TM-33 XML, etc.
pub fn patch_photometry_for_variant(
    raw_bytes: &[u8],
    lumens: Option<i32>,
    watts: Option<f64>,
    format: PhotometryExportFormat,
) -> Option<Vec<u8>> {
    let ldt = parse_and_overlay(raw_bytes, lumens, watts)?;
    export_photometry(&ldt, format)
}

/// Parse photometric bytes (LDT / IES / TM-33 XML) and emit them in
/// `format` without applying any variant overlay. The "convert only"
/// counterpart to [`patch_photometry_for_variant`] — useful when the
/// caller wants the raw photometry in a different format than the
/// source (e.g. variant has no flux/watts overrides but the GLDF was
/// merged into TM-33 so the user wants LDT back).
///
/// Returns `None` when the bytes don't parse as any supported format.
pub fn convert_raw_photometry(raw_bytes: &[u8], format: PhotometryExportFormat) -> Option<Vec<u8>> {
    let s = std::str::from_utf8(raw_bytes).ok()?;
    let trimmed = s.trim_start_matches('\u{feff}').trim_start();
    let ldt = if trimmed.starts_with('<') {
        let doc = eulumdat::atla::xml::parse(s).ok()?;
        let ldt: Eulumdat = (&doc).into();
        ldt
    } else if let Ok(ldt) = Eulumdat::parse(s) {
        ldt
    } else {
        eulumdat::IesParser::parse(s).ok()?
    };
    export_photometry(&ldt, format)
}

/// Shared parse + overlay step used by both
/// [`patch_ldt_for_variant`] and [`patch_photometry_for_variant`].
///
/// Accepts LDT (most common), IES (eulumdat::IesParser falls back to
/// Eulumdat shape) and TM-33 XML (the file may be the shared
/// ldc/iesxml carrier produced by tm33_to_gldf — see that fn for the
/// single-file dual-reference scheme).
///
/// Returns `None` when neither override is set or the bytes don't
/// parse — both are no-op signals the caller propagates.
fn parse_and_overlay(
    raw_bytes: &[u8],
    lumens: Option<i32>,
    watts: Option<f64>,
) -> Option<Eulumdat> {
    if lumens.is_none() && watts.is_none() {
        return None;
    }
    let s = std::str::from_utf8(raw_bytes).ok()?;
    let trimmed = s.trim_start_matches('\u{feff}').trim_start();
    let mut ldt = if trimmed.starts_with('<') {
        let doc = eulumdat::atla::xml::parse(s).ok()?;
        let ldt: Eulumdat = (&doc).into();
        ldt
    } else if let Ok(ldt) = Eulumdat::parse(s) {
        ldt
    } else {
        eulumdat::IesParser::parse(s).ok()?
    };
    if let Some(set) = ldt.lamp_sets.first_mut() {
        if let Some(w) = watts {
            set.wattage_with_ballast = w;
        }
        if let Some(lm) = lumens {
            set.total_luminous_flux = lm as f64;
        }
    }
    Some(ldt)
}

#[cfg(test)]
mod variant_format_tests {
    use super::*;

    fn load_real_ldt() -> Vec<u8> {
        // Use the demo LDT fixture so we exercise the lib's parsers
        // against bytes that actually round-trip in production.
        // CARGO_MANIFEST_DIR resolves to the lib crate; the fixture
        // lives at the workspace root under `tests/data/`.
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
        let path = std::path::Path::new(&manifest_dir).join("../../tests/data/test.ldt");
        std::fs::read(&path)
            .unwrap_or_else(|_| panic!("LDT fixture not found at {}", path.display()))
    }

    /// patch_photometry_for_variant emits TM-33 XML when asked, even
    /// though the source is LDT. This is the round-trip that fixes
    /// the `wide.xml` filename / EULUMDAT bytes bug — the caller can
    /// now pick the format independent of the source.
    #[test]
    fn patches_ldt_and_emits_tm33_xml() {
        let raw = load_real_ldt();
        let bytes =
            patch_photometry_for_variant(&raw, Some(2200), None, PhotometryExportFormat::AtlaXml)
                .expect("conversion succeeds");
        let s = std::str::from_utf8(&bytes).expect("utf8");
        assert!(
            s.contains("<?xml") || s.contains("<LuminaireOpticalData"),
            "expected XML, got: {}",
            &s[..s.len().min(120)]
        );
    }

    /// patch_photometry_for_variant emits IES when asked. Confirms
    /// the IES branch of the format chooser actually returns IES
    /// bytes (rather than LDT, the historical hardcoded format).
    #[test]
    fn patches_ldt_and_emits_ies() {
        let raw = load_real_ldt();
        let bytes =
            patch_photometry_for_variant(&raw, Some(2200), None, PhotometryExportFormat::Ies)
                .expect("conversion succeeds");
        let s = std::str::from_utf8(&bytes).expect("utf8");
        // IES output starts with the `IES:LM-63-…` magic header.
        // Accept LM-63-2002 / LM-63-2019 / legacy IESNA: variants
        // — all of them carry the `IES` token at offset 0.
        assert!(
            s.starts_with("IES"),
            "expected IES output, got: {}",
            &s[..s.len().min(80)]
        );
    }

    /// convert_raw_photometry honours the format choice even without
    /// any overlay — the no-overrides path used when a variant has
    /// no per-emitter flux/watts but the user still wants format
    /// conversion (e.g. TM-33 → LDT).
    #[test]
    fn convert_raw_photometry_format_choice() {
        let raw = load_real_ldt();
        let ies =
            convert_raw_photometry(&raw, PhotometryExportFormat::Ies).expect("ies conversion");
        let ies_str = std::str::from_utf8(&ies).unwrap();
        assert!(
            ies_str.starts_with("IES"),
            "expected IES output, got: {}",
            &ies_str[..ies_str.len().min(80)]
        );
    }
}