mittens-engine 0.6.0

A Vulkan and OpenXR scene engine with ECS, reactive signals, and Meow Meow scripting
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
pub mod action;
pub mod ambient_light;
pub mod animation;
pub mod asset_payload;
pub mod audio_band_pass_filter;
pub mod audio_buffer_size;
pub mod audio_clip;
pub mod audio_gain;
pub mod audio_high_pass_filter;
pub mod audio_limiter;
pub mod audio_low_pass_filter;
pub mod audio_mix;
pub mod audio_oscillator;
pub mod audio_output;
pub mod avatar_body_yaw;
pub mod avatar_control;
pub mod background;
pub mod background_color;
pub mod bloom;
pub mod blur_pass;
pub mod bone_rest_pose;
pub mod bounds;
pub mod camera_2d;
pub mod camera_3d;
pub mod camera_xr;
pub mod clock;
pub mod collision;
pub mod collision_shape;
pub mod color;
pub mod component_ref;
pub mod controller_xr;
pub mod data;
pub mod directional_light;
pub mod editor;
pub mod emissive;
pub mod emissive_pass;
pub mod fit_bounds;
pub mod gesture_coord_type;
pub mod gizmo;
pub mod gltf;
pub mod gravity;
pub mod grid;
pub mod html_element;
pub mod http_client;
pub mod http_server;
pub mod ik_chain;
pub mod input;
pub mod input_transform_mode;
pub mod input_xr;
pub mod input_xr_gamepad;
pub mod inspect_layout;
pub mod keyframe;
pub mod kinetic_response;
pub mod layout;
pub mod layout_bounds;
pub mod light_quantization;
pub mod mesh;
pub mod mirror;
pub mod music_note;
pub mod normal_visualisation;
pub mod opacity;
pub mod option;
pub mod overlay;
pub mod pose_capture;
pub mod render_graph;
pub mod router;
pub mod scrolling;
pub mod secondary_motion;
pub mod selectable;
pub mod selection;
pub mod serialize;
pub mod signal_observer_router;
pub mod signal_route_upward;
pub mod skinned_mesh;
pub mod stencil_clip;
pub mod style;
pub mod transparent_cutout;
pub mod xr;

pub mod point_light;
pub mod pointer;
pub mod raycast;
pub mod raycastable;
pub mod raycastable_shape;
pub mod renderable;
pub mod renderer_settings;
pub mod renderer_stats;
pub mod text;
pub mod text_input;
pub mod text_shadow;
pub mod texture;
pub mod texture_filtering;
pub mod transform;
pub mod transform_camera_specific;
pub mod transform_parent;
pub mod transform_pipeline;
pub mod transform_pipeline_map;
pub mod transform_temporal_filter;
pub mod transition;
pub mod uv;

