Skip to main content

mittens_engine/engine/ecs/component/
opacity.rs

1use crate::engine::ecs::ComponentId;
2use crate::engine::ecs::component::Component;
3
4/// Per-instance opacity multiplier for a renderable.
5///
6/// Intended to be attached as a descendant of a `RenderableComponent`.
7///
8/// Note: opacity is a *multiplier* (0..1). It combines with the instance color alpha and
9/// any sampled texture alpha in the shader.
10#[derive(Debug, Clone, Copy)]
11pub struct OpacityComponent {
12    pub opacity: f32,
13    /// If true, this renderable should be treated as requiring correct multi-layer blending.
14    ///
15    /// This routes the instance into the sorted (slow) transparent pass.
16    /// When false, the instance can use the instanced (fast) transparent pass.
17    pub multiple_layers: bool,
18}
19
20impl OpacityComponent {
21    pub fn new() -> Self {
22        Self {
23            opacity: 1.0,
24            multiple_layers: false,
25        }
26    }
27
28    /// Convenience: set opacity from an 8-bit value (0..255).
29    pub fn with_value(mut self, value: u8) -> Self {
30        self.opacity = (value as f32) / 255.0;
31        self
32    }
33
34    pub fn with_opacity(mut self, opacity: f32) -> Self {
35        self.opacity = if opacity.is_finite() {
36            opacity.clamp(0.0, 1.0)
37        } else {
38            1.0
39        };
40        self
41    }
42
43    /// Mark this opacity as requiring correct multi-layer blending.
44    ///
45    /// This opts the renderable into the sorted transparent pass (no instancing).
46    pub fn with_multiple_layers(mut self) -> Self {
47        self.multiple_layers = true;
48        self
49    }
50}
51
52impl Default for OpacityComponent {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58impl Component for OpacityComponent {
59    fn name(&self) -> &'static str {
60        "opacity"
61    }
62
63    fn as_any(&self) -> &dyn std::any::Any {
64        self
65    }
66
67    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
68        self
69    }
70
71    fn init(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter, component: ComponentId) {
72        emit.push_intent_now(
73            component,
74            crate::engine::ecs::IntentValue::RegisterOpacity {
75                component_ids: vec![component],
76            },
77        );
78    }
79
80    fn to_mms_ast(
81        &self,
82        _world: &crate::engine::ecs::World,
83    ) -> crate::scripting::ast::ComponentExpression {
84        use crate::engine::ecs::component::ce_helpers::*;
85        let mut ce = ce_call("Opacity", "opacity", vec![num(self.opacity as f64)]);
86        if self.multiple_layers {
87            ce = ce.with_call("multiple_layers", vec![]);
88        }
89        ce
90    }
91}