Skip to main content

ferroui_render3d/
lib.rs

1//! The renderer of FerroUI's 3D scenes (#608, `docs/porting/media3d.md`): what every backend
2//! shares to draw the [`Scene3DSnapshot`](ferroui_base::rendering::scene3d::Scene3DSnapshot) of a
3//! `Viewport3D`.
4//!
5//! - [`cpu`]: the CPU reference rasterizer, deterministic and in safe Rust: the reference of the
6//!   comparison tests, the renderer of the surfaces without a GPU (Skia raster, headless, the CPU
7//!   mode of Vello) and, until a backend has a GPU executor, the counted last resort on its GPU
8//!   surfaces ([`report_scene_drawn_on_cpu`]).
9//! - [`uniforms`]: the constants of a render (the camera, the lights, the matrices and colours of
10//!   each draw) as `#[repr(C)]`, std140-compatible structures, the one layout the CPU reference and
11//!   the shaders of the GPU executors (step D4) share.
12//! - [`lighting`]: the lighting of WPF's lights and materials per pixel, ported from ProGPU's
13//!   `ComputeWpfLighting`.
14//! - [`output_cache`]: the output of a scene kept while the scene, the size and the scale are
15//!   unchanged.
16//! - [`shader`]: `scene3d.wgsl`, the one shader of the GPU executors, restricted to what WebGL2
17//!   and OpenGL ES 3.0 run.
18//! - `wgpu_executor` (feature `wgpu`): the executor of the GPU modes of the Vello backend, which
19//!   draws a scene with wgpu into a texture of the device (step D4).
20//!
21//! The crate depends on the base library and std only, and on wgpu with its feature `wgpu`; its
22//! other GPU executors come with their steps (D5: Metal, D8: GL, D9: Vulkan) as features.
23
24#![forbid(unsafe_code)]
25
26pub mod cpu;
27pub mod lighting;
28mod math;
29pub mod output_cache;
30pub mod shader;
31pub mod uniforms;
32#[cfg(feature = "wgpu")]
33pub mod wgpu_executor;
34
35#[cfg(test)]
36mod test_scenes;
37
38pub use cpu::{CpuRasterizer, CpuRenderOptions, Scene3DImage};
39pub use output_cache::Scene3DOutputCache;
40
41use ferroui_base::logging::{LogArea, LogEventLevel, Logger};
42use ferroui_base::{PixelSize, Rect};
43use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
44
45/// The scenes drawn by the CPU reference on a GPU surface.
46static SCENES_DRAWN_ON_CPU: AtomicU64 = AtomicU64::new(0);
47static SCENES_DRAWN_ON_CPU_REPORTED: AtomicBool = AtomicBool::new(false);
48/// The lights left out of renders, past [`uniforms::MAX_LIGHTS`].
49static LIGHTS_LEFT_OUT: AtomicU64 = AtomicU64::new(0);
50static LIGHTS_LEFT_OUT_REPORTED: AtomicBool = AtomicBool::new(false);
51/// The layers drawn with their colour because their brush cannot be sampled yet.
52static UNSAMPLED_BRUSHES: AtomicU64 = AtomicU64::new(0);
53static UNSAMPLED_BRUSHES_REPORTED: AtomicBool = AtomicBool::new(false);
54
55/// How many times a scene was drawn by the CPU reference on a GPU surface since the process
56/// started: the gap of the backends without a GPU executor (`docs/porting/gpu-rendering.md`), which
57/// the GPU executors of steps D4 and later close. A surface without a GPU (Skia raster, the CPU
58/// mode of Vello) draws the CPU reference by definition and is not counted.
59pub fn scenes_drawn_on_cpu() -> u64 {
60    SCENES_DRAWN_ON_CPU.load(Ordering::Relaxed)
61}
62
63/// Counts a scene drawn by the CPU reference on a GPU surface of `backend` (a name for the
64/// log, such as "Skia (GPU)"), and reports the first one in the log (area `Visual`, level
65/// warning).
66pub fn report_scene_drawn_on_cpu(backend: &str) {
67    SCENES_DRAWN_ON_CPU.fetch_add(1, Ordering::Relaxed);
68    if SCENES_DRAWN_ON_CPU_REPORTED.swap(true, Ordering::Relaxed) {
69        return;
70    }
71    if let Some(logger) = Logger::try_get(LogEventLevel::Warning, LogArea::VISUAL) {
72        logger.log(
73            None,
74            &format!(
75                "A 3D scene (Viewport3D) is drawn by the CPU reference on a GPU surface of {backend}: the backend has no \
76                 GPU executor for 3D scenes there yet, or its executor failed (docs/porting/media3d.md, \
77                 docs/porting/gpu-rendering.md)."
78            ),
79        );
80    }
81}
82
83/// How many lights were left out of renders since the process started: a render takes the
84/// first [`uniforms::MAX_LIGHTS`] lights of a scene in tree order (`docs/porting/media3d.md`,
85/// section 6.1).
86pub fn lights_left_out() -> u64 {
87    LIGHTS_LEFT_OUT.load(Ordering::Relaxed)
88}
89
90pub(crate) fn note_lights_left_out(count: usize) {
91    LIGHTS_LEFT_OUT.fetch_add(count as u64, Ordering::Relaxed);
92    if LIGHTS_LEFT_OUT_REPORTED.swap(true, Ordering::Relaxed) {
93        return;
94    }
95    if let Some(logger) = Logger::try_get(LogEventLevel::Warning, LogArea::VISUAL) {
96        logger.log(
97            None,
98            "A 3D scene has more than 16 lights: the lights after the 16th in tree order are left out \
99             (docs/porting/media3d.md, section 6.1).",
100        );
101    }
102}
103
104/// How many material layers were drawn with their `Color` alone because the renderer cannot
105/// sample their brush yet (a gradient, an image, a visual or drawing brush: step D6 of the port),
106/// since the process started.
107pub fn layers_with_unsampled_brushes() -> u64 {
108    UNSAMPLED_BRUSHES.load(Ordering::Relaxed)
109}
110
111pub(crate) fn note_unsampled_brush() {
112    UNSAMPLED_BRUSHES.fetch_add(1, Ordering::Relaxed);
113    if UNSAMPLED_BRUSHES_REPORTED.swap(true, Ordering::Relaxed) {
114        return;
115    }
116    if let Some(logger) = Logger::try_get(LogEventLevel::Warning, LogArea::VISUAL) {
117        logger.log(
118            None,
119            "A material of a 3D scene paints with a brush the 3D renderer cannot sample yet (only solid colour brushes \
120             are drawn before step D6): the layer is drawn with its Color (docs/porting/media3d.md).",
121        );
122    }
123}
124
125/// The size in device pixels of the image of a viewport drawn over `bounds` (in the coordinates of
126/// a drawing context) whose transform to the device maps the unit x axis to `x_axis` and the
127/// unit y axis to `y_axis`, and the scale (device pixels per unit, the larger of the two axes):
128/// the bounds at the resolution of the device, also under a rotation or a skew
129/// (`docs/porting/media3d.md`, section 3.6). The perspective of a 2D transform is not taken into
130/// account. Each side is at least one pixel and at most [`cpu::MAX_SIDE`].
131pub fn scene_pixel_size(bounds: Rect, x_axis: (f64, f64), y_axis: (f64, f64)) -> (PixelSize, f64) {
132    let x_scale = x_axis.0.hypot(x_axis.1);
133    let y_scale = y_axis.0.hypot(y_axis.1);
134    let side = |length: f64| {
135        if length.is_finite() {
136            // A tolerance below a pixel, so that 100 units at a scale of 1.5 are 150 pixels.
137            (length - 1e-6).ceil().clamp(1.0, f64::from(cpu::MAX_SIDE)) as i32
138        } else {
139            1
140        }
141    };
142    let size = PixelSize::new(side(bounds.width * x_scale), side(bounds.height * y_scale));
143    let scale = x_scale.max(y_scale);
144    (size, if scale.is_finite() && scale > 0.0 { scale } else { 1.0 })
145}