pub use self::gltf::GLTFComponent;
pub use crate::engine::ecs::system::model::collision_types::{CollisionMode, CollisionShape};
pub use action::ActionComponent;
pub use ambient_light::AmbientLightComponent;
pub use animation::AnimationComponent;
pub use animation::AnimationState;
pub use animation::ResolveTargetsMode;
pub use asset_payload::AssetPayloadComponent;
pub use audio_band_pass_filter::*;
pub use audio_buffer_size::AudioBufferSizeComponent;
pub use audio_clip::{AudioClipComponent, AudioClipLoadState, AudioTriggerMode};
pub use audio_gain::*;
pub use audio_high_pass_filter::*;
pub use audio_limiter::*;
pub use audio_low_pass_filter::*;
pub use audio_mix::AudioMixComponent;
pub use audio_oscillator::{AudioOscillator, AudioOscillatorComponent, OscillatorType};
pub use audio_output::AudioOutputComponent;
pub use avatar_body_yaw::AvatarBodyYawComponent;
pub use avatar_control::AvatarControlComponent;
pub use background::BackgroundComponent;
pub use background_color::BackgroundColorComponent;
pub use bloom::BloomComponent;
pub use blur_pass::BlurPassComponent;
pub use bone_rest_pose::BoneRestPoseComponent;
pub use bounds::BoundsComponent;
pub use camera_2d::Camera2DComponent;
pub use camera_3d::Camera3DComponent;
pub use camera_xr::CameraXRComponent;
pub use clock::ClockComponent;
pub use collision::CollisionComponent;
pub use collision_shape::CollisionShapeComponent;
pub use color::ColorComponent;
pub use component_ref::{
    ComponentRef, QueryRootMode, ScopedQuery, parse_scoped_query, resolve_component_ref,
    resolve_scoped_query,
};
pub use controller_xr::{ControllerHand, ControllerPoseKind, ControllerXRComponent};
pub use data::{DataComponent, DataEntry, DataValue};
pub use directional_light::DirectionalLightComponent;
pub use editor::EditorComponent;
pub use editor::EditorInteractionMode;
pub use editor::TransformGizmoCoordSpace;
pub use emissive::EmissiveComponent;
pub use emissive_pass::EmissivePassComponent;
pub use fit_bounds::{FitBoundsComponent, FitBoundsMode, FitBoundsTarget};
pub use gesture_coord_type::{GestureCoordType, GestureCoordTypeComponent};
pub use gizmo::{
    TransformGizmoAxis, TransformGizmoComponent, TransformGizmoRotateComponent,
    TransformGizmoScaleComponent, TransformGizmoTranslateComponent,
};
pub use gravity::GravityComponent;
pub use grid::GridComponent;
pub use html_element::{ElementType, HtmlElementComponent};
pub use http_client::HttpClientComponent;
pub use http_server::HttpServerComponent;
pub use ik_chain::{IKChainComponent, IKSolver};
pub use input::InputComponent;
pub use input_transform_mode::{ForwardAxis, InputTransformModeComponent, RollAxis};
pub use input_xr::InputXRComponent;
pub use input_xr_gamepad::{
    InputXRGamepadComponent, XrAxisControl, XrButtonControl, XrHandPreference,
};
pub use inspect_layout::InspectLayoutComponent;
pub use keyframe::KeyframeComponent;
pub use kinetic_response::{KineticResponseComponent, KineticResponseMode};
pub use layout::LayoutComponent;
pub use layout_bounds::LayoutBoundsComponent;
pub use light_quantization::LightQuantizationComponent;
pub use mesh::MeshComponent;
pub use mirror::MirrorComponent;
pub(crate) use music_note::NotePitch;
pub use music_note::{MusicNote, MusicNoteComponent};
pub use normal_visualisation::NormalVisualisationComponent;
pub use opacity::OpacityComponent;
pub use option::OptionComponent;
pub use overlay::OverlayComponent;
pub use point_light::PointLightComponent;
pub use pointer::PointerComponent;
pub use pose_capture::*;
pub use raycast::{RayCastComponent, RayCastMode};
pub use raycastable::{PointerEvents, RaycastableComponent};
pub use raycastable_shape::{RaycastableShapeComponent, RaycastableShapeType};
pub use render_graph::RenderGraphComponent;
pub use renderable::RenderableComponent;
pub use renderer_settings::RendererSettingsComponent;
pub use renderer_stats::RendererStatsComponent;
pub use router::RouterComponent;
pub use scrolling::ScrollingComponent;
pub use secondary_motion::{
    SecondaryMotionComponent, SpringBoneComponent, SpringJointComponent,
    export_secondary_motion_sidecar,
};
pub use selectable::SelectableComponent;
pub use selection::{SelectionComponent, SelectionEntry, SelectionMode};
pub use serialize::SerializeComponent;
pub use signal_observer_router::SignalObserverRouterComponent;
pub use signal_route_upward::SignalRouteUpwardComponent;
pub use skinned_mesh::SkinnedMeshComponent;
pub use stencil_clip::StencilClipComponent;
pub use style::{
    AlignItems, BoxSizing, Display, EdgeInsets, FlexDirection, FlexWrap, JustifyContent, Overflow,
    Position, SizeDimension, StyleComponent, StylePatch, TextAlign, WordWrapMode,
};
pub use text::TextComponent;
pub use text_input::{TextInputComponent, TextInputGlyphHitComponent};
pub use text_shadow::TextShadowComponent;
pub use texture::{CatEngineTextureFormat, TextureComponent};
pub use texture_filtering::TextureFilteringComponent;
pub use transform::TransformComponent;
pub use transform_camera_specific::{
    TransformCameraSpecificComponent, TransformCameraSpecificMode,
};
pub use transform_parent::TransformParentComponent;
pub use transform_pipeline::{
    TransformDropComponent, TransformForkTRSComponent, TransformMergeTRSComponent,
    TransformSampleAncestorComponent,
};
pub use transform_pipeline_map::{
    TransformMapRotationComponent, TransformMapScaleComponent, TransformMapTranslationComponent,
};
pub use transform_temporal_filter::{
    QuatExtractYawComponent, QuatTemporalFilterComponent, QuatYawFollowComponent,
    Vector3TemporalFilterComponent,
};
pub use transition::{TransitionComponent, TransitionEasing, TransitionReplacePolicy};
pub use transparent_cutout::TransparentCutoutComponent;
pub use uv::UVComponent;
pub use xr::XrComponent;
pub type XRHandComponent = ControllerXRComponent;

