1use serde::{Deserialize, Serialize};
35use std::collections::HashMap;
36use std::str::FromStr;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40#[serde(untagged)]
41pub enum TokenValue {
42 Single {
44 value: String,
45 },
46 Adaptive {
48 light: String,
49 dark: String,
50 },
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct YggdrasilTokens {
56 pub color: HashMap<String, TokenValue>,
57 pub font: HashMap<String, TokenValue>,
58 pub spacing: HashMap<String, TokenValue>,
59 pub radius: HashMap<String, TokenValue>,
60 pub shadow: HashMap<String, TokenValue>,
61 pub border: HashMap<String, TokenValue>,
62 pub anim: HashMap<String, TokenValue>,
63 pub bifrost: HashMap<String, TokenValue>,
64 pub gungnir: HashMap<String, TokenValue>,
65 pub mjolnir: HashMap<String, TokenValue>,
66 pub accessibility: HashMap<String, TokenValue>,
67}
68
69impl YggdrasilTokens {
70 pub fn new() -> Self {
71 Self {
72 color: HashMap::new(),
73 font: HashMap::new(),
74 spacing: HashMap::new(),
75 radius: HashMap::new(),
76 shadow: HashMap::new(),
77 border: HashMap::new(),
78 anim: HashMap::new(),
79 bifrost: HashMap::new(),
80 gungnir: HashMap::new(),
81 mjolnir: HashMap::new(),
82 accessibility: HashMap::new(),
83 }
84 }
85
86 pub fn get_color(&self, key: &str, is_dark: bool) -> Option<String> {
88 self.color.get(key).and_then(|token| {
89 match token {
90 TokenValue::Single { value } => Some(value.clone()),
91 TokenValue::Adaptive { light, dark } => {
92 if is_dark { Some(dark.clone()) } else { Some(light.clone()) }
93 }
94 }
95 })
96 }
97
98 pub fn get<T: FromStr>(&self, category: &str, key: &str, is_dark: bool) -> Option<T> {
100 let map = match category {
101 "color" => &self.color,
102 "font" => &self.font,
103 "spacing" => &self.spacing,
104 "radius" => &self.radius,
105 "shadow" => &self.shadow,
106 "border" => &self.border,
107 "anim" => &self.anim,
108 "bifrost" => &self.bifrost,
109 "gungnir" => &self.gungnir,
110 "mjolnir" => &self.mjolnir,
111 "accessibility" => &self.accessibility,
112 _ => return None,
113 };
114
115 map.get(key).and_then(|token| {
116 match token {
117 TokenValue::Single { value } => value.parse().ok(),
118 TokenValue::Adaptive { light, dark } => {
119 let value = if is_dark { dark } else { light };
120 value.parse().ok()
121 }
122 }
123 })
124 }
125}
126
127pub trait View: Sized + Send {
128 type Body: View;
131
132 fn body(self) -> Self::Body;
133
134 fn render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}
137
138 fn layout(&self) -> Option<&dyn layout::LayoutView> {
140 None
141 }
142
143 fn modifier<M: ViewModifier>(self, m: M) -> ModifiedView<Self, M> {
145 ModifiedView::new(self, m)
146 }
147
148 fn bifrost(self, blur: f32, saturation: f32, opacity: f32) -> ModifiedView<Self, BifrostModifier> {
150 self.modifier(BifrostModifier { blur, saturation, opacity })
151 }
152
153 fn gungnir(self, color: impl Into<String>, radius: f32, intensity: f32) -> ModifiedView<Self, GungnirModifier> {
155 self.modifier(GungnirModifier { color: color.into(), radius, intensity })
156 }
157
158 fn mjolnir_slice(self, angle: f32, offset: f32) -> ModifiedView<Self, MjolnirSliceModifier> {
160 self.modifier(MjolnirSliceModifier { angle, offset })
161 }
162
163 fn mjolnir_shatter(self, pieces: u32, force: f32) -> ModifiedView<Self, MjolnirShatterModifier> {
165 self.modifier(MjolnirShatterModifier { pieces, force })
166 }
167
168 fn bifrost_bridge(self, id: impl Into<String>) -> ModifiedView<Self, BifrostBridgeModifier> {
170 self.modifier(BifrostBridgeModifier { id: id.into() })
171 }
172
173 fn background(self, color: [f32; 4]) -> ModifiedView<Self, BackgroundModifier> {
175 self.modifier(BackgroundModifier { color })
176 }
177
178 fn padding(self, amount: f32) -> ModifiedView<Self, PaddingModifier> {
180 self.modifier(PaddingModifier { amount })
181 }
182
183 fn opacity(self, opacity: f32) -> ModifiedView<Self, OpacityModifier> {
185 self.modifier(OpacityModifier { opacity: opacity.clamp(0.0, 1.0) })
186 }
187
188 fn foreground_color(self, color: [f32; 4]) -> ModifiedView<Self, ForegroundColorModifier> {
190 self.modifier(ForegroundColorModifier { color })
191 }
192
193 fn frame(self, width: Option<f32>, height: Option<f32>) -> ModifiedView<Self, FrameModifier> {
195 self.modifier(FrameModifier { width, height })
196 }
197
198 fn clip_to_bounds(self) -> ModifiedView<Self, ClipModifier> {
200 self.modifier(ClipModifier)
201 }
202
203 fn border(self, color: [f32; 4], width: f32) -> ModifiedView<Self, BorderModifier> {
205 self.modifier(BorderModifier { color, width })
206 }
207
208 fn on_appear<F: Fn() + Send + Sync + 'static>(self, action: F) -> ModifiedView<Self, LifecycleModifier> {
210 self.modifier(LifecycleModifier {
211 on_appear: Some(Arc::new(action)),
212 on_disappear: None,
213 })
214 }
215
216 fn on_disappear<F: Fn() + Send + Sync + 'static>(self, action: F) -> ModifiedView<Self, LifecycleModifier> {
218 self.modifier(LifecycleModifier {
219 on_appear: None,
220 on_disappear: Some(Arc::new(action)),
221 })
222 }
223
224 fn erase(self) -> AnyView where Self: 'static {
226 AnyView::new(self)
227 }
228}
229
230pub trait ErasedView: Send {
232 fn render_erased(&self, renderer: &mut dyn Renderer, rect: Rect);
233 fn name(&self) -> &'static str;
234}
235
236impl<V: View + 'static> ErasedView for V {
237 fn render_erased(&self, renderer: &mut dyn Renderer, rect: Rect) {
238 self.render(renderer, rect);
239 }
240
241 fn name(&self) -> &'static str {
242 std::any::type_name::<V>()
243 }
244}
245
246pub struct AnyView {
248 inner: Box<dyn ErasedView>,
249}
250
251impl AnyView {
252 pub fn new<V: View + 'static>(view: V) -> Self {
253 Self { inner: Box::new(view) }
254 }
255}
256
257impl View for AnyView {
258 type Body = Never;
259 fn body(self) -> Self::Body { unreachable!() }
260
261 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
262 renderer.push_vnode(rect, self.inner.name());
263 self.inner.render_erased(renderer, rect);
264 renderer.pop_vnode();
265 }
266}
267
268#[derive(Debug, Clone, PartialEq)]
272pub struct BifrostBridgeModifier {
273 pub id: String,
274}
275
276impl ViewModifier for BifrostBridgeModifier {
277 fn modify<V: View>(self, content: V) -> impl View {
278 ModifiedView::new(content, self)
279 }
280
281 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
282 renderer.register_shared_element(&self.id, rect);
284 }
285}
286
287#[derive(Debug, Clone, Copy, PartialEq)]
290pub struct MjolnirSliceModifier {
291 pub angle: f32,
292 pub offset: f32,
293}
294
295impl ViewModifier for MjolnirSliceModifier {
296 fn modify<V: View>(self, content: V) -> impl View {
297 ModifiedView::new(content, self)
298 }
299
300 fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
301 renderer.push_mjolnir_slice(self.angle, self.offset);
302 }
303
304 fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
305 renderer.pop_mjolnir_slice();
306 }
307}
308
309#[derive(Debug, Clone, Copy, PartialEq)]
312pub struct MjolnirShatterModifier {
313 pub pieces: u32,
314 pub force: f32,
315}
316
317impl ViewModifier for MjolnirShatterModifier {
318 fn modify<V: View>(self, content: V) -> impl View {
319 ModifiedView::new(content, self)
320 }
321
322 fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
323 let pieces = self.pieces.max(1);
325 for i in 0..pieces {
326 let progress = i as f32 / pieces as f32;
327 let next_progress = (i + 1) as f32 / pieces as f32;
328
329 let angle_start = progress * 360.0;
330 let angle_end = next_progress * 360.0;
331
332 renderer.push_mjolnir_slice(angle_start, 0.0);
334 renderer.push_mjolnir_slice(angle_end + 180.0, 0.0);
335
336 let mid_angle = (angle_start + angle_end) / 2.0;
338 let rad = mid_angle.to_radians();
339 let dx = rad.cos() * self.force;
340 let dy = rad.sin() * self.force;
341
342 let shard_rect = Rect {
343 x: rect.x + dx,
344 y: rect.y + dy,
345 ..rect
346 };
347
348 view.render(renderer, shard_rect);
349
350 renderer.pop_mjolnir_slice();
351 renderer.pop_mjolnir_slice();
352 }
353 }
354}
355
356#[derive(Debug, Clone, Copy, PartialEq)]
359pub struct BifrostModifier {
360 pub blur: f32,
361 pub saturation: f32,
362 pub opacity: f32,
363}
364
365impl ViewModifier for BifrostModifier {
366 fn modify<V: View>(self, content: V) -> impl View {
367 ModifiedView::new(content, self)
368 }
369
370 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
371 renderer.bifrost(rect, self.blur, self.saturation, self.opacity);
372 }
373}
374
375#[derive(Debug, Clone, Copy, PartialEq)]
377pub struct BackgroundModifier {
378 pub color: [f32; 4],
379}
380
381impl ViewModifier for BackgroundModifier {
382 fn modify<V: View>(self, content: V) -> impl View {
383 ModifiedView::new(content, self)
384 }
385
386 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
387 renderer.fill_rect(rect, self.color);
388 }
389}
390
391#[derive(Debug, Clone, Copy, PartialEq)]
393pub struct PaddingModifier {
394 pub amount: f32,
395}
396
397impl ViewModifier for PaddingModifier {
398 fn modify<V: View>(self, content: V) -> impl View {
399 ModifiedView::new(content, self)
400 }
401
402 fn transform_rect(&self, rect: Rect) -> Rect {
403 Rect {
404 x: rect.x + self.amount,
405 y: rect.y + self.amount,
406 width: (rect.width - 2.0 * self.amount).max(0.0),
407 height: (rect.height - 2.0 * self.amount).max(0.0),
408 }
409 }
410}
411
412#[derive(Debug, Clone, PartialEq)]
415pub struct GungnirModifier {
416 pub color: String,
417 pub radius: f32,
418 pub intensity: f32,
419}
420
421impl ViewModifier for GungnirModifier {
422 fn modify<V: View>(self, content: V) -> impl View {
423 ModifiedView::new(content, self)
424 }
425
426 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
427 renderer.stroke_rect(rect, [0.0, 1.0, 1.0, self.intensity], self.radius / 10.0);
429 }
430}
431
432#[derive(Debug, Clone, Copy, PartialEq)]
434pub struct GungnirPulseModifier {
435 pub color: [f32; 4],
436 pub radius: f32,
437 pub speed: f32,
438}
439
440impl ViewModifier for GungnirPulseModifier {
441 fn modify<V: View>(self, content: V) -> impl View {
442 ModifiedView::new(content, self)
443 }
444
445 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
446 let time = std::time::SystemTime::now()
447 .duration_since(std::time::UNIX_EPOCH)
448 .unwrap_or_default()
449 .as_secs_f32();
450
451 let intensity = (time * self.speed).sin() * 0.5 + 0.5;
454 let mut color = self.color;
455 color[3] *= intensity;
456
457 renderer.stroke_rect(rect, color, self.radius);
459 }
460}
461
462#[derive(Debug, Clone, PartialEq)]
464pub struct SleipnirModifier<T> {
465 pub target: T,
466 pub stiffness: f32,
467 pub damping: f32,
468}
469
470impl<T: Send + Sync + 'static + Clone> ViewModifier for SleipnirModifier<T> {
471 fn modify<V: View>(self, content: V) -> impl View {
472 ModifiedView::new(content, self)
473 }
474}
475
476#[derive(Clone)]
478pub struct LifecycleModifier {
479 pub on_appear: Option<Arc<dyn Fn() + Send + Sync>>,
480 pub on_disappear: Option<Arc<dyn Fn() + Send + Sync>>,
481}
482
483impl ViewModifier for LifecycleModifier {
484 fn modify<V: View>(self, content: V) -> impl View {
485 ModifiedView::new(content, self)
486 }
487}
488
489#[derive(Debug, Clone, Copy, PartialEq)]
492pub struct OpacityModifier {
493 pub opacity: f32,
494}
495
496impl ViewModifier for OpacityModifier {
497 fn modify<V: View>(self, content: V) -> impl View {
498 ModifiedView::new(content, self)
499 }
500
501 fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
502 renderer.push_opacity(self.opacity);
503 }
504
505 fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
506 renderer.pop_opacity();
507 }
508}
509
510#[derive(Debug, Clone, Copy, PartialEq)]
513pub struct ForegroundColorModifier {
514 pub color: [f32; 4],
515}
516
517impl ViewModifier for ForegroundColorModifier {
518 fn modify<V: View>(self, content: V) -> impl View {
519 ModifiedView::new(content, self)
520 }
521}
522
523#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub struct ClipModifier;
527
528impl ViewModifier for ClipModifier {
529 fn modify<V: View>(self, content: V) -> impl View {
530 ModifiedView::new(content, self)
531 }
532
533 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
534 renderer.push_clip_rect(rect);
535 }
536
537 fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
538 renderer.pop_clip_rect();
539 }
540}
541
542#[derive(Debug, Clone, Copy, PartialEq)]
544pub struct BorderModifier {
545 pub color: [f32; 4],
546 pub width: f32,
547}
548
549impl ViewModifier for BorderModifier {
550 fn modify<V: View>(self, content: V) -> impl View {
551 ModifiedView::new(content, self)
552 }
553
554 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
555 renderer.stroke_rect(rect, self.color, self.width);
556 }
557}
558
559#[doc(hidden)]
561pub enum Never {}
562
563impl View for Never {
564 type Body = Never;
565 fn body(self) -> Never {
566 unreachable!()
567 }
568}
569
570pub struct ModifiedView<V, M> {
574 view: V,
575 modifier: M,
576}
577
578 impl<V: View, M: ViewModifier> ModifiedView<V, M> {
579 #[doc(hidden)]
580 pub fn new(view: V, modifier: M) -> Self {
581 Self { view, modifier }
582 }
583 }
584
585 impl<V: View, M: ViewModifier> View for ModifiedView<V, M> {
586 type Body = ModifiedView<V::Body, M>;
587
588 fn body(self) -> Self::Body {
589 ModifiedView {
590 view: self.view.body(),
591 modifier: self.modifier.clone(),
592 }
593 }
594
595 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
596 self.modifier.render_view(&self.view, renderer, rect);
597 }
598 }
599
600
601 pub trait ViewModifier: Send + Clone {
602 fn modify<V: View>(self, content: V) -> impl View;
603
604 fn render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}
606
607 fn post_render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}
609
610 fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
613 self.render(renderer, rect);
614 let child_rect = self.transform_rect(rect);
615 view.render(renderer, child_rect);
616 self.post_render(renderer, rect);
617 }
618
619 fn transform_rect(&self, rect: Rect) -> Rect { rect }
620 }
621
622 pub trait Renderer: Send {
630 fn fill_rect(&mut self, rect: Rect, color: [f32; 4]);
632 fn fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: [f32; 4]);
633 fn fill_ellipse(&mut self, rect: Rect, color: [f32; 4]);
635
636 fn stroke_rect(&mut self, rect: Rect, color: [f32; 4], stroke_width: f32);
638 fn stroke_rounded_rect(&mut self, rect: Rect, radius: f32, color: [f32; 4], stroke_width: f32);
639 fn stroke_ellipse(&mut self, rect: Rect, color: [f32; 4], stroke_width: f32);
641 fn draw_line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, color: [f32; 4], stroke_width: f32);
643
644 fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: [f32; 4]);
646 fn measure_text(&mut self, text: &str, size: f32) -> (f32, f32);
648
649 fn draw_texture(&mut self, texture_id: u32, rect: Rect);
652 fn draw_image(&mut self, image_name: &str, rect: Rect);
654 fn load_image(&mut self, name: &str, data: &[u8]);
656
657 fn upload_data_texture(&mut self, _id: &str, _data: &[f32], _width: u32, _height: u32) {}
660 fn draw_heatmap(&mut self, _texture_id: &str, _rect: Rect, _palette: &str) {}
662
663 fn draw_mesh(&mut self, _mesh: &Mesh, _color: [f32; 4], _transform: glam::Mat4) {}
666
667 fn draw_linear_gradient(&mut self, _rect: Rect, _start_color: [f32; 4], _end_color: [f32; 4], _angle: f32) {}
670 fn draw_radial_gradient(&mut self, _rect: Rect, _inner_color: [f32; 4], _outer_color: [f32; 4]) {}
672 fn draw_drop_shadow(&mut self, _rect: Rect, _radius: f32, _color: [f32; 4], _blur: f32, _spread: f32) {}
674 fn stroke_dashed_rounded_rect(&mut self, _rect: Rect, _radius: f32, _color: [f32; 4], _width: f32, _dash: f32, _gap: f32) {}
676 fn draw_9slice(&mut self, _image_name: &str, _rect: Rect, _left: f32, _top: f32, _right: f32, _bottom: f32) {}
678
679 fn push_clip_rect(&mut self, rect: Rect);
683 fn pop_clip_rect(&mut self);
685
686 fn push_opacity(&mut self, opacity: f32);
690 fn pop_opacity(&mut self);
692
693 fn set_theme(&mut self, _theme: ColorTheme) {}
695 fn set_rage(&mut self, _rage: f32) {}
696 fn trigger_shatter_event(&mut self, _origin: [f32; 2], _force: f32) {}
697
698 fn bifrost(&mut self, rect: Rect, blur: f32, saturation: f32, opacity: f32);
701 fn push_mjolnir_slice(&mut self, angle: f32, offset: f32);
703 fn pop_mjolnir_slice(&mut self);
705 fn mjolnir_shatter(&mut self, _rect: Rect, _pieces: u32, _force: f32, _color: [f32; 4]) {}
707 fn mjolnir_fluid_shatter(&mut self, _rect: Rect, _pieces: u32, _force: f32, _color: [f32; 4]) {}
708 fn draw_mjolnir_bolt(&mut self, _from: [f32; 2], _to: [f32; 2], _color: [f32; 4]) {}
710
711 fn set_aria_role(&mut self, _role: &str) {}
713 fn set_aria_label(&mut self, _label: &str) {}
714
715 fn register_shared_element(&mut self, _id: &str, _rect: Rect) {}
717
718 fn push_vnode(&mut self, _rect: Rect, _name: &'static str) {}
721 fn pop_vnode(&mut self) {}
723 fn register_handler(&mut self, _event_type: &str, _handler: std::sync::Arc<dyn Fn(Event) + Send + Sync>) {}
725 }
726
727 use bytemuck::{Pod, Zeroable};
732
733 #[repr(C)]
735 #[derive(Copy, Clone, Debug, Pod, Zeroable, serde::Serialize, serde::Deserialize)]
736 pub struct ColorTheme {
737 pub primary_neon: [f32; 4], pub shatter_neon: [f32; 4],
739 pub glass_base: [f32; 4],
740 pub glass_edge: [f32; 4],
741 pub rune_glow: [f32; 4],
742 pub ember_core: [f32; 4],
743 pub background_deep: [f32; 4],
744 pub glass_blur_strength: f32,
745 pub shatter_edge_width: f32,
746 pub neon_bloom_radius: f32,
747 pub rune_opacity: f32, pub _pad: [f32; 3], pub _pad2: f32,
751 }
752
753 impl ColorTheme {
754 pub fn cyberpunk_viking() -> Self {
755 Self {
756 primary_neon: [0.0, 1.0, 0.95, 1.2],
757 shatter_neon: [1.0, 0.0, 0.75, 1.5],
758 glass_base: [0.04, 0.04, 0.06, 0.82],
759 glass_edge: [0.0, 0.45, 0.55, 0.6],
760 rune_glow: [0.75, 0.98, 1.0, 0.9],
761 ember_core: [0.95, 0.12, 0.12, 1.0],
762 background_deep: [0.01, 0.01, 0.03, 1.0],
763 glass_blur_strength: 0.6,
764 shatter_edge_width: 1.8,
765 neon_bloom_radius: 0.022,
766 rune_opacity: 0.55,
767 _pad: [0.0; 3],
768 _pad2: 0.0,
769 }
770 }
771 }
772
773 impl Default for ColorTheme {
774 fn default() -> Self {
775 Self::cyberpunk_viking()
776 }
777 }
778
779 #[repr(C)]
781 #[derive(Copy, Clone, Debug, Pod, Zeroable, serde::Serialize, serde::Deserialize)]
782 pub struct SceneUniforms {
783 pub view: glam::Mat4,
784 pub proj: glam::Mat4,
785 pub time: f32,
786 pub delta_time: f32,
787 pub resolution: [f32; 2],
788 pub mouse: [f32; 2],
789 pub mouse_velocity: [f32; 2],
790 pub shatter_origin: [f32; 2],
791 pub shatter_time: f32,
792 pub shatter_force: f32,
793 pub berzerker_rage: f32,
794 pub scroll_offset: f32,
795 pub _pad: [f32; 2],
797 }
798
799 impl SceneUniforms {
800 pub fn new(width: f32, height: f32) -> Self {
801 Self {
802 view: glam::Mat4::IDENTITY,
803 proj: glam::Mat4::orthographic_lh(0.0, width, height, 0.0, -100.0, 100.0),
804 time: 0.0,
805 delta_time: 0.016,
806 resolution: [width, height],
807 mouse: [0.5, 0.5],
808 mouse_velocity: [0.0, 0.0],
809 shatter_origin: [0.5, 0.5],
810 shatter_time: -100.0,
811 shatter_force: 0.0,
812 berzerker_rage: 0.0,
813 scroll_offset: 0.0,
814 _pad: [0.0; 2],
815 }
816 }
817 }
818
819 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
821 pub struct Mesh {
822 pub vertices: Vec<[f32; 3]>,
823 pub normals: Vec<[f32; 3]>,
824 pub indices: Vec<u32>,
825 }
826
827 impl Mesh {
828 pub fn from_obj(data: &[u8]) -> anyhow::Result<Vec<Self>> {
829 let mut cursor = std::io::Cursor::new(data);
830 let (models, _) = tobj::load_obj_buf(&mut cursor, &tobj::LoadOptions::default(), |_| {
831 Ok((Vec::new(), Default::default()))
832 })?;
833
834 let mut meshes = Vec::new();
835 for m in models {
836 let mesh = m.mesh;
837 let vertices: Vec<[f32; 3]> = mesh.positions.chunks(3).map(|c| [c[0], c[1], c[2]]).collect();
838 let normals = if mesh.normals.is_empty() {
839 vec![[0.0, 0.0, 1.0]; vertices.len()]
840 } else {
841 mesh.normals.chunks(3).map(|c| [c[0], c[1], c[2]]).collect()
842 };
843 meshes.push(Mesh { vertices, normals, indices: mesh.indices });
844 }
845 Ok(meshes)
846 }
847
848 pub fn from_stl(data: &[u8]) -> anyhow::Result<Self> {
849 let mut cursor = std::io::Cursor::new(data);
850 let stl = stl_io::read_stl(&mut cursor)?;
851
852 let vertices: Vec<[f32; 3]> = stl.vertices.iter().map(|v| [v[0], v[1], v[2]]).collect();
853 let mut indices = Vec::new();
854 for face in stl.faces {
855 indices.push(face.vertices[0] as u32);
856 indices.push(face.vertices[1] as u32);
857 indices.push(face.vertices[2] as u32);
858 }
859
860 let normals = vec![[0.0, 0.0, 1.0]; vertices.len()];
861
862 Ok(Mesh { vertices, normals, indices })
863 }
864 }
865
866 pub trait FrameRenderer<E = ()>: Renderer {
869 fn begin_frame(&mut self) -> E;
870 fn end_frame(&mut self, encoder: E);
871 }
872
873
874
875use std::sync::Arc;
876
877#[derive(Clone)]
879pub struct State<T: Clone + Send + Sync + 'static> {
880 value: Arc<std::sync::RwLock<T>>,
881 subscribers: Arc<std::sync::RwLock<Vec<Box<dyn FnMut(&T) + Send + Sync>>>>,
882}
883
884impl<T: Clone + Send + Sync + 'static> State<T> {
885 pub fn new(value: T) -> Self {
887 Self {
888 value: Arc::new(std::sync::RwLock::new(value)),
889 subscribers: Arc::new(std::sync::RwLock::new(Vec::new())),
890 }
891 }
892
893 pub fn get(&self) -> T {
895 self.value.read().unwrap().clone()
896 }
897
898 pub fn set(&self, value: T) {
900 *self.value.write().unwrap() = value;
901 let mut subscribers = self.subscribers.write().unwrap();
903 for subscriber in subscribers.iter_mut() {
904 subscriber(&self.get());
905 }
906 }
907
908 pub fn subscribe<F: FnMut(&T) + Send + Sync + 'static>(&self, callback: F) {
910 self.subscribers.write().unwrap().push(Box::new(callback));
911 }
912}
913
914#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
918pub struct ComponentErrorState {
919 pub has_error: bool,
920 pub error_message: Option<String>,
921 pub error_location: Option<String>,
922}
923
924impl ComponentErrorState {
925 pub fn clear() -> Self {
927 Self::default()
928 }
929
930 pub fn error(message: impl Into<String>, location: impl Into<String>) -> Self {
932 Self {
933 has_error: true,
934 error_message: Some(message.into()),
935 error_location: Some(location.into()),
936 }
937 }
938}
939
940#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
942pub struct KnowledgeFragment {
943 pub id: String,
945 pub summary: String,
947 pub source: String,
949 pub created_at: u64,
951 pub accessed_count: u32,
953 pub content: Option<String>,
955}
956
957#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
960pub struct KnowledgeState {
961 #[serde(skip)]
963 pub component_states: std::collections::HashMap<u64, Arc<dyn std::any::Any + Send + Sync>>,
964
965 pub fragments: HashMap<String, KnowledgeFragment>,
967
968 pub last_query_results: Vec<String>,
970}
971
972use std::sync::OnceLock;
973use crate::runtime::NodeStateSnapshot;
974
975pub static SYSTEM_STATE: OnceLock<Arc<std::sync::RwLock<KnowledgeState>>> = OnceLock::new();
977
978pub fn get_system_state() -> Arc<std::sync::RwLock<KnowledgeState>> {
980 SYSTEM_STATE.get_or_init(|| Arc::new(std::sync::RwLock::new(KnowledgeState::default()))).clone()
981}
982
983impl KnowledgeState {
984 pub fn new() -> Self {
986 Self::default()
987 }
988
989 pub fn set_component_state<T: 'static + Send + Sync>(&mut self, id: u64, state: T) {
991 self.component_states.insert(id, Arc::new(std::sync::RwLock::new(state)));
992 }
993
994 pub fn get_component_state<T: 'static + Send + Sync>(&self, id: u64) -> Option<Arc<std::sync::RwLock<T>>> {
996 let lock = self.component_states.get(&id)?;
997 lock.clone().downcast::<std::sync::RwLock<T>>().ok()
998 }
999
1000 pub fn remember(&mut self, fragment: KnowledgeFragment) {
1002 self.fragments.insert(fragment.id.clone(), fragment);
1003 }
1004
1005 pub fn process_query(&mut self, query: &str) {
1007 let query_lower = query.to_lowercase();
1008 let mut results: Vec<(f32, String)> = self.fragments
1009 .iter()
1010 .map(|(id, frag)| {
1011 let mut score = 0.0;
1012 if frag.summary.to_lowercase().contains(&query_lower) { score += 1.0; }
1013 if frag.source.to_lowercase().contains(&query_lower) { score += 0.5; }
1014 (score, id.clone())
1015 })
1016 .filter(|(score, _)| *score > 0.0)
1017 .collect();
1018
1019 results.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
1021
1022 self.last_query_results = results.into_iter()
1023 .map(|(_, id)| id)
1024 .take(5)
1025 .collect();
1026 }
1027
1028 pub fn snapshot(&self) -> Vec<NodeStateSnapshot> {
1030 let mut snapshots = Vec::new();
1031
1032 for (_id, frag) in &self.fragments {
1034 if let Ok(val) = serde_json::to_value(frag) {
1035 snapshots.push(NodeStateSnapshot {
1036 id: 0,
1037 state: val,
1038 });
1039 }
1040 }
1041
1042 snapshots
1043 }
1044}
1045
1046#[derive(Clone)]
1048pub struct Binding<T: Clone + Send + Sync + 'static> {
1049 state: Arc<std::sync::RwLock<T>>,
1050}
1051
1052impl<T: Clone + Send + Sync + 'static> Binding<T> {
1053 pub fn from_state(state: &State<T>) -> Self {
1055 Self {
1056 state: state.value.clone(),
1057 }
1058 }
1059
1060 pub fn get(&self) -> T {
1062 self.state.read().unwrap().clone()
1063 }
1064
1065 pub fn set(&self, value: T) {
1067 *self.state.write().unwrap() = value;
1068 }
1069}
1070
1071use std::any::TypeId;
1072use std::sync::Mutex;
1073
1074pub(crate) static ENVIRONMENT: OnceLock<Mutex<HashMap<TypeId, Box<dyn std::any::Any + Send + Sync>>>> = OnceLock::new();
1076
1077pub trait EnvKey: 'static + Send + Sync {
1081 type Value: Clone + Send + Sync + 'static;
1083
1084 fn default_value() -> Self::Value;
1086}
1087
1088pub struct YggdrasilKey;
1090
1091impl EnvKey for YggdrasilKey {
1092 type Value = YggdrasilTokens;
1093 fn default_value() -> Self::Value {
1094 default_tokens()
1095 }
1096}
1097
1098pub struct AssetKey;
1100
1101impl EnvKey for AssetKey {
1102 type Value = Arc<dyn AssetManager>;
1103 fn default_value() -> Self::Value {
1104 Arc::new(DefaultAssetManager::new())
1105 }
1106}
1107
1108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1110pub enum Appearance {
1111 Light,
1112 Dark,
1113}
1114
1115#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1117pub enum Orientation {
1118 Horizontal,
1119 Vertical,
1120}
1121
1122#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1124pub struct Color {
1125 pub r: f32,
1126 pub g: f32,
1127 pub b: f32,
1128 pub a: f32,
1129}
1130
1131impl Color {
1132 pub const BLACK: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
1133 pub const WHITE: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
1134 pub const TRANSPARENT: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
1135 pub const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
1136 pub const GREEN: Color = Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 };
1137 pub const BLUE: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
1138 pub const CYAN: Color = Color { r: 0.0, g: 1.0, b: 1.0, a: 1.0 };
1139 pub const YELLOW: Color = Color { r: 1.0, g: 1.0, b: 0.0, a: 1.0 };
1140 pub const MAGENTA: Color = Color { r: 1.0, g: 0.0, b: 1.0, a: 1.0 };
1141 pub const GRAY: Color = Color { r: 0.5, g: 0.5, b: 0.5, a: 1.0 };
1142
1143 pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
1145 Self { r, g, b, a }
1146 }
1147
1148 pub fn as_array(&self) -> [f32; 4] {
1150 [self.r, self.g, self.b, self.a]
1151 }
1152}
1153
1154impl View for Color {
1155 type Body = Never;
1156 fn body(self) -> Self::Body { unreachable!() }
1157
1158 fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
1159 renderer.fill_rect(rect, self.as_array());
1160 }
1161}
1162
1163pub struct AppearanceKey;
1165
1166impl EnvKey for AppearanceKey {
1167 type Value = Appearance;
1168 fn default_value() -> Self::Value {
1169 Appearance::Dark }
1171}
1172
1173pub struct StyleResolver;
1175
1176impl StyleResolver {
1177 pub fn color(key: &str) -> String {
1179 let tokens = Environment::<YggdrasilKey>::new().get();
1180 let appearance = Environment::<AppearanceKey>::new().get();
1181 let is_dark = appearance == Appearance::Dark;
1182
1183 tokens.get_color(key, is_dark).unwrap_or_else(|| "#FF00FF".to_string()) }
1185
1186 pub fn get<T: FromStr>(category: &str, key: &str) -> Option<T> {
1188 let tokens = Environment::<YggdrasilKey>::new().get();
1189 let appearance = Environment::<AppearanceKey>::new().get();
1190 let is_dark = appearance == Appearance::Dark;
1191
1192 tokens.get(category, key, is_dark)
1193 }
1194}
1195
1196pub fn default_tokens() -> YggdrasilTokens {
1198 let mut tokens = YggdrasilTokens::new();
1199
1200 tokens.color.insert("background".to_string(), TokenValue::Single {
1202 value: "#000000".to_string(), });
1204
1205 tokens.color.insert("primary".to_string(), TokenValue::Single {
1206 value: "#00FFFF".to_string(), });
1208
1209 tokens.color.insert("secondary".to_string(), TokenValue::Single {
1210 value: "#FF00FF".to_string(), });
1212
1213 tokens.color.insert("surface".to_string(), TokenValue::Adaptive {
1214 light: "#FFFFFF".to_string(),
1215 dark: "#121212".to_string(),
1216 });
1217
1218 tokens.color.insert("text".to_string(), TokenValue::Adaptive {
1219 light: "#000000".to_string(),
1220 dark: "#FFFFFF".to_string(),
1221 });
1222
1223 tokens.bifrost.insert("blur".to_string(), TokenValue::Single {
1225 value: "25.0".to_string(),
1226 });
1227 tokens.bifrost.insert("saturation".to_string(), TokenValue::Single {
1228 value: "1.2".to_string(),
1229 });
1230 tokens.bifrost.insert("opacity".to_string(), TokenValue::Single {
1231 value: "0.65".to_string(),
1232 });
1233
1234 tokens.gungnir.insert("intensity".to_string(), TokenValue::Single {
1236 value: "1.0".to_string(),
1237 });
1238 tokens.gungnir.insert("radius".to_string(), TokenValue::Single {
1239 value: "15.0".to_string(),
1240 });
1241
1242 tokens.mjolnir.insert("clip_angle".to_string(), TokenValue::Single {
1244 value: "12.0".to_string(),
1245 });
1246 tokens.mjolnir.insert("border_width".to_string(), TokenValue::Single {
1247 value: "2.0".to_string(),
1248 });
1249
1250 tokens.anim.insert("stiffness".to_string(), TokenValue::Single {
1252 value: "170.0".to_string(),
1253 });
1254 tokens.anim.insert("damping".to_string(), TokenValue::Single {
1255 value: "26.0".to_string(),
1256 });
1257 tokens.anim.insert("mass".to_string(), TokenValue::Single {
1258 value: "1.0".to_string(),
1259 });
1260
1261 tokens.accessibility.insert("reduce_motion".to_string(), TokenValue::Single {
1263 value: "false".to_string(),
1264 });
1265
1266 tokens
1267}
1268
1269
1270
1271
1272pub struct Environment<K: EnvKey> {
1274 _marker: std::marker::PhantomData<K>,
1275}
1276
1277impl<K: EnvKey> Environment<K> {
1278 pub fn new() -> Self {
1280 Self {
1281 _marker: std::marker::PhantomData,
1282 }
1283 }
1284
1285 pub fn get(&self) -> K::Value {
1287 if let Some(env_store) = ENVIRONMENT.get() {
1288 let env_lock = env_store.lock().unwrap();
1289 if let Some(val) = env_lock.get(&std::any::TypeId::of::<K>()) {
1290 if let Some(typed_val) = val.downcast_ref::<K::Value>() {
1291 return typed_val.clone();
1292 }
1293 }
1294 }
1295 K::default_value()
1296 }
1297}
1298
1299pub mod env {
1301
1302 pub fn insert<K: super::EnvKey>(value: K::Value) {
1304 if let Some(store) = super::ENVIRONMENT.get() {
1305 let mut env_map = store.lock().unwrap();
1306 env_map.insert(std::any::TypeId::of::<K>(), Box::new(value));
1307 }
1308 }
1309
1310 pub fn remove<K: super::EnvKey>() {
1312 if let Some(store) = super::ENVIRONMENT.get() {
1313 let mut env_map = store.lock().unwrap();
1314 env_map.remove(&std::any::TypeId::of::<K>());
1315 }
1316 }
1317}
1318
1319
1320
1321#[derive(Debug, Clone, Copy, PartialEq)]
1325pub struct Size {
1326 pub width: f32,
1327 pub height: f32,
1328}
1329
1330#[derive(Debug, Clone, Copy, PartialEq)]
1332pub struct EdgeInsets {
1333 pub top: f32,
1334 pub leading: f32,
1335 pub bottom: f32,
1336 pub trailing: f32,
1337}
1338
1339impl EdgeInsets {
1340 pub fn all(value: f32) -> Self {
1342 Self {
1343 top: value,
1344 leading: value,
1345 bottom: value,
1346 trailing: value,
1347 }
1348 }
1349
1350 pub fn vertical(value: f32) -> Self {
1352 Self {
1353 top: value,
1354 leading: 0.0,
1355 bottom: value,
1356 trailing: 0.0,
1357 }
1358 }
1359
1360 pub fn horizontal(value: f32) -> Self {
1362 Self {
1363 top: 0.0,
1364 leading: value,
1365 bottom: 0.0,
1366 trailing: value,
1367 }
1368 }
1369}
1370
1371#[derive(Debug, Clone, Copy, PartialEq)]
1373pub struct FrameModifier {
1374 pub width: Option<f32>,
1375 pub height: Option<f32>,
1376}
1377
1378impl FrameModifier {
1379 pub fn new() -> Self {
1380 Self {
1381 width: None,
1382 height: None,
1383 }
1384 }
1385
1386 pub fn width(mut self, width: f32) -> Self {
1387 self.width = Some(width);
1388 self
1389 }
1390
1391 pub fn height(mut self, height: f32) -> Self {
1392 self.height = Some(height);
1393 self
1394 }
1395
1396 pub fn size(mut self, width: f32, height: f32) -> Self {
1397 self.width = Some(width);
1398 self.height = Some(height);
1399 self
1400 }
1401}
1402
1403impl ViewModifier for FrameModifier {
1404 fn modify<V: View>(self, content: V) -> impl View {
1405 ModifiedView::new(content, self)
1406 }
1407}
1408
1409
1410#[derive(Debug, Clone, Copy, PartialEq)]
1412pub struct OffsetModifier {
1413 pub x: f32,
1414 pub y: f32,
1415}
1416
1417impl OffsetModifier {
1418 pub fn new(x: f32, y: f32) -> Self {
1419 Self { x, y }
1420 }
1421}
1422
1423impl ViewModifier for OffsetModifier {
1424 fn modify<V: View>(self, content: V) -> impl View {
1425 ModifiedView::new(content, self)
1426 }
1427}
1428
1429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1431pub struct ZIndexModifier {
1432 pub z_index: i32,
1433}
1434
1435impl ZIndexModifier {
1436 pub fn new(z_index: i32) -> Self {
1437 Self { z_index }
1438 }
1439}
1440
1441impl ViewModifier for ZIndexModifier {
1442 fn modify<V: View>(self, content: V) -> impl View {
1443 ModifiedView::new(content, self)
1444 }
1445}
1446
1447#[derive(Debug, Clone, Copy, PartialEq)]
1449pub struct LayoutConstraints {
1450 pub min_width: Option<f32>,
1451 pub max_width: Option<f32>,
1452 pub min_height: Option<f32>,
1453 pub max_height: Option<f32>,
1454}
1455
1456impl Default for LayoutConstraints {
1457 fn default() -> Self {
1458 Self {
1459 min_width: None,
1460 max_width: None,
1461 min_height: None,
1462 max_height: None,
1463 }
1464 }
1465}
1466
1467#[derive(Debug, Clone, Copy, PartialEq)]
1469pub struct LayoutModifier {
1470 pub constraints: LayoutConstraints,
1471}
1472
1473impl LayoutModifier {
1474 pub fn new(constraints: LayoutConstraints) -> Self {
1475 Self { constraints }
1476 }
1477}
1478
1479impl ViewModifier for LayoutModifier {
1480 fn modify<V: View>(self, content: V) -> impl View {
1481 ModifiedView::new(content, self)
1482 }
1483}
1484
1485#[derive(Debug, Clone, Copy, PartialEq)]
1487pub struct FlexModifier {
1488 pub flex: f32,
1489}
1490
1491impl FlexModifier {
1492 pub fn new(flex: f32) -> Self {
1493 Self { flex }
1494 }
1495}
1496
1497impl ViewModifier for FlexModifier {
1498 fn modify<V: View>(self, content: V) -> impl View {
1499 ModifiedView::new(content, self)
1500 }
1501}
1502
1503pub mod layout {
1505 use super::*;
1506
1507 pub struct LayoutCache;
1509
1510 impl LayoutCache {
1511 pub fn new() -> Self {
1512 Self
1513 }
1514
1515 pub fn clear(&mut self) {
1516 }
1518 }
1519
1520 #[derive(Debug, Clone, Copy, PartialEq)]
1522 pub struct SizeProposal {
1523 pub width: Option<f32>,
1524 pub height: Option<f32>,
1525 }
1526
1527 impl SizeProposal {
1528 pub fn unspecified() -> Self {
1529 Self {
1530 width: None,
1531 height: None,
1532 }
1533 }
1534
1535 pub fn width(width: f32) -> Self {
1536 Self {
1537 width: Some(width),
1538 height: None,
1539 }
1540 }
1541
1542 pub fn height(height: f32) -> Self {
1543 Self {
1544 width: None,
1545 height: Some(height),
1546 }
1547 }
1548
1549 pub fn tight(width: f32, height: f32) -> Self {
1550 Self {
1551 width: Some(width),
1552 height: Some(height),
1553 }
1554 }
1555 }
1556
1557 pub trait LayoutView: Send {
1559 fn size_that_fits(&self, proposal: SizeProposal, subviews: &[&dyn LayoutView], cache: &mut LayoutCache) -> Size;
1561
1562 fn place_subviews(&self, bounds: Rect, subviews: &mut [&mut dyn LayoutView], cache: &mut LayoutCache);
1564 }
1565
1566 #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1568 pub struct Rect {
1569 pub x: f32,
1570 pub y: f32,
1571 pub width: f32,
1572 pub height: f32,
1573 }
1574
1575 impl Rect {
1576 pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
1577 Self { x, y, width, height }
1578 }
1579
1580 pub fn zero() -> Self {
1581 Self { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }
1582 }
1583
1584 pub fn size(&self) -> Size {
1585 Size { width: self.width, height: self.height }
1586 }
1587
1588 pub fn split_horizontal(&self, n: usize) -> Vec<Rect> {
1590 if n == 0 { return vec![]; }
1591 let item_width = self.width / n as f32;
1592 (0..n).map(|i| Rect {
1593 x: self.x + i as f32 * item_width,
1594 y: self.y,
1595 width: item_width,
1596 height: self.height,
1597 }).collect()
1598 }
1599
1600 pub fn split_vertical(&self, n: usize) -> Vec<Rect> {
1602 if n == 0 { return vec![]; }
1603 let item_height = self.height / n as f32;
1604 (0..n).map(|i| Rect {
1605 x: self.x,
1606 y: self.y + i as f32 * item_height,
1607 width: self.width,
1608 height: item_height,
1609 }).collect()
1610 }
1611 }
1612}
1613
1614pub use layout::{LayoutView, SizeProposal, Rect, LayoutCache};
1616pub mod runtime;
1619pub mod scene_graph;
1620
1621pub use scene_graph::{NodeId, bifrost_registry};
1622
1623
1624#[derive(Debug, Clone, PartialEq)]
1626pub enum AssetState<T> {
1627 Loading,
1628 Ready(T),
1629 Error(String),
1630}
1631
1632pub trait AssetManager: Send + Sync {
1634 fn load_image(&self, url: &str) -> AssetState<Arc<Vec<u8>>>;
1636
1637 fn preload_image(&self, url: &str);
1639}
1640
1641
1642#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1644pub enum Event {
1645 PointerDown { x: f32, y: f32 },
1646 PointerUp { x: f32, y: f32 },
1647 PointerMove { x: f32, y: f32 },
1648 KeyDown { key: String },
1649 KeyUp { key: String },
1650}
1651
1652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1654pub enum EventResponse {
1655 Handled,
1656 Ignored,
1657}
1658
1659pub struct DefaultAssetManager {
1661 cache: Arc<std::sync::RwLock<HashMap<String, AssetState<Arc<Vec<u8>>>>>>,
1662}
1663
1664impl DefaultAssetManager {
1665 pub fn new() -> Self {
1666 Self {
1667 cache: Arc::new(std::sync::RwLock::new(HashMap::new())),
1668 }
1669 }
1670}
1671
1672impl AssetManager for DefaultAssetManager {
1673 fn load_image(&self, url: &str) -> AssetState<Arc<Vec<u8>>> {
1674 let mut cache = self.cache.write().unwrap();
1675 if let Some(state) = cache.get(url) {
1676 return state.clone();
1677 }
1678
1679 cache.insert(url.to_string(), AssetState::Loading);
1682 AssetState::Loading
1683 }
1684
1685 fn preload_image(&self, _url: &str) {
1686 }
1688}
1689
1690#[cfg(test)]
1691mod phase1_test;