Skip to main content

mittens_engine/engine/ecs/component/
camera_2d.rs

1use crate::engine::ecs::ComponentId;
2use crate::engine::ecs::component::Component;
3use crate::engine::graphics::CameraTarget;
4
5/// 2D camera component.
6///
7/// This is a sibling of `Camera3DComponent` (3D-ish view/proj camera).
8/// The 2D camera drives a global NDC translation used by the mesh vertex shader.
9#[derive(Debug, Clone)]
10pub struct Camera2DComponent {
11    pub handle: Option<crate::engine::ecs::system::camera_system::CameraHandle>,
12    // Cached ECS id (runtime-only). Filled in during init.
13    pub component_id: Option<ComponentId>,
14    /// Which output this camera targets for activation.
15    pub target: CameraTarget,
16}
17
18impl Camera2DComponent {
19    pub fn new() -> Self {
20        Self {
21            handle: None,
22            component_id: None,
23            target: CameraTarget::Window,
24        }
25    }
26
27    /// Ask the CameraSystem to make this the active camera.
28    pub fn make_active_camera(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter) {
29        if self.handle.is_some() {
30            if let Some(component) = self.component_id {
31                emit.push_intent_now(
32                    component,
33                    crate::engine::ecs::IntentValue::MakeActiveCamera {
34                        component_ids: vec![component],
35                    },
36                );
37            }
38        }
39    }
40}
41
42impl Default for Camera2DComponent {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48impl Component for Camera2DComponent {
49    fn name(&self) -> &'static str {
50        "camera2d"
51    }
52
53    fn as_any(&self) -> &dyn std::any::Any {
54        self
55    }
56
57    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
58        self
59    }
60
61    fn init(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter, component: ComponentId) {
62        self.component_id = Some(component);
63        emit.push_intent_now(
64            component,
65            crate::engine::ecs::IntentValue::RegisterCamera2d {
66                component_ids: vec![component],
67            },
68        );
69    }
70
71    fn to_mms_ast(
72        &self,
73        _world: &crate::engine::ecs::World,
74    ) -> crate::scripting::ast::ComponentExpression {
75        use crate::engine::ecs::component::ce_helpers::*;
76        let target = match self.target {
77            CameraTarget::Window => "window",
78            CameraTarget::Xr => "xr",
79        };
80        ce("Camera2D").with_call("target", vec![s(target)])
81    }
82}