/// For now, our "LightComponent" is a point light.
pub type LightComponent = point_light::PointLightComponent;

/// World-owned record for a component payload plus its topology.
///
/// This is the building block of the component-centric ECS: a single flat store of records
/// in `World`, each record carrying its own parent/children handles.

pub struct ComponentNode {
    pub guid: uuid::Uuid,
    /// Engine-side type identifier from `Component::name()` (e.g. `"transform"`, `"text"`).
    /// Set at construction, never changes.
    pub component_type: String,
    /// User-assigned label for this node (e.g. `name = "catgirl"` in MMS).
    /// Defaults to empty. Used for `#label` query selectors.
    pub name: String,
    /// CSS-style class membership (e.g. `class = "avatar"` in MMS).
    /// Used for `.class` query selectors.
    pub classes: Vec<String>,
    pub component: Box<dyn Component>,
    pub parent: Option<crate::engine::ecs::ComponentId>,
    pub children: Vec<crate::engine::ecs::ComponentId>,
    pub initialized: bool,
}

impl ComponentNode {
    pub fn new(component: Box<dyn Component>) -> Self {
        let component_type = component.name().to_string();
        Self {
            guid: uuid::Uuid::new_v4(),
            component_type,
            name: String::new(),
            classes: Vec::new(),
            component,
            parent: None,
            children: Vec::new(),
            initialized: false,
        }
    }

    /// Create a node with a user-assigned label (`name`).
    /// `component_type` is still derived from `component.name()`.
    pub fn new_named(name: impl Into<String>, component: Box<dyn Component>) -> Self {
        let component_type = component.name().to_string();
        Self {
            guid: uuid::Uuid::new_v4(),
            component_type,
            name: name.into(),
            classes: Vec::new(),
            component,
            parent: None,
            children: Vec::new(),
            initialized: false,
        }
    }

    pub fn new_with_guid_named(
        guid: uuid::Uuid,
        name: impl Into<String>,
        component: Box<dyn Component>,
    ) -> Self {
        let component_type = component.name().to_string();
        Self {
            guid,
            component_type,
            name: name.into(),
            classes: Vec::new(),
            component,
            parent: None,
            children: Vec::new(),
            initialized: false,
        }
    }
}

/// Component interface.
/// `init` runs when the component is registered
pub trait Component: std::any::Any {
    fn as_any(&self) -> &dyn std::any::Any;
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;

    /// Short debug/type name for this component kind (e.g. "transform", "camera").
    fn name(&self) -> &'static str;

    fn set_id(&mut self, _component: crate::engine::ecs::ComponentId) {}

    /// Called when component is added to the World
    fn init(
        &mut self,
        _emit: &mut dyn crate::engine::ecs::SignalEmitter,
        _component: crate::engine::ecs::ComponentId,
    ) {
    }

