dream_soft_render/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5//! A CPU rasterizer that turns 2D triangles into RGBA8 bytes, and does it the same way every
6//! time.
7//!
8//! There is no GPU here, no window, no swapchain, and no driver to have opinions about your
9//! blend state. You hand `dream-soft-render` rectangles, textured rectangles, and triangle
10//! meshes; it writes premultiplied pixels into a buffer you own. What happens to the buffer
11//! afterwards (a Linux framebuffer, a PNG, a golden-test hash) is your business.
12//!
13//! It exists because egui on a handheld with no usable GPU still has to draw something, and
14//! the CPU in those handhelds is a small ARM core that notices every wasted instruction. The
15//! hot paths recognize what they are drawing (solid rectangles, glyph quads, triangle fans)
16//! instead of treating everything as anonymous triangles, and the `AArch64` NEON paths are
17//! held byte-for-byte to the portable code by tests.
18//!
19//! # Drawing a Frame
20//!
21//! ```
22//! use dream_soft_render::{ClipRect, Color, Mesh, Rect, SoftwareRenderer, Vertex};
23//!
24//! # fn main() -> Result<(), dream_soft_render::Error> {
25//! let mut renderer = SoftwareRenderer::default();
26//! let checkerboard = renderer.create_texture(2, 2, &[
27//! 255, 255, 255, 255, 0, 0, 0, 255,
28//! 0, 0, 0, 255, 255, 255, 255, 255,
29//! ])?;
30//!
31//! let mut frame = renderer.begin_frame(64, 48)?;
32//! frame.clear(Color::from_rgb(17, 20, 28));
33//! frame.fill_rect(
34//! Rect::from_min_size([4.0, 4.0], [24.0, 12.0]),
35//! Color::from_rgba_unmultiplied(80, 160, 255, 192),
36//! ClipRect::ALL,
37//! )?;
38//! frame.textured_rect(
39//! Rect::from_min_size([32.0, 4.0], [16.0, 16.0]),
40//! Rect::FULL_UV,
41//! checkerboard,
42//! Color::WHITE,
43//! ClipRect::ALL,
44//! )?;
45//!
46//! let warning = Color::from_rgb(220, 40, 40);
47//! frame.mesh(
48//! Mesh {
49//! vertices: &[
50//! Vertex::new([8.0, 40.0], [0.0, 0.0], warning),
51//! Vertex::new([24.0, 24.0], [0.0, 0.0], warning),
52//! Vertex::new([40.0, 40.0], [0.0, 0.0], warning),
53//! ],
54//! indices: &[0, 1, 2],
55//! texture: None,
56//! },
57//! ClipRect::ALL,
58//! )?;
59//!
60//! let rgba = &frame.surface().pixels; // 64 * 48 * 4 bytes, top row first
61//! # assert_eq!(rgba.len(), 64 * 48 * 4);
62//! # Ok(())
63//! # }
64//! ```
65//!
66//! Draw calls rasterize immediately, in the order you make them. There is no command list to
67//! flush and no deferred state that can disagree with what you asked for.
68//!
69//! egui applications do not build meshes by hand. With the `egui` feature they call
70//! `SoftwareRenderer::render_egui` with a UI closure; see the `egui_adapter` module. Both paths
71//! write the same surface, share the same textures, and produce identical pixels for identical
72//! geometry.
73//!
74//! # Features
75//!
76//! - `egui` (off by default): the egui adapter. Without it the crate has no egui dependency at
77//! all; the rasterizer and the drawing API above never needed one.
78//!
79//! # The Rules
80//!
81//! Every drawing path follows these, egui frames included. If the code and this list ever
82//! disagree, the code is wrong.
83//!
84//! - **Surface.** Row-major RGBA8, top row first, exactly `width * height * 4` bytes, at most
85//! [`MAX_SURFACE_PIXELS`] pixels and 65535 on a side. It is an opaque framebuffer: every blended pixel is written
86//! with alpha 255, so the alpha channel does not carry coverage. A new or resized surface
87//! starts transparent black. Otherwise a frame draws over whatever the last one left, until
88//! you call [`Frame::clear`]. Nothing clears behind your back.
89//! - **Coordinates.** Surface pixels. Origin at the top-left corner, x to the right, y down.
90//! Pixel `(x, y)` covers `[x, x + 1) x [y, y + 1)` and is sampled at its center,
91//! `(x + 0.5, y + 0.5)`.
92//! - **Triangle coverage.** A triangle covers the pixels whose centers it contains. A center
93//! exactly on an edge goes to one side by a fixed tie-break, so two triangles sharing that
94//! edge never both blend the pixel.
95//! - **Rectangle coverage.** A rectangle covers the pixels whose centers satisfy
96//! `min < center <= max` on both axes. `max <= min` on either axis covers nothing.
97//! - **Clipping.** [`ClipRect`] is integer pixels, half-open, and clamped to the surface.
98//! - **Color.** [`Color`] is premultiplied RGBA8, and so are texture pixels. Vertex colors
99//! interpolate linearly across a triangle and multiply the sampled texel per channel as
100//! `round(a * b / 255)`.
101//! - **Blending.** Premultiplied source-over, onto an opaque destination:
102//! `dst = src + round(dst * (255 - src_alpha) / 255)`, saturating, alpha written as 255.
103//! Fully transparent source pixels leave the destination alone.
104//! - **Sampling.** Nearest texel. UV `(0, 0)` is the texture's top-left and `(1, 1)` its
105//! bottom-right; coordinates clamp to that range, and the texel on each axis is
106//! `round(uv * (size - 1))`. Untextured meshes sample opaque white.
107//! - **Determinism.** Output is a function of the draw calls. Same calls, same bytes, on every
108//! platform, with or without NEON.
109//!
110//! # Limits and Failures
111//!
112//! A surface holds at most [`MAX_SURFACE_PIXELS`] (1280x720) and one renderer's textures at
113//! most [`MAX_TEXTURE_BYTES`] (8 MiB). Both limits exist to catch accidents on small machines,
114//! not because the rasterizer falls over past them. A surface side is also at most 65535
115//! pixels and a texture side at most 65536 texels, and those limits are the rasterizer's: its
116//! pixel and texel coordinates stop there.
117//!
118//! Malformed input is an [`Error`]: a mesh index past the end of its vertices, pixel data of
119//! the wrong length, a NaN rectangle, a freed texture. The renderer does not clip bad input
120//! into something drawable and carry on. Code that feeds it garbage has a bug, and a quietly
121//! wrong frame would only hide where.
122
123mod color;
124#[cfg(feature = "egui")]
125#[cfg_attr(docsrs, doc(cfg(feature = "egui")))]
126pub mod egui_adapter;
127mod error;
128mod geometry;
129mod raster;
130#[cfg(feature = "egui")]
131mod render_benchmark;
132mod renderer;
133mod surface;
134mod texture;
135
136pub use color::Color;
137pub use error::{Error, VertexField};
138pub use geometry::{ClipRect, Rect, Vertex};
139pub use renderer::{Frame, Mesh, SoftwareRenderer};
140pub use surface::{MAX_SURFACE_PIXELS, SoftwareSurface};
141pub use texture::{MAX_TEXTURE_BYTES, TextureId};
142
143// Compiles the README's examples so they cannot drift from the API. Some use the egui adapter.
144#[cfg(all(doctest, feature = "egui"))]
145#[doc = include_str!("../README.md")]
146struct ReadmeDoctests;