Skip to main content

webizen_render/
lib.rs

1//! Webizen N-Dimensional Renderer
2//!
3//! A zero-heap, N-dimensional semantic renderer that projects QualiaDB's
4//! multi-modal logic graph onto 2D/3D surfaces using Projective Geometric Algebra (PGA).
5//!
6//! # Features
7//! - PGA-based transformations (Motors unify rotation and translation)
8//! - Zero-heap render loop (512-byte stack buffer discipline)
9//! - Cross-platform support (WASM/Windows/Apple Silicon)
10//! - Semantic culling (Deontic/Temporal passes)
11//! - Epistemic Level of Detail (DoXastic LoD)
12
13pub mod audio_contract;
14pub mod geo_viewport;
15pub mod math;
16pub mod pipeline;
17#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
18pub mod poet_preview;
19pub mod scene_contract;
20pub mod shaders;
21pub mod telemetry;
22pub mod ui;
23pub mod ui_layout;
24pub mod ui_msdf_text;
25#[cfg(feature = "qualia")]
26pub mod volumetric;
27#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
28mod volumetric_native_preview;
29#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
30mod volumetric_shot;
31#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
32pub use volumetric_shot::{NativeShot, ShotProbe};
33#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
34pub use volumetric_native_preview::{ReviewGeometry, ReviewView, REVIEW_VIEWS};
35#[cfg(feature = "qualia")]
36pub mod volumetric_hmc;
37#[cfg(feature = "qualia")]
38mod volumetric_texture;
39pub mod wgpu_renderer;
40pub mod zero_copy_views;
41
42// Re-export main types for convenience
43pub use math::{AlignedBufferF32, Motor, MotorEncoder, RenderQuin};
44#[cfg(feature = "qualia")]
45pub use pipeline::{WebizenFramePlan, WebizenFrameScheduleError, WebizenFrameScheduler};
46pub use pipeline::{
47    admit_capabilities, FrameExtent, HistoryPublication, LinearDepthView, MotionVectorsView,
48    ReactiveMaskView, TemporalAdmission, TemporalCapabilityRefusal, TemporalContractError,
49    TemporalFrameContract, TemporalHistoryContract, TemporalProducerCapabilities,
50    TemporalProducerContract, TemporalResource,
51};
52pub use pipeline::{BindGroupManager, RenderBindGroups};
53pub use scene_contract::{RenderScene, SceneCamera, SceneEdge, SceneFace, SceneNode, ScenePoint};
54pub use shaders::{EPISTEMIC_WGSL, PROJECTOR_WGSL};
55pub use telemetry::SystemTelemetry;
56pub use ui::{
57    Color4f, NodeWire, Rect2D, UiWidget, WidgetKind, ZeroHeapUiCanvas, MAX_UI_TEXT_QUADS,
58    MAX_UI_WIDGETS, MAX_UI_WIRES,
59};
60pub use ui_layout::{
61    AlignItems, ComputedUiRect, Edges, FlexDirection, JustifyContent, Margin, Padding, SizeRule,
62    UiLayoutNode, UiLayoutStyle, ZeroHeapUiLayoutTree, MAX_UI_LAYOUT_NODES, NO_UI_NODE,
63};
64pub use ui_msdf_text::{
65    generate_procedural_msdf_atlas_into, glyph_metrics_for_char, glyph_slot_for_char,
66    kerning_advance_em, msdf_median_of_three, shape_text_zero_heap, MsdfGlyphMetrics,
67    MsdfTextQuad, ShapedTextRunMetrics, MAX_MSDF_TEXT_QUADS, MSDF_ATLAS_COLS,
68    MSDF_ATLAS_GLYPH_COUNT, MSDF_ATLAS_HEIGHT, MSDF_ATLAS_ROWS, MSDF_ATLAS_WIDTH, MSDF_CELL_PX,
69    MSDF_PIXEL_RANGE, MSDF_TEXT_WGSL,
70};
71#[cfg(feature = "qualia")]
72pub use volumetric::{HmcTextureAdmissionReport, HmcTextureStreamRequest, VolumetricRenderer};
73#[cfg(all(feature = "qualia", not(target_arch = "wasm32")))]
74pub use volumetric::{
75    render_scene_png as render_volumetric_scene_png, render_scene_rgba8_into,
76};
77#[cfg(not(target_arch = "wasm32"))]
78pub use wgpu_renderer::{
79    render_preview_data_uri, render_preview_png, render_scene_data_uri, render_scene_png,
80    render_scene_png_with_time,
81};
82pub use wgpu_renderer::{
83    pixel_receipt_from_rgba8, probe_webgpu_capabilities, Camera, PixelFormat, PixelReadback,
84    PixelReceipt,
85    PixelReceiptStatus, ScreenPoint, Vec3, WebGpuAdapterReport, WebGpuCapabilityReport,
86    WebGpuFeatureReport, WebGpuLimitReport, WebGpuRuntimeReceipt, WebGpuStatus, WgpuRenderer,
87    MAX_OFFSCREEN_DIMENSION, MAX_PIXEL_READBACK_BYTES,
88};
89pub use zero_copy_views::{CameraUniform, ModelUniform, Std140Field, Std140Type, TimeUniform};
90
91// Decoupled volumetric/holographic and EMF pipelines from etalon-render
92pub use etalon_render;
93pub use etalon_render::{
94    EmfFieldCell, EmfPipeline, EmfPipelineDesc, EmfSliceUniform, FrameCameraPod,
95    HolographicNodeGpu as EtalonHolographicNodeGpu, ManifoldProjectionPod,
96    ObserverStandpointUniform as EtalonObserverStandpointUniform,
97    VolumetricPipeline as EtalonVolumetricPipeline, EMF_VOLUMETRIC_WGSL, HOLOGRAPHIC_WGSL,
98};
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn test_motor_size() {
106        assert_eq!(std::mem::size_of::<Motor>(), 64);
107    }
108
109    #[test]
110    fn test_render_quin_size() {
111        assert_eq!(std::mem::size_of::<RenderQuin>(), 64);
112    }
113
114    #[test]
115    fn test_motor_encoder() {
116        let mut encoder = MotorEncoder::new();
117        encoder.add_motor(Motor::identity());
118        assert_eq!(encoder.len(), 1);
119
120        let bytes = encoder.encode();
121        assert_eq!(bytes.len(), 64); // 1 motor * 64 bytes
122    }
123
124    #[test]
125    fn test_render_quin_creation() {
126        let quin = RenderQuin::new(
127            [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
128            123,
129            0.5,
130            0.9,
131            1000.0,
132        );
133        assert_eq!(quin.semantic_id, 123);
134        assert_eq!(quin.intensity, 0.5);
135    }
136
137    #[test]
138    fn test_shaders_exist() {
139        // Verify shaders are included
140        assert!(!PROJECTOR_WGSL.is_empty());
141        assert!(!EPISTEMIC_WGSL.is_empty());
142    }
143
144    #[test]
145    fn test_etalon_render_reexports() {
146        assert!(!EMF_VOLUMETRIC_WGSL.is_empty());
147        assert!(!HOLOGRAPHIC_WGSL.is_empty());
148        assert_eq!(std::mem::size_of::<FrameCameraPod>(), 160);
149        assert_eq!(std::mem::size_of::<ManifoldProjectionPod>(), 48);
150    }
151
152    /// End-to-end headless render: build an offscreen renderer, clear to red,
153    /// and read the pixels back. Skips gracefully when no GPU adapter is present
154    /// (e.g. a headless CI box without a software fallback).
155    #[cfg(not(target_arch = "wasm32"))]
156    #[test]
157    fn offscreen_clear_reads_back_solid_color() {
158        let renderer = match pollster::block_on(WgpuRenderer::new_offscreen(64, 64)) {
159            Ok(r) => r,
160            Err(e) => {
161                eprintln!("skipping offscreen render test: no GPU adapter ({e})");
162                return;
163            }
164        };
165
166        renderer.clear("#ff0000");
167        let pixels = renderer
168            .read_pixels()
169            .expect("offscreen target yields pixels");
170
171        assert_eq!(pixels.len(), 64 * 64 * 4, "tightly-packed RGBA8");
172        // sRGB endpoints are invariant, so a pure-red clear reads back as (255,0,0,255).
173        assert!(
174            pixels[0] > 200,
175            "expected red channel high, got {}",
176            pixels[0]
177        );
178        assert!(
179            pixels[1] < 80,
180            "expected green channel low, got {}",
181            pixels[1]
182        );
183        assert!(
184            pixels[2] < 80,
185            "expected blue channel low, got {}",
186            pixels[2]
187        );
188        assert_eq!(pixels[3], 255, "expected opaque alpha");
189    }
190
191    /// Locks in the linear (non-sRGB) offscreen target: a mid-tone CSS color must
192    /// read back byte-for-byte. An sRGB target would re-encode 128 (~0.50) up to
193    /// ~188, so this test fails if the format regresses to `Rgba8UnormSrgb`.
194    #[cfg(not(target_arch = "wasm32"))]
195    #[test]
196    fn offscreen_midtone_passthrough_is_linear() {
197        let renderer = match pollster::block_on(WgpuRenderer::new_offscreen(64, 64)) {
198            Ok(r) => r,
199            Err(e) => {
200                eprintln!("skipping offscreen midtone test: no GPU adapter ({e})");
201                return;
202            }
203        };
204
205        renderer.clear("#808080"); // byte 128 per channel
206        let pixels = renderer
207            .read_pixels()
208            .expect("offscreen target yields pixels");
209
210        // Allow ±2 for rounding; sRGB re-encoding would land near 188 and fail.
211        for (i, label) in ["R", "G", "B"].iter().enumerate() {
212            assert!(
213                (126..=130).contains(&pixels[i]),
214                "{label} expected ~128 (linear passthrough), got {}",
215                pixels[i]
216            );
217        }
218    }
219
220    /// Render real content (a triangle on a dark clear) and confirm we produce a
221    /// valid PNG headlessly — the byte stream a webview can display directly.
222    #[cfg(not(target_arch = "wasm32"))]
223    #[test]
224    fn offscreen_encodes_valid_png() {
225        let renderer = match pollster::block_on(WgpuRenderer::new_offscreen(96, 96)) {
226            Ok(r) => r,
227            Err(e) => {
228                eprintln!("skipping png test: no GPU adapter ({e})");
229                return;
230            }
231        };
232
233        renderer.clear("#101820");
234        renderer.fill_polygon(
235            &[
236                ScreenPoint { x: 48.0, y: 12.0 },
237                ScreenPoint { x: 12.0, y: 82.0 },
238                ScreenPoint { x: 84.0, y: 82.0 },
239            ],
240            "#67e8f9",
241            1.0,
242        );
243
244        let png = renderer.read_png().expect("offscreen yields a PNG");
245
246        // PNG 8-byte signature.
247        assert_eq!(
248            &png[..8],
249            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
250            "expected PNG magic bytes"
251        );
252        assert!(
253            png.len() > 100,
254            "PNG should be non-trivial, got {} bytes",
255            png.len()
256        );
257        eprintln!("encoded headless PNG: {} bytes", png.len());
258    }
259
260    /// The one-call bridge the native webview uses: render → PNG → base64 data-URI.
261    #[cfg(not(target_arch = "wasm32"))]
262    #[test]
263    fn preview_data_uri_is_well_formed() {
264        let uri = match render_preview_data_uri(80, 80) {
265            Some(u) => u,
266            None => {
267                eprintln!("skipping data-uri test: no GPU adapter");
268                return;
269            }
270        };
271        assert!(
272            uri.starts_with("data:image/png;base64,"),
273            "expected PNG data-URI, got: {}",
274            &uri[..uri.len().min(40)]
275        );
276        assert!(uri.len() > 200, "data-URI should carry real image data");
277        eprintln!("preview data-URI: {} chars", uri.len());
278    }
279
280    /// Test RenderScene contract with nodes (points)
281    #[cfg(not(target_arch = "wasm32"))]
282    #[test]
283    fn render_scene_with_nodes() {
284        let mut scene = RenderScene::new();
285        scene.add_node(SceneNode {
286            position: ScenePoint {
287                x: 0.5,
288                y: 0.5,
289                z: 0.0,
290            },
291            color: "#ff0000".to_string(),
292            radius: 10.0,
293            alpha: 1.0,
294            ..SceneNode::default()
295        });
296        scene.add_node(SceneNode {
297            position: ScenePoint {
298                x: 0.2,
299                y: 0.3,
300                z: 0.0,
301            },
302            color: "#00ff00".to_string(),
303            radius: 5.0,
304            alpha: 0.8,
305            ..SceneNode::default()
306        });
307
308        let png = match render_scene_png(&scene, 64, 64) {
309            Some(p) => p,
310            None => {
311                eprintln!("skipping render_scene test: no GPU adapter");
312                return;
313            }
314        };
315
316        assert_eq!(
317            &png[..8],
318            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
319            "expected PNG magic bytes"
320        );
321        eprintln!("rendered scene with nodes: {} bytes", png.len());
322    }
323
324    /// Test RenderScene contract with edges (lines)
325    #[cfg(not(target_arch = "wasm32"))]
326    #[test]
327    fn render_scene_with_edges() {
328        let mut scene = RenderScene::new();
329        scene.add_edge(SceneEdge {
330            from: ScenePoint {
331                x: 0.1,
332                y: 0.1,
333                z: 0.0,
334            },
335            to: ScenePoint {
336                x: 0.9,
337                y: 0.9,
338                z: 0.0,
339            },
340            color: "#67e8f9".to_string(),
341            width: 2.0,
342            alpha: 1.0,
343        });
344
345        let png = match render_scene_png(&scene, 64, 64) {
346            Some(p) => p,
347            None => {
348                eprintln!("skipping render_scene test: no GPU adapter");
349                return;
350            }
351        };
352
353        assert_eq!(
354            &png[..8],
355            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
356            "expected PNG magic bytes"
357        );
358        eprintln!("rendered scene with edges: {} bytes", png.len());
359    }
360
361    /// Test RenderScene contract with faces (filled polygons)
362    #[cfg(not(target_arch = "wasm32"))]
363    #[test]
364    fn render_scene_with_faces() {
365        let mut scene = RenderScene::new();
366        scene.add_face(SceneFace {
367            vertices: vec![
368                ScenePoint {
369                    x: 0.5,
370                    y: 0.1,
371                    z: 0.0,
372                },
373                ScenePoint {
374                    x: 0.1,
375                    y: 0.9,
376                    z: 0.0,
377                },
378                ScenePoint {
379                    x: 0.9,
380                    y: 0.9,
381                    z: 0.0,
382                },
383            ],
384            color: "#f59e0b".to_string(),
385            alpha: 1.0,
386        });
387
388        let png = match render_scene_png(&scene, 64, 64) {
389            Some(p) => p,
390            None => {
391                eprintln!("skipping render_scene test: no GPU adapter");
392                return;
393            }
394        };
395
396        assert_eq!(
397            &png[..8],
398            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
399            "expected PNG magic bytes"
400        );
401        eprintln!("rendered scene with faces: {} bytes", png.len());
402    }
403
404    /// Test RenderScene contract with mixed content (nodes, edges, faces)
405    #[cfg(not(target_arch = "wasm32"))]
406    #[test]
407    fn render_scene_mixed() {
408        let mut scene = RenderScene::new();
409        scene.set_background("#101820");
410
411        // Add a face
412        scene.add_face(SceneFace {
413            vertices: vec![
414                ScenePoint {
415                    x: 0.5,
416                    y: 0.2,
417                    z: 0.0,
418                },
419                ScenePoint {
420                    x: 0.2,
421                    y: 0.8,
422                    z: 0.0,
423                },
424                ScenePoint {
425                    x: 0.8,
426                    y: 0.8,
427                    z: 0.0,
428                },
429            ],
430            color: "#3b82f6".to_string(),
431            alpha: 0.5,
432        });
433
434        // Add edges
435        scene.add_edge(SceneEdge {
436            from: ScenePoint {
437                x: 0.2,
438                y: 0.2,
439                z: 0.0,
440            },
441            to: ScenePoint {
442                x: 0.8,
443                y: 0.2,
444                z: 0.0,
445            },
446            color: "#ffffff".to_string(),
447            width: 1.0,
448            alpha: 1.0,
449        });
450
451        // Add nodes
452        scene.add_node(SceneNode {
453            position: ScenePoint {
454                x: 0.5,
455                y: 0.5,
456                z: 0.0,
457            },
458            color: "#ef4444".to_string(),
459            radius: 8.0,
460            alpha: 1.0,
461            ..SceneNode::default()
462        });
463
464        let png = match render_scene_png(&scene, 96, 96) {
465            Some(p) => p,
466            None => {
467                eprintln!("skipping render_scene test: no GPU adapter");
468                return;
469            }
470        };
471
472        assert_eq!(
473            &png[..8],
474            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
475            "expected PNG magic bytes"
476        );
477        assert!(png.len() > 100, "PNG should be non-trivial");
478        eprintln!("rendered mixed scene: {} bytes", png.len());
479    }
480
481    /// Test RenderScene data URI output
482    #[cfg(not(target_arch = "wasm32"))]
483    #[test]
484    fn render_scene_data_uri_is_well_formed() {
485        let scene = RenderScene::new();
486        let uri = match render_scene_data_uri(&scene, 64, 64) {
487            Some(u) => u,
488            None => {
489                eprintln!("skipping data-uri test: no GPU adapter");
490                return;
491            }
492        };
493        assert!(
494            uri.starts_with("data:image/png;base64,"),
495            "expected PNG data-URI, got: {}",
496            &uri[..uri.len().min(40)]
497        );
498        assert!(uri.len() > 200, "data-URI should carry real image data");
499        eprintln!("scene data-URI: {} chars", uri.len());
500    }
501}