    /// Called when component is removed from the World.
    fn cleanup(
        &mut self,
        _emit: &mut dyn crate::engine::ecs::SignalEmitter,
        _component: crate::engine::ecs::ComponentId,
    ) {
    }

    /// Encode component data to a HashMap for serialization.
    ///
    /// Components should serialize their data fields (not runtime handles).
    fn encode(&self) -> std::collections::HashMap<String, serde_json::Value> {
        std::collections::HashMap::new()
    }

    /// Decode component data from a HashMap after deserialization.
    ///
    /// Components should restore their data fields from the map.
    fn decode(
        &mut self,
        _data: &std::collections::HashMap<String, serde_json::Value>,
    ) -> Result<(), String> {
        Ok(())
    }

    /// Encode this component as an MMS Component Expression AST node.
    ///
    /// The returned `ComponentExpression` should round-trip through the
    /// MMS pipeline: `unparse → parse → eval_ce → spawn_tree` reconstructs
    /// an equivalent component. Default impl emits a bare CE with no
    /// constructors/body, using `name()` (snake_case) as the type — this
    /// works for "tag" components with no state but most overrides will
    /// want to emit proper builder calls for their fields.
    fn to_mms_ast(
        &self,
        _world: &crate::engine::ecs::World,
    ) -> crate::scripting::ast::ComponentExpression {
        crate::scripting::ast::ComponentExpression {
            component_type: crate::scripting::ast::Ident(self.name().to_string()),
            constructors: Vec::new(),
            body: crate::scripting::ast::BlockStatement {
                statements: Vec::new(),
            },
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers for component `to_mms_ast` implementations.
// Imported by each component file: `use super::ce_helpers::*;` (or fully qualified).
// ---------------------------------------------------------------------------

pub mod ce_helpers {
    use crate::scripting::ast::{
        BlockStatement, ComponentExpression, ConstructorCall, Expression, Ident, UnaryOpKind,
    };

    /// Empty CE: `Name {}` (no constructors, empty body).
    pub fn ce(type_name: &str) -> ComponentExpression {
        ComponentExpression {
            component_type: Ident(type_name.to_string()),
            constructors: Vec::new(),
            body: BlockStatement {
                statements: Vec::new(),
            },
        }
    }

    /// CE with a single primary constructor: `Name.method(args)`.
    pub fn ce_call(type_name: &str, method: &str, args: Vec<Expression>) -> ComponentExpression {
        ComponentExpression {
            component_type: Ident(type_name.to_string()),
            constructors: vec![ConstructorCall {
                method: Ident(method.to_string()),
                args,
            }],
            body: BlockStatement {
                statements: Vec::new(),
            },
        }
    }

    pub trait CeBuilder {
        fn with_call(self, method: &str, args: Vec<Expression>) -> Self;
    }

    impl CeBuilder for ComponentExpression {
        fn with_call(mut self, method: &str, args: Vec<Expression>) -> Self {
            self.constructors.push(ConstructorCall {
                method: Ident(method.to_string()),
                args,
            });
            self
        }
    }

    pub fn num(n: f64) -> Expression {
        if n < 0.0 {
            Expression::UnaryOp {
                op: UnaryOpKind::Neg,
                operand: Box::new(Expression::Number(-n)),
            }
        } else {
            Expression::Number(n)
        }
    }

    pub fn nums<I: IntoIterator<Item = f64>>(values: I) -> Vec<Expression> {
        values.into_iter().map(num).collect()
    }

    pub fn s(text: &str) -> Expression {
        Expression::String(text.to_string())
    }

    pub fn b(value: bool) -> Expression {
        Expression::Bool(value)
    }

    pub fn ident(name: &str) -> Expression {
        Expression::Identifier(Ident(name.to_string()))
    }

    pub fn array(items: Vec<Expression>) -> Expression {
        Expression::Array(items)
    }

    pub fn ls<I: IntoIterator<Item = S>, S: AsRef<str>>(values: I) -> Expression {
        Expression::Array(values.into_iter().map(|v| s(v.as_ref())).collect())
    }
}