Skip to main content

webizen_studio/render/
scene_to_contract.rs

1//! Convert internal Scene graph to neutral RenderScene contract
2//!
3//! This module provides the mapping layer between webizen-studio's rich
4//! scene graph (Scene/Node/Mesh) and webizen-render's neutral GPU contract
5//! (RenderScene/SceneNode/SceneEdge/SceneFace). This allows the studio to
6//! drive the headless GPU renderer while keeping the dependency direction
7//! correct (studio → render).
8
9use super::graph::{Node, Scene};
10use super::scene::{Camera, Vec3};
11use webizen_render::scene_contract::{
12    RenderScene, SceneCamera, SceneEdge, SceneFace, SceneNode, ScenePoint,
13};
14
15/// Convert webizen-studio Camera to RenderScene SceneCamera
16impl From<Camera> for SceneCamera {
17    fn from(camera: Camera) -> Self {
18        SceneCamera {
19            position: [camera.eye.x, camera.eye.y, camera.eye.z],
20            target: [camera.target.x, camera.target.y, camera.target.z],
21            fov: 60.0, // Fixed FOV for now - can be derived from focal_scale
22        }
23    }
24}
25
26/// Convert internal Scene to RenderScene contract
27impl From<Scene> for RenderScene {
28    fn from(scene: Scene) -> Self {
29        let mut render_scene = RenderScene::new();
30        render_scene.set_camera(scene.camera.into());
31
32        // Convert CSS variable background to fallback color
33        // In production, this would resolve theme variables
34        let bg_color = resolve_css_color(&scene.background);
35        render_scene.set_background(bg_color);
36
37        // Walk the scene graph and collect all renderable elements
38        for root in &scene.roots {
39            collect_scene_elements(root, &|v| v, &mut render_scene);
40        }
41
42        render_scene
43    }
44}
45
46/// Recursively collect renderable elements from the scene graph
47fn collect_scene_elements(
48    node: &Node,
49    world_transform: &dyn Fn(Vec3) -> Vec3,
50    render_scene: &mut RenderScene,
51) {
52    let to_world = |v: Vec3| world_transform(node.transform.apply(v));
53
54    if let Some(mesh) = &node.mesh {
55        let style = &node.style;
56
57        // Collect faces (filled polygons) - drawn first (background layer)
58        if let Some(fill) = &style.fill {
59            for face in &mesh.faces {
60                let vertices: Vec<ScenePoint> = face
61                    .iter()
62                    .filter_map(|&i| {
63                        let world_pos = to_world(mesh.vertices[i]);
64                        // Project to normalized screen space (0..1)
65                        // For now, use simple orthographic projection
66                        // TODO: Use camera projection from Scene
67                        Some(ScenePoint {
68                            x: normalize_coordinate(world_pos.x),
69                            y: normalize_coordinate(world_pos.y),
70                            z: normalize_coordinate(world_pos.z),
71                        })
72                    })
73                    .collect();
74
75                if vertices.len() >= 3 {
76                    render_scene.add_face(SceneFace {
77                        vertices,
78                        color: resolve_css_color(fill),
79                        alpha: style.alpha,
80                    });
81                }
82            }
83        }
84
85        // Collect edges (lines)
86        if let Some(stroke) = &style.stroke {
87            for &(a, b) in &mesh.edges {
88                let from = to_world(mesh.vertices[a]);
89                let to = to_world(mesh.vertices[b]);
90
91                // Semantic shading: derive edge strength from node weights
92                let edge_weight = compute_edge_weight(node);
93                let (width, alpha) = compute_edge_attributes(edge_weight, style.width, style.alpha);
94
95                render_scene.add_edge(SceneEdge {
96                    from: ScenePoint {
97                        x: normalize_coordinate(from.x),
98                        y: normalize_coordinate(from.y),
99                        z: normalize_coordinate(from.z),
100                    },
101                    to: ScenePoint {
102                        x: normalize_coordinate(to.x),
103                        y: normalize_coordinate(to.y),
104                        z: normalize_coordinate(to.z),
105                    },
106                    color: resolve_css_color(stroke),
107                    width,
108                    alpha,
109                });
110            }
111        }
112
113        // Collect vertices as nodes (points) - drawn last (foreground layer)
114        if let Some(point) = &style.point {
115            for v in &mesh.vertices {
116                let world_pos = to_world(*v);
117
118                // Semantic shading: derive weight from transform scale
119                let weight = extract_semantic_weight(node);
120                let radius = compute_radius_from_weight(weight, style.point_radius);
121
122                // Semantic shading: derive classification from node label
123                let classification = extract_classification_from_label(&node.label);
124                let color = map_classification_to_color(classification, point);
125
126                // Animation states: derive from node label semantics
127                let (is_inferencing, pulse_rate) = extract_animation_state(&node.label);
128
129                let entity_id = if node.entity_id != 0 {
130                    node.entity_id
131                } else {
132                    parse_entity_id_from_label(&node.label)
133                };
134                render_scene.add_node(SceneNode {
135                    id: node.label.clone(),
136                    position: ScenePoint {
137                        x: normalize_coordinate(world_pos.x),
138                        y: normalize_coordinate(world_pos.y),
139                        z: normalize_coordinate(world_pos.z),
140                    },
141                    color,
142                    radius,
143                    alpha: style.alpha,
144                    is_inferencing,
145                    pulse_rate,
146                    tensor: webizen_render::scene_contract::Tensor10DProjection::default(),
147                    epistemic_state: webizen_render::scene_contract::EpistemicState::Collapsed,
148                    version: 0.0,
149                    entity_id,
150                    affordance_bits: node.affordance_bits,
151                });
152            }
153        }
154    }
155
156    // Recursively process children
157    for child in &node.children {
158        collect_scene_elements(child, &to_world, render_scene);
159    }
160}
161
162/// Parse entity id from layout ids like `016x` hex (`{:016x}` from entity_view projection).
163pub(crate) fn parse_entity_id_from_label(label: &str) -> u64 {
164    let s = label.trim();
165    if s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit()) {
166        return u64::from_str_radix(s, 16).unwrap_or(0);
167    }
168    if let Some(hex) = s.strip_prefix("entity:") {
169        if hex.chars().all(|c| c.is_ascii_hexdigit()) {
170            return u64::from_str_radix(hex, 16).unwrap_or(0);
171        }
172    }
173    0
174}
175
176#[cfg(test)]
177mod entity_id_tests {
178    use super::parse_entity_id_from_label;
179
180    #[test]
181    fn parses_layout_hex_id() {
182        assert_eq!(parse_entity_id_from_label("00000000000000ab"), 0xab);
183        assert_eq!(parse_entity_id_from_label("entity:ff"), 0xff);
184        assert_eq!(parse_entity_id_from_label("plain-label"), 0);
185    }
186}
187
188/// Extract semantic weight from a node's transform scale.
189/// Larger scales indicate more important/central entities.
190fn extract_semantic_weight(node: &Node) -> f64 {
191    // Use the maximum scale component as the weight indicator
192    node.transform
193        .scale
194        .x
195        .max(node.transform.scale.y)
196        .max(node.transform.scale.z)
197}
198
199/// Compute edge weight from node weight.
200/// Edges from higher-weight nodes are considered stronger.
201fn compute_edge_weight(node: &Node) -> f64 {
202    extract_semantic_weight(node)
203}
204
205/// Compute edge width and alpha from edge weight.
206/// Stronger edges get thicker lines and higher opacity.
207fn compute_edge_attributes(edge_weight: f64, base_width: f64, base_alpha: f64) -> (f64, f64) {
208    // Clamp weight to reasonable range
209    let clamped_weight = edge_weight.clamp(0.1, 10.0);
210    // Linear scaling for width (edges shouldn't get too thick)
211    let width = base_width * (1.0 + (clamped_weight - 1.0) * 0.5);
212    // Alpha scales with weight (stronger edges are more visible)
213    let alpha = base_alpha * clamped_weight.min(1.0);
214    (width, alpha.clamp(0.1, 1.0))
215}
216
217/// Compute radius from weight using non-linear scaling.
218/// Uses square root scaling to prevent outliers from dominating the screen.
219fn compute_radius_from_weight(weight: f64, base_radius: f64) -> f64 {
220    // Clamp weight to reasonable range (0.1 to 10.0)
221    let clamped_weight = weight.clamp(0.1, 10.0);
222    // Square root scaling: sqrt(weight) * base_radius
223    base_radius * clamped_weight.sqrt()
224}
225
226/// Extract classification from node label.
227/// Parses semantic type hints from label naming conventions.
228fn extract_classification_from_label(label: &str) -> SemanticClassification {
229    let label_lower = label.to_lowercase();
230
231    if label_lower.contains("person")
232        || label_lower.contains("user")
233        || label_lower.contains("agent")
234    {
235        SemanticClassification::Person
236    } else if label_lower.contains("concept")
237        || label_lower.contains("idea")
238        || label_lower.contains("topic")
239    {
240        SemanticClassification::Concept
241    } else if label_lower.contains("document")
242        || label_lower.contains("file")
243        || label_lower.contains("resource")
244    {
245        SemanticClassification::Document
246    } else if label_lower.contains("location")
247        || label_lower.contains("place")
248        || label_lower.contains("spatial")
249    {
250        SemanticClassification::Location
251    } else if label_lower.contains("event")
252        || label_lower.contains("action")
253        || label_lower.contains("activity")
254    {
255        SemanticClassification::Event
256    } else if label_lower.contains("organization")
257        || label_lower.contains("company")
258        || label_lower.contains("group")
259    {
260        SemanticClassification::Organization
261    } else {
262        SemanticClassification::Generic
263    }
264}
265
266/// Map semantic classification to color.
267/// Returns RGBA color arrays for the GPU shader.
268fn map_classification_to_color(
269    classification: SemanticClassification,
270    fallback_color: &str,
271) -> String {
272    match classification {
273        SemanticClassification::Person => "#3b82f6".to_string(), // Blue
274        SemanticClassification::Concept => "#f59e0b".to_string(), // Orange
275        SemanticClassification::Document => "#10b981".to_string(), // Green
276        SemanticClassification::Location => "#8b5cf6".to_string(), // Purple
277        SemanticClassification::Event => "#ef4444".to_string(),  // Red
278        SemanticClassification::Organization => "#6366f1".to_string(), // Indigo
279        SemanticClassification::Generic => resolve_css_color(fallback_color),
280    }
281}
282
283/// Extract animation state from node label.
284/// Derives inferencing state and pulse rate from semantic hints.
285fn extract_animation_state(label: &str) -> (bool, f64) {
286    let label_lower = label.to_lowercase();
287
288    // Nodes with "inferencing", "processing", or "active" keywords are animated
289    let is_inferencing = label_lower.contains("inferencing")
290        || label_lower.contains("processing")
291        || label_lower.contains("computing")
292        || label_lower.contains("active");
293
294    // Pulse rate based on semantic intensity (higher for critical nodes)
295    let pulse_rate = if label_lower.contains("critical") || label_lower.contains("urgent") {
296        2.0 // Fast pulse
297    } else if label_lower.contains("normal") || label_lower.contains("standard") {
298        1.0 // Normal pulse
299    } else if is_inferencing {
300        0.5 // Slow pulse for inferencing
301    } else {
302        0.0 // Static
303    };
304
305    (is_inferencing, pulse_rate)
306}
307
308/// Semantic classification of nodes for color mapping.
309#[derive(Debug, Clone, Copy, PartialEq)]
310enum SemanticClassification {
311    Person,
312    Concept,
313    Document,
314    Location,
315    Event,
316    Organization,
317    Generic,
318}
319
320/// Normalize a world coordinate to screen space (0..1)
321/// This is a simplified projection - in production, use proper camera projection
322fn normalize_coordinate(coord: f64) -> f64 {
323    // Simple normalization: map from typical world range (-10..10) to (0..1)
324    (coord + 10.0) / 20.0
325}
326
327/// Resolve CSS color variables to concrete colors
328/// For now, this handles CSS variables and returns a fallback
329fn resolve_css_color(color: &str) -> String {
330    // Handle CSS custom properties (variables)
331    if color.starts_with("var(") {
332        // Map common theme variables to fallback colors
333        return match color {
334            s if s.contains("qualia-accent") => "#67e8f9".to_string(), // Cyan
335            s if s.contains("qualia-bg") => "#101820".to_string(),     // Dark slate
336            s if s.contains("qualia-primary") => "#3b82f6".to_string(), // Blue
337            s if s.contains("qualia-secondary") => "#8b5cf6".to_string(), // Purple
338            s if s.contains("qualia-success") => "#10b981".to_string(), // Green
339            s if s.contains("qualia-warning") => "#f59e0b".to_string(), // Amber
340            s if s.contains("qualia-error") => "#ef4444".to_string(),  // Red
341            _ => "#ffffff".to_string(),                                // Fallback to white
342        };
343    }
344
345    // Return CSS color as-is if it's not a variable
346    color.to_string()
347}
348
349#[cfg(test)]
350mod tests {
351    use super::super::graph::Style;
352    use super::super::mesh::Mesh;
353    use super::*;
354
355    #[test]
356    fn test_camera_conversion() {
357        let camera = Camera::default();
358        let scene_camera = SceneCamera::from(camera);
359        assert_eq!(scene_camera.position, [0.0, 8.0, 18.0]);
360        assert_eq!(scene_camera.target, [0.0, 0.5, 0.0]);
361    }
362
363    #[test]
364    fn test_empty_scene_conversion() {
365        let scene = Scene::new(Camera::default());
366        let render_scene = RenderScene::from(scene);
367        assert!(render_scene.is_empty());
368        assert_eq!(render_scene.background, "#101820");
369    }
370
371    #[test]
372    fn test_scene_with_cube_conversion() {
373        let scene = Scene::new(Camera::default()).add(
374            Node::new("cube")
375                .with_mesh(Mesh::cube(1.0))
376                .with_style(Style::wire("#67e8f9")),
377        );
378
379        let render_scene = RenderScene::from(scene);
380        // A cube has edges and vertices
381        assert!(!render_scene.is_empty());
382        assert!(render_scene.edges.len() > 0);
383    }
384
385    #[test]
386    fn test_css_color_resolution() {
387        assert_eq!(resolve_css_color("var(--qualia-accent)"), "#67e8f9");
388        assert_eq!(resolve_css_color("var(--qualia-bg)"), "#101820");
389        assert_eq!(resolve_css_color("#ff0000"), "#ff0000");
390        assert_eq!(resolve_css_color("rgb(255,0,0)"), "rgb(255,0,0)");
391    }
392
393    #[test]
394    fn test_coordinate_normalization() {
395        // Map -10..10 to 0..1
396        assert_eq!(normalize_coordinate(-10.0), 0.0);
397        assert_eq!(normalize_coordinate(0.0), 0.5);
398        assert_eq!(normalize_coordinate(10.0), 1.0);
399    }
400}