Skip to main content

mln_style/
light.rs

1use std::sync::Arc;
2
3use crate::conversion::{Convertible, Error};
4use crate::expression::Functions;
5use crate::property::table::{self, InPlace, OwnerSlot, SetPropertyError, StyleProperty};
6
7crate::properties!(
8    #[expect(non_snake_case, reason = "named like the layers' property sets")]
9    pub mod LightProperties: paint {
10        light_anchor: constant LightAnchorType = LightAnchorType::Viewport,
11        light_position: constant Position = Position::new([1.15_f32, 210.0_f32, 30.0_f32]),
12        light_color: constant Color = Color::white(),
13        light_intensity: constant f32 = 0.5_f32,
14    }
15    use crate::types::LightAnchorType, crate::types::Position, crate::color::Color;
16);
17
18/// The style's light.
19#[derive(Clone, Debug, Default, PartialEq)]
20pub struct Light {
21    pub properties: LightProperties::Transitionable,
22}
23
24impl Light {
25    #[must_use]
26    pub fn new() -> Self {
27        Light::default()
28    }
29
30    /// Sets a property (or `<name>-transition`) from a style JSON value,
31    /// whose expressions parse against `functions`.
32    pub fn set_property(&mut self, name: &str, value: &Convertible<'_>, functions: &Arc<Functions>) -> Option<Error> {
33        set_property(&mut InPlace(self), name, value, functions)
34    }
35
36    /// As [`set_property`](Self::set_property), on a shared light, which is
37    /// copied only if the value changes it.
38    pub fn set_shared_property(
39        light: &mut Arc<Light>,
40        name: &str,
41        value: &Convertible<'_>,
42        functions: &Arc<Functions>,
43    ) -> Option<Error> {
44        set_property(light, name, value, functions)
45    }
46
47    #[must_use]
48    pub fn property(&self, name: &str) -> StyleProperty {
49        table::property(self, name)
50    }
51}
52
53fn set_property<O: OwnerSlot<Light>>(
54    owner: &mut O,
55    name: &str,
56    value: &Convertible<'_>,
57    functions: &Arc<Functions>,
58) -> Option<Error> {
59    match table::set_property(owner, name, value, functions) {
60        Ok(()) => None,
61        Err(SetPropertyError::Invalid(error)) => Some(error),
62        Err(SetPropertyError::Unknown) => Some(Error::new("light doesn't support this property")),
63    }
64}
65
66/// Converts the style's `light`, whose expressions parse against `functions`.
67pub fn convert_light(value: &Convertible<'_>, functions: &Arc<Functions>, error: &mut Error) -> Option<Light> {
68    if !value.is_object() {
69        error.message = "light must be an object".to_owned();
70        return None;
71    }
72
73    let mut light = Light::new();
74    for name in table::names::<Light>() {
75        let Some(member) = value.object_member(&name) else {
76            continue;
77        };
78        if let Some(conversion_error) = light.set_property(&name, &member, functions) {
79            *error = conversion_error;
80            return None;
81        }
82    }
83
84    Some(light)
85}