Skip to main content

webizen_studio/render/
qualia.rs

1//! QualiaDB-driven scenes — the binding that makes this a *semantic* 3D engine.
2//!
3//! A [`SemanticScene`] is the data-driven scene description QualiaDB produces from
4//! a graph query: SPARQL/SPARQL-star results, or N3/`modalities` inference output
5//! (e.g. the anatomy use-case — health observations → organ highlights with an
6//! intensity score). Each [`SceneItem`] carries its **provenance** so geometry is
7//! traceable back to the NQuin that justified it.
8//!
9//! The split is deliberate:
10//! - **Semantics** (what to show, how hot, why) come from QualiaDB.
11//! - **Geometry** (where each item sits, what mesh) comes from a `layout` the
12//!   consumer supplies (e.g. an anatomical atlas), so the same semantic scene can
13//!   drive a body map, a knowledge graph, or a physics field.
14//!
15//! On native, the heavy math/physics behind a scene belongs to QualiaDB
16//! (`geometric_algebra` SIMD, `domains::physical`, `quantum_dft`, `ode_solver`,
17//! diffusion `shaders/`); this module is the UI-side binding, not a math engine.
18
19use super::graph::{Node, Scene, Style};
20use super::mesh::Mesh;
21use super::scene::{Camera, Vec3};
22use serde::{Deserialize, Serialize};
23
24/// Visual state of a semantic item. Matches the anatomy representation contract
25/// (`"highlighted"`, `"active"`, …) so a QualiaDB payload deserializes directly.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
27#[serde(rename_all = "lowercase")]
28pub enum ItemState {
29    #[default]
30    Default,
31    Active,
32    Highlighted,
33    Alert,
34}
35
36/// One element of a semantic scene, produced by a QualiaDB query/inference.
37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
38pub struct SceneItem {
39    /// Stable id used by the layout to look up geometry (e.g. `"heart"`).
40    pub id: String,
41    #[serde(default)]
42    pub state: ItemState,
43    /// Inference confidence / heat, 0.0–1.0.
44    #[serde(default)]
45    pub intensity: f64,
46    /// `q42:` provenance hash linking back to the justifying NQuin(s).
47    #[serde(default)]
48    pub provenance: Option<String>,
49    /// Human-readable reasons ("Why is this highlighted").
50    #[serde(default)]
51    pub reasons: Vec<String>,
52}
53
54/// A semantic, backend-neutral scene description from QualiaDB. Deserializes from
55/// the representation-contract payload returned by a Tauri command / SPARQL query.
56#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
57pub struct SemanticScene {
58    #[serde(default)]
59    pub items: Vec<SceneItem>,
60    #[serde(default)]
61    pub explanations: Vec<String>,
62}
63
64/// Anything that yields a [`SemanticScene`] from the graph — a Tauri command
65/// result wrapper, a SPARQL binding, or the offline stub. Lets UI code stay
66/// agnostic about whether the engine answered or a preview did.
67pub trait SceneSource {
68    fn semantic_scene(&self) -> SemanticScene;
69}
70
71impl SceneSource for SemanticScene {
72    fn semantic_scene(&self) -> SemanticScene {
73        self.clone()
74    }
75}
76
77/// Map a semantic state + intensity to a themeable CSS color. Higher intensity
78/// pushes toward the warm accent; lower stays cool/muted. Deterministic.
79pub fn item_color(state: ItemState, intensity: f64) -> String {
80    let t = intensity.clamp(0.0, 1.0);
81    // Cool (muted blue-grey) → warm (alert orange-red) interpolation.
82    let (r0, g0, b0) = (96.0, 132.0, 168.0);
83    let (r1, g1, b1) = match state {
84        ItemState::Alert => (239.0, 68.0, 68.0),
85        ItemState::Highlighted => (245.0, 158.0, 11.0),
86        ItemState::Active => (34.0, 197.0, 94.0),
87        ItemState::Default => (148.0, 163.0, 184.0),
88    };
89    let lerp = |a: f64, b: f64| (a + (b - a) * t).round() as u8;
90    let alpha = 0.35 + 0.6 * t;
91    format!(
92        "rgba({}, {}, {}, {:.2})",
93        lerp(r0, r1),
94        lerp(g0, g1),
95        lerp(b0, b1),
96        alpha
97    )
98}
99
100/// Build a renderable [`Scene`] from a [`SemanticScene`] plus a `layout` that maps
101/// each item id to its world position and mesh. Items the layout doesn't recognise
102/// are skipped. Each item becomes a [`Node`] colored by [`item_color`]; its
103/// provenance and reasons ride along on the node label for inspection/tooltips.
104pub fn build_scene<L>(sem: &SemanticScene, camera: Camera, layout: L) -> Scene
105where
106    L: Fn(&str) -> Option<(Vec3, Mesh)>,
107{
108    let mut scene = Scene::new(camera).with_background("var(--qualia-bg)");
109    for item in &sem.items {
110        let Some((position, mesh)) = layout(&item.id) else {
111            continue;
112        };
113        let color = item_color(item.state, item.intensity);
114        let style = match item.state {
115            ItemState::Default => Style::wire(color),
116            _ => Style {
117                stroke: Some(color.clone()),
118                fill: Some(color),
119                ..Default::default()
120            },
121        };
122        let label = match &item.provenance {
123            Some(p) => format!("{} [{}]", item.id, p),
124            None => item.id.clone(),
125        };
126        scene = scene.add(
127            Node::new(label)
128                .at(position)
129                .with_mesh(mesh)
130                .with_style(style),
131        );
132    }
133    scene
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn item_color_intensity_monotonic_alpha() {
142        let lo = item_color(ItemState::Highlighted, 0.0);
143        let hi = item_color(ItemState::Highlighted, 1.0);
144        assert_ne!(lo, hi);
145        assert!(hi.contains("0.95")); // alpha ramps with intensity
146    }
147
148    #[test]
149    fn build_scene_uses_layout_and_skips_unknown() {
150        let sem = SemanticScene {
151            items: vec![
152                SceneItem {
153                    id: "heart".into(),
154                    state: ItemState::Highlighted,
155                    intensity: 0.8,
156                    provenance: Some("q42:abc".into()),
157                    reasons: vec!["elevated BP".into()],
158                },
159                SceneItem {
160                    id: "unknown".into(),
161                    ..SceneItem {
162                        id: String::new(),
163                        state: ItemState::Default,
164                        intensity: 0.0,
165                        provenance: None,
166                        reasons: vec![],
167                    }
168                },
169            ],
170            explanations: vec![],
171        };
172        let scene = build_scene(&sem, Camera::default(), |id| {
173            (id == "heart").then(|| (Vec3::new(0.0, 0.0, 0.0), Mesh::uv_sphere(1.0, 6, 8)))
174        });
175        assert_eq!(scene.roots.len(), 1, "unknown id skipped");
176        assert!(scene.roots[0].label.contains("q42:abc"));
177    }
178
179    #[test]
180    fn semantic_scene_deserializes_from_contract_json() {
181        let json = r#"{"items":[{"id":"heart","state":"highlighted","intensity":0.82,
182            "provenance":"q42:deadbeef","reasons":["elevated BP"]}],
183            "explanations":["cardiovascular load"]}"#;
184        let s: SemanticScene = serde_json::from_str(json).unwrap();
185        assert_eq!(s.items.len(), 1);
186        assert_eq!(s.items[0].state, ItemState::Highlighted);
187        assert_eq!(s.explanations[0], "cardiovascular load");
188    }
189}