feat(native-playground): add GPU 2D transforms, procedural dot-grid, and Edgeless Note/Frame/Text canvas

Add GPU paint transform and local content-mask stacks across Metal, wgpu, and WebGL2 shaders, quarter-octave glyph zoom bucketing, and procedural single-draw-call dot-grid backgrounds in crates/ui (plus TextSystem::line_gap).

Implement the Edgeless spatial canvas (camera, dot-grid, Surface-parented Frame and EdgelessText, Note scale/collapse/style parity, cached per-note BlockFlow with zero pan/zoom relayouts, and zoom bar), register edgeless_1k_pan_zoom_blocks_relayout in perf/compare-n3.mjs, and add cross-backend headless regression tests and Chromium WebGL2 smoke assertions.
This commit is contained in:
DarkSky committed 2026-11-23 13:58:04 +09:00
1 parent 5b82831fd8
commit ba55dd7058
26 files changed
+3110 -172

No files matched your search

+8 -2
View File
@@ -48,7 +48,7 @@ This document records the active engineering invariants enforced in CI today alo
- **Pointer and keys**: A press on the page dismisses the slash menu, the link field (unapplied) and a block drag, then goes to the editor; pointer moves and the release are handled at the window root, so a drag continues outside the page. The formatting toolbar waits while the button of a plain press is held and opens on release; a double or triple click opens it at once. Keys reach one handler, `editor_key_down`, which first offers them to the overlays: an open link field takes every key but the ones that type text, the slash menu takes `Up`, `Down`, `Tab`, `Shift+Tab`, `Enter` and `Escape` (`Tab` steps through the items and never indents the block; `Enter` without a match closes the menu and does not split the block), and everything else is the editor's. A pointer on an open popover does not change which block is hovered under it.
- **Edits are single undo steps**: Every overlay edit goes through the editor's `PageDocSession`, stores the selection for undo, and is published like any editor commit. Marks use the editor's `format_mark`; a link and an alignment run in one `structural_edit` across the selected paragraph and list blocks; a to-do box, a collapse and a drop are isolated between `stop_capturing` calls, the drop through `reparent_block` so numbered runs are renumbered. A slash command is one `structural_edit`, following BlockSuite's `updateBlockType` and `appendDivider`: it removes the typed `/filter`, then a paragraph type, a list type or code converts the block with whatever text it has left (in place within a flavour, as a fresh block across flavours; a block without text of its own gets the new block below instead), and a divider goes right below the block, followed by an empty paragraph to type in when the block was the last of its parent. The caret stays where the command was typed, or moves to the block after a divider. One undo restores the typed command.
- **Positioner**: `place_popover` is pure and works in screen space below the top bar: `Above` (formatting toolbar, centered on the selection) and `BelowStart` (slash menu, at the caret) flip to the other side when the preferred one would come closer than the edge margin to the top bar or the window bottom, and clamp horizontally inside the margins. Results are on the pixel grid.
- **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. A popover at zero opacity is not mounted; one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Nothing here loops per frame.
- **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. An opening popover mounts on its first frame at zero opacity so its hitboxes are live immediately; a closed popover at zero opacity is unmounted, and one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Nothing here loops per frame.
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 32 px, and the menu has no border, only its shadow.
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's grabber: a 4 × 12 px bar while the pointer is on the block's row, and two columns of three dots on a 14 px pill once the pointer is on the handle or drags it. A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
@@ -65,9 +65,15 @@ This document records the active engineering invariants enforced in CI today alo
- **`RichParagraph`**: The single rich-text engine: `BlockFlow` lays out and paints paragraph and list text with it (`LaidOutRichParagraph::paint_at`, the same path `RichParagraphElement` uses), and reads remote carets and selections from its geometry. Cursor and selection geometry uses source UTF-16 positions and extended-grapheme boundaries. Each inline reference occupies one document unit regardless of its resolved label width, wraps as one inline object (the words before it stay on their line), and its prefix is the generated `LinkedPageIcon` SVG painted at the `DecorationKind::PageGlyph` bounds. `color` and `background` marks resolve through the theme (`DecorationKind::Highlight` behind the glyphs), and bold follows CSS `bolder`. Shaped lines supply wrapping, painting, hit targets, and both caret affinities at a soft wrap.
- **Inline style parity**: Code boxes and links follow the light/dark theme tokens and browser measurements in `tokens/style-oracle.json`; the code box metrics are constants that a test keeps equal to the oracle, so the oracle JSON is never embedded in the shipped binary. Plain and rich renders of one document can be reproduced with `bs-harness render-rich-sample --out-plain plain.png --out-rich rich.png`.
### Edgeless rendering and GPU transforms
- **End-to-end GPU transforms and local clip masks**: `Window::with_paint_transformation` composes 2D affine transforms (`TransformationMatrix`) on a stack and `Window::with_local_paint_mask` intersects pre-transform local clip rects (`ContentMask<Pixels>`). All GPU primitives (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, and `PathRasterizationVertex`) are 16-byte aligned (`size_of % 16 == 0`, verified by compile-time assertions) for WebGL2 `RGBA32U` instance-texture decoding. Both Metal (`shaders.metal`) and wgpu/WebGL2 (`shaders.wgsl`, `shaders_webgl.wgsl`, `shaders_subpixel.wgsl`) transform vertices on the GPU, evaluate SDFs in local space scaled by `transform_scale` for 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-space `content_mask` and pre-transform `local_content_mask`.
- **Quarter-octave glyph zoom bucketing**: Under non-unit paint scales, `Window::paint_glyph` and `Window::paint_glyph_in_run` quantize rasterization scale to quarter-octave buckets (`2^(round(4*log2(s))/4)` clamped to `[0.25, 8.0]`), rasterizing atlas tiles at `font_size * bucket` while scaling local quad bounds by `1 / bucket` so cached `1.0x` `RichParagraph` / `BlockFlow` layouts render crisply at `0.1x..6.0x` without re-shaping or relayouting during pan/zoom.
- **Procedural dot-grid (`BackgroundTag::DotGrid = 4`)**: Renders the Edgeless background grid in a single fullscreen `Quad` draw call with 1-device-pixel anti-aliased dots anchored to world `(0, 0)` and spacing matching BlockSuite's `getBgGridGap(zoom)`.
- **Spatial camera & canvas**: `edgeless_camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds. `edgeless_canvas.rs` renders `affine:frame`, `affine:note` (each backed by a cached `BlockFlow::layout_nodes` with zero relayout during pan/zoom), and rotated/scaled `affine:edgeless-text` under `edgeless.viewport`, with bottom-right screen-space zoom controls (`chrome.edgeless_zoom`). `bs-harness render --mode edgeless [--zoom <f32>] [--pan <x>,<y>]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`.
## Planned Contracts (upcoming crates & features)
- **Whiteboard rendering**: World-space content transforms/masks implemented end-to-end in the GPU shaders (today `BlockFlow` applies the world-to-screen mapping per element on the CPU), and the Edgeless whiteboard surface (Edgeless mode shows a placeholder card).
- **Whiteboard surface elements & interaction**: Surface shapes, connectors, brushes, mindmaps, and pointer selection/drag editing on top of the Edgeless spatial canvas.
## Build & verification commands
@@ -66,6 +66,8 @@ struct BenchmarksV1 {
layout_single_keystroke_blocks_relayout: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
edgeless_1k_pan_zoom_frame_ms: Option<TimingStat>,
#[serde(skip_serializing_if = "Option::is_none")]
edgeless_1k_pan_zoom_blocks_relayout: Option<u64>,
headless_frame_render_ms: TimingStat,
}
@@ -555,9 +557,46 @@ fn run_audit_states() -> Result<()> {
}
audited += 1;
}
// Audit Edgeless default + zoomed states (0.5x, 2.0x) in both themes and widths.
for (label, zoom_opt) in [
("edgeless_default", None),
("edgeless_zoom_0.5x", Some(0.5_f32)),
("edgeless_zoom_2.0x", Some(2.0_f32)),
] {
let context = format!("{label} {width}x{height} {}", theme.as_str());
let session = start_headless_session(
width,
height,
PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
)?;
let _ = session.frame()?;
if let Some(z) = zoom_opt {
session.update(|v, _, cx| v.set_edgeless_zoom(z, cx))?;
}
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
);
anyhow::ensure!(
snapshot.elements.contains_key("edgeless.viewport"),
"edgeless.viewport missing in {context}"
);
anyhow::ensure!(
snapshot.elements.contains_key("chrome.edgeless_zoom"),
"chrome.edgeless_zoom missing in {context}"
);
audited += 1;
}
}
}
println!("audit-states passed: 0 violations across {audited} overlay states");
println!("audit-states passed: 0 violations across {audited} states");
Ok(())
}
@@ -567,6 +606,8 @@ fn render_headless(
out_png: PathBuf,
out_snapshot: PathBuf,
click_edgeless: bool,
zoom: Option<f32>,
pan: Option<(f32, f32)>,
state: OverlayState,
options: PlaygroundOptions,
) -> Result<()> {
@@ -598,6 +639,16 @@ fn render_headless(
session.headless_win.request_frame();
}
if zoom.is_some() || pan.is_some() {
session.update(|v, _, cx| match (pan, zoom) {
(Some((px_w, py_w)), Some(z)) => v.set_edgeless_camera(px_w, py_w, z, cx),
(Some((px_w, py_w)), None) => v.set_edgeless_pan(px_w, py_w, cx),
(None, Some(z)) => v.set_edgeless_zoom(z, cx),
(None, None) => {}
})?;
session.headless_win.request_frame();
}
let (image, snapshot, glyph_count) = session.app.update(|cx| {
session.window_handle.update(cx, |_, window, _| {
let snapshot = window.frame_snapshot().clone();
@@ -1432,6 +1483,171 @@ fn bench_page(session: &HeadlessSession) -> Result<(TimingStat, TimingStat, u64)
Ok((cold, edits, work))
}
fn bench_edgeless_1k() -> Result<(TimingStat, u64)> {
use blocksuite_playground_doc::{
client_id_from_seed,
schema::{BlockSpec, ParagraphType},
};
use playground::room_client::DocState;
let session = start_headless_session(
1280,
800,
PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
)?;
// Build a 1,000-block spatial Edgeless scene: 250 Notes (each with 3 paragraphs = 1,000
// blocks), 20 Frames, and 30 rotated EdgelessTexts spread across a 2D grid.
let mut doc = DocState::new("bench-edgeless-1k", client_id_from_seed(0x4d35))?;
doc.workspace.initialize_meta()?;
doc.workspace.create_page(
playground::HOME_PAGE_ID,
"Edgeless 1K Bench",
1_700_000_000_000,
)?;
let page = doc.workspace.ensure_page(playground::HOME_PAGE_ID)?;
let mut now_ms = 1_000_u64;
let mut tick = || {
now_ms += 1;
now_ms
};
page.add_block(
"e1k-page",
BlockSpec::Page {
title: "Edgeless 1K Bench".to_string(),
},
None,
None,
tick(),
)?;
page.add_block(
"e1k-surface",
BlockSpec::Surface,
Some("e1k-page"),
None,
tick(),
)?;
for f in 0..20 {
let col = (f % 5) as f32;
let row = (f / 5) as f32;
page.add_block(
&format!("e1k-frame-{f}"),
BlockSpec::Frame {
title: format!("Frame {f}"),
xywh: Some(format!(
"[{},{},1800,1200]",
col * 2000.0 - 40.0,
row * 1400.0 - 40.0
)),
presentation_index: Some(format!("a{f:02}")),
},
Some("e1k-page"),
None,
tick(),
)?;
}
for n in 0..250 {
let col = (n % 25) as f32;
let row = (n / 25) as f32;
let note_id = format!("e1k-note-{n}");
page.add_block(
&note_id,
BlockSpec::Note {
xywh: Some(format!("[{},{},340,180]", col * 400.0, row * 240.0)),
},
Some("e1k-page"),
None,
tick(),
)?;
for p in 0..3 {
page.add_block(
&format!("e1k-note-{n}-p{p}"),
BlockSpec::Paragraph {
paragraph_type: if p == 0 {
ParagraphType::H4
} else {
ParagraphType::Text
},
text: format!("Note {n} paragraph {p}: GPU transform spatial test."),
},
Some(&note_id),
None,
tick(),
)?;
}
}
for t in 0..30 {
let et_id = format!("e1k-text-{t}");
page.add_block(
&et_id,
BlockSpec::EdgelessText {
xywh: Some(format!(
"[{},{},260,64]",
(t % 10) as f32 * 480.0,
2600.0 + (t / 10) as f32 * 140.0
)),
},
Some("e1k-page"),
None,
tick(),
)?;
page.set_block_prop(
&et_id,
"prop:rotate",
y_octo::SessionValue::Any(y_octo::Any::Float64((((t % 7) as f64 - 3.0) * 5.0).into())),
tick(),
)?;
page.add_block(
&format!("e1k-text-{t}-p"),
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: format!("Rotated label #{t}"),
},
Some(&et_id),
None,
tick(),
)?;
}
session.update(|v, _, cx| v.set_document(doc, cx))?;
// Warmup frame: lays out and caches all Notes and EdgelessTexts once.
session.headless_win.request_frame();
let _ = session.image()?;
// 30-step pan + 0.25x..4.0x zoom sweep: must incur ZERO block relayouts.
let mut times = Vec::with_capacity(30);
let mut relayout_count = 0_u64;
for step in 0..30 {
let frac = step as f32 / 29.0;
let zoom = 0.25 * (16.0_f32).powf(frac); // 0.25x -> 4.0x
let pan_x = -200.0 + frac * 1800.0;
let pan_y = -100.0 + (frac * std::f32::consts::TAU).sin() * 400.0 + 400.0;
let t = ui::clock_now();
session.update(|v, w, cx| {
v.set_edgeless_camera(pan_x, pan_y, zoom, cx);
w.refresh();
})?;
session.headless_win.request_frame();
let _ = session.image()?;
times.push(t.elapsed().as_secs_f64() * 1000.0);
relayout_count += session.update(|v, _, _| v.edgeless_last_frame_relayouts())?;
}
anyhow::ensure!(
relayout_count == 0,
"edgeless 1k pan/zoom sweep triggered {relayout_count} block relayouts (expected 0)"
);
let stat = timing_stat(times);
println!(
"edgeless 1k pan/zoom (30 steps, 0.25x..4.0x): median/p95 {:.3}/{:.3} ms, {} blocks relayout",
stat.median, stat.p95, relayout_count
);
Ok((stat, relayout_count))
}
fn run_bench(
out_json: PathBuf,
explicit_commit: Option<String>,
@@ -1476,6 +1692,7 @@ fn run_bench(
.unwrap_or(0);
let (cold, edits, work) = bench_page(&session)?;
let (edgeless_ms, edgeless_relayouts) = bench_edgeless_1k()?;
let metrics = PerfMetricsV1 {
schema_version: 1,
commit,
@@ -1492,7 +1709,8 @@ fn run_bench(
layout_10k_blocks_cold_ms: Some(cold),
layout_single_keystroke_ms: Some(edits),
layout_single_keystroke_blocks_relayout: Some(work),
edgeless_1k_pan_zoom_frame_ms: None,
edgeless_1k_pan_zoom_frame_ms: Some(edgeless_ms),
edgeless_1k_pan_zoom_blocks_relayout: Some(edgeless_relayouts),
headless_frame_render_ms: timing_stat(frame_times_ms),
},
};
@@ -2299,6 +2517,8 @@ fn main() -> Result<()> {
let mut width = 1280_u32;
let mut height = 800_u32;
let mut click_edgeless = false;
let mut zoom: Option<f32> = None;
let mut pan: Option<(f32, f32)> = None;
let mut state = OverlayState::Default;
let mut options = PlaygroundOptions::default();
while let Some(arg) = args.next() {
@@ -2313,6 +2533,16 @@ fn main() -> Result<()> {
height = args.next().context("--height requires value")?.parse()?
}
"--click-edgeless" => click_edgeless = true,
"--zoom" => {
zoom = Some(args.next().context("--zoom requires float")?.parse()?);
}
"--pan" => {
let raw = args.next().context("--pan requires <x>,<y>")?;
let (xs, ys) = raw
.split_once(',')
.context("--pan must be formatted as <x>,<y>")?;
pan = Some((xs.trim().parse()?, ys.trim().parse()?));
}
"--state" => {
let value = args.next().context("--state requires an overlay state")?;
state = OverlayState::parse(&value).with_context(|| {
@@ -2340,6 +2570,8 @@ fn main() -> Result<()> {
out_png,
out_snapshot,
click_edgeless,
zoom,
pan,
state,
options,
)
@@ -406,7 +406,7 @@ impl InlineLayout {
spans
}
fn paint(&self, origin: Point<Pixels>, window: &mut Window, cx: &mut App) {
pub(crate) fn paint(&self, origin: Point<Pixels>, window: &mut Window, cx: &mut App) {
for piece in &self.pieces {
let piece_origin = point(
origin.x + px(piece.x),
@@ -958,7 +958,13 @@ impl BlockBody {
})
}
fn paint(&self, origin: Point<Pixels>, state: BlockPaint, window: &mut Window, cx: &mut App) {
pub(crate) fn paint(
&self,
origin: Point<Pixels>,
state: BlockPaint,
window: &mut Window,
cx: &mut App,
) {
for prim in &self.prims {
match prim {
Prim::CodeLine { x, y, layout, clip } => {
@@ -966,10 +972,10 @@ impl BlockBody {
.code_scroll
.map_or(0.0, |code| state.code_scroll_x.clamp(0.0, code.max_x));
let text_origin = point(origin.x + px(*x - scroll), origin.y + px(*y));
window.with_content_mask(
Some(ui::ContentMask {
window.with_local_paint_mask(
ui::ContentMask {
bounds: clip.bounds(origin),
}),
},
|window| layout.paint(text_origin, window, cx),
);
}
@@ -1001,10 +1007,10 @@ impl BlockBody {
Prim::Text { x, y, layout, clip } => {
let text_origin = point(origin.x + px(*x), origin.y + px(*y));
match clip {
Some(clip) => window.with_content_mask(
Some(ui::ContentMask {
Some(clip) => window.with_local_paint_mask(
ui::ContentMask {
bounds: clip.bounds(origin),
}),
},
|window| layout.paint(text_origin, window, cx),
),
None => layout.paint(text_origin, window, cx),
@@ -1253,6 +1259,37 @@ impl BlockFlow {
stats: pass.stats,
}
}
/// Lay an arbitrary slice of block nodes out in local coordinates (no page title or bottom
/// padding), reusing cached block bodies across passes.
pub fn layout_nodes(
&mut self,
nodes: &[BlockNode],
input: &FlowInput<'_>,
window: &Window,
) -> FlowLayout {
let mut pass = FlowPass {
dirty: None,
input,
palette: input.theme.palette(),
window,
previous: std::mem::take(&mut self.bodies),
next: HashMap::new(),
blocks: Vec::new(),
stats: FlowStats::default(),
y: 0.0,
pending_margin: None,
};
pass.flow(nodes, 0.0, 0, BlockAlign::Left);
pass.y += pass.pending_margin.take().unwrap_or(0.0);
self.bodies = pass.next;
FlowLayout {
blocks: pass.blocks,
width: input.width,
height: pass.y,
stats: pass.stats,
}
}
}
fn heading_level(node: &BlockNode) -> Option<u8> {
@@ -0,0 +1,332 @@
//! Spatial camera, coordinate conversion, and BlockSuite dot-grid spacing for Edgeless mode.
use ui::{Pixels, Point, Size, TransformationMatrix, point, px};
/// Minimum allowed Edgeless zoom factor (10%).
pub const MIN_ZOOM: f32 = 0.1;
/// Maximum allowed Edgeless zoom factor (600%).
pub const MAX_ZOOM: f32 = 6.0;
/// Multiplicative step applied by zoom-in / zoom-out controls.
const ZOOM_STEP: f32 = 1.25;
/// Axis-aligned rectangle in Edgeless world coordinates.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WorldRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
impl WorldRect {
pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
Self { x, y, w, h }
}
pub fn right(self) -> f32 {
self.x + self.w
}
pub fn bottom(self) -> f32 {
self.y + self.h
}
pub fn center(self) -> (f32, f32) {
(self.x + self.w * 0.5, self.y + self.h * 0.5)
}
pub fn is_empty(self) -> bool {
self.w <= 0.0 || self.h <= 0.0
}
pub fn intersects(self, other: Self) -> bool {
self.x < other.right()
&& self.right() > other.x
&& self.y < other.bottom()
&& self.bottom() > other.y
}
pub fn union(self, other: Self) -> Self {
if self.is_empty() {
return other;
}
if other.is_empty() {
return self;
}
let min_x = self.x.min(other.x);
let min_y = self.y.min(other.y);
let max_x = self.right().max(other.right());
let max_y = self.bottom().max(other.bottom());
Self::new(min_x, min_y, max_x - min_x, max_y - min_y)
}
pub fn dilate(self, margin: f32) -> Self {
Self::new(
self.x - margin,
self.y - margin,
self.w + 2.0 * margin,
self.h + 2.0 * margin,
)
}
}
/// Parse a BlockSuite `"[x,y,w,h]"` string into a [`WorldRect`].
pub fn parse_xywh(xywh: &str) -> Option<WorldRect> {
let trimmed = xywh.trim();
let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
let mut parts = inner.split(',').map(|s| s.trim().parse::<f32>().ok());
let x = parts.next()??;
let y = parts.next()??;
let w = parts.next()??;
let h = parts.next()??;
if parts.next().is_some()
|| !x.is_finite()
|| !y.is_finite()
|| !w.is_finite()
|| !h.is_finite()
{
return None;
}
Some(WorldRect::new(x, y, w.max(0.0), h.max(0.0)))
}
/// World-to-screen camera for the infinite Edgeless canvas.
///
/// Mapping: `screen = viewport_origin + (world - pan) * zoom`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EdgelessCamera {
/// World X coordinate at the top-left of the viewport.
pub pan_x: f32,
/// World Y coordinate at the top-left of the viewport.
pub pan_y: f32,
/// Uniform zoom factor in `[MIN_ZOOM, MAX_ZOOM]`.
pub zoom: f32,
}
impl Default for EdgelessCamera {
fn default() -> Self {
Self {
pan_x: 0.0,
pan_y: 0.0,
zoom: 1.0,
}
}
}
impl EdgelessCamera {
pub fn new(pan_x: f32, pan_y: f32, zoom: f32) -> Self {
Self {
pan_x,
pan_y,
zoom: zoom.clamp(MIN_ZOOM, MAX_ZOOM),
}
}
/// Map a world-space point into window screen coordinates.
pub fn world_to_screen(
&self,
world: Point<Pixels>,
viewport_origin: Point<Pixels>,
) -> Point<Pixels> {
point(
px(f32::from(viewport_origin.x) + (f32::from(world.x) - self.pan_x) * self.zoom),
px(f32::from(viewport_origin.y) + (f32::from(world.y) - self.pan_y) * self.zoom),
)
}
/// Map a window screen-space point into world coordinates.
pub fn screen_to_world(
&self,
screen: Point<Pixels>,
viewport_origin: Point<Pixels>,
) -> Point<Pixels> {
let z = self.zoom.max(MIN_ZOOM);
point(
px((f32::from(screen.x) - f32::from(viewport_origin.x)) / z + self.pan_x),
px((f32::from(screen.y) - f32::from(viewport_origin.y)) / z + self.pan_y),
)
}
/// Build the 2D GPU transformation matrix mapping logical world pixels to logical screen pixels.
pub fn to_transformation_matrix(&self, viewport_origin: Point<Pixels>) -> TransformationMatrix {
TransformationMatrix {
rotation_scale: [[self.zoom, 0.0], [0.0, self.zoom]],
translation: [
f32::from(viewport_origin.x) - self.pan_x * self.zoom,
f32::from(viewport_origin.y) - self.pan_y * self.zoom,
],
}
}
/// Visible world-space rectangle covered by a viewport of `viewport_size`.
pub fn visible_world_bounds(&self, viewport_size: Size<Pixels>) -> WorldRect {
let z = self.zoom.max(MIN_ZOOM);
WorldRect::new(
self.pan_x,
self.pan_y,
f32::from(viewport_size.width) / z,
f32::from(viewport_size.height) / z,
)
}
/// Translate the camera by a screen-space delta (positive `dx`/`dy` drags content right/down).
pub fn pan_by_screen_delta(&mut self, dx: f32, dy: f32) {
let z = self.zoom.max(MIN_ZOOM);
self.pan_x -= dx / z;
self.pan_y -= dy / z;
}
/// Change zoom to `new_zoom` while keeping the world point under `anchor_screen` fixed.
pub fn zoom_at(
&mut self,
new_zoom: f32,
anchor_screen: Point<Pixels>,
viewport_origin: Point<Pixels>,
) {
let world_before = self.screen_to_world(anchor_screen, viewport_origin);
self.zoom = new_zoom.clamp(MIN_ZOOM, MAX_ZOOM);
self.pan_x = f32::from(world_before.x)
- (f32::from(anchor_screen.x) - f32::from(viewport_origin.x)) / self.zoom;
self.pan_y = f32::from(world_before.y)
- (f32::from(anchor_screen.y) - f32::from(viewport_origin.y)) / self.zoom;
}
/// Zoom in one step anchored at the viewport center.
pub fn zoom_in(&mut self, viewport_origin: Point<Pixels>, viewport_size: Size<Pixels>) {
let center = point(
px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5),
px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5),
);
self.zoom_at(self.zoom * ZOOM_STEP, center, viewport_origin);
}
/// Zoom out one step anchored at the viewport center.
pub fn zoom_out(&mut self, viewport_origin: Point<Pixels>, viewport_size: Size<Pixels>) {
let center = point(
px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5),
px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5),
);
self.zoom_at(self.zoom / ZOOM_STEP, center, viewport_origin);
}
/// Reset zoom to `1.0` anchored at the viewport center.
pub fn reset_zoom(&mut self, viewport_origin: Point<Pixels>, viewport_size: Size<Pixels>) {
let center = point(
px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5),
px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5),
);
self.zoom_at(1.0, center, viewport_origin);
}
/// Frame `world_bounds` inside `viewport_size` with `padding` screen pixels on all sides.
pub fn fit_to_bounds(
&mut self,
world_bounds: WorldRect,
viewport_size: Size<Pixels>,
padding: f32,
) {
let vw = f32::from(viewport_size.width).max(1.0);
let vh = f32::from(viewport_size.height).max(1.0);
if world_bounds.is_empty() {
self.zoom = 1.0;
self.pan_x = -vw * 0.5;
self.pan_y = -vh * 0.5;
return;
}
let avail_w = (vw - 2.0 * padding).max(1.0);
let avail_h = (vh - 2.0 * padding).max(1.0);
let fit_zoom = (avail_w / world_bounds.w)
.min(avail_h / world_bounds.h)
.min(1.0)
.clamp(MIN_ZOOM, MAX_ZOOM);
self.zoom = fit_zoom;
let (cx, cy) = world_bounds.center();
self.pan_x = cx - vw / (2.0 * self.zoom);
self.pan_y = cy - vh / (2.0 * self.zoom);
}
/// Screen-space phase offset `(phase_x, phase_y)` in `[0, gap)` centering each dot inside
/// its `gap × gap` tile and anchoring the dot-grid to world `(0, 0)` during panning.
pub fn dot_grid_phase(&self, gap: f32) -> (f32, f32) {
let gap = gap.max(1.0);
(
(-self.pan_x * self.zoom + gap * 0.5).rem_euclid(gap),
(-self.pan_y * self.zoom + gap * 0.5).rem_euclid(gap),
)
}
}
/// Exact BlockSuite dot-grid screen spacing (`getBgGridGap` in `get-bg-grip-gap.ts`).
pub fn bg_grid_gap(zoom: f32) -> f32 {
let step = if zoom < 0.5 {
2.0
} else {
1.0 / zoom.floor().max(1.0)
};
(20.0 * step * zoom).clamp(10.0, 50.0).round()
}
#[cfg(test)]
mod tests {
use super::*;
use ui::size;
#[test]
fn world_screen_roundtrip_and_matrix_match() {
let cam = EdgelessCamera::new(-120.0, 45.0, 1.75);
let origin = point(px(0.0), px(52.0));
let world = point(px(340.0), px(-80.0));
let screen = cam.world_to_screen(world, origin);
let back = cam.screen_to_world(screen, origin);
assert!((f32::from(back.x) - f32::from(world.x)).abs() < 1e-4);
assert!((f32::from(back.y) - f32::from(world.y)).abs() < 1e-4);
let mat = cam.to_transformation_matrix(origin);
let mapped = mat.apply(world);
assert!((f32::from(mapped.x) - f32::from(screen.x)).abs() < 1e-4);
assert!((f32::from(mapped.y) - f32::from(screen.y)).abs() < 1e-4);
}
#[test]
fn cursor_anchored_zoom_preserves_world_point() {
let mut cam = EdgelessCamera::new(100.0, 200.0, 1.0);
let origin = point(px(0.0), px(52.0));
let cursor = point(px(420.0), px(310.0));
let before = cam.screen_to_world(cursor, origin);
cam.zoom_at(2.5, cursor, origin);
let after = cam.screen_to_world(cursor, origin);
assert!((f32::from(before.x) - f32::from(after.x)).abs() < 1e-3);
assert!((f32::from(before.y) - f32::from(after.y)).abs() < 1e-3);
}
#[test]
fn bg_grid_gap_clamps_across_zoom_range() {
for zoom in [0.1, 0.25, 0.5, 1.0, 1.5, 2.0, 4.0, 6.0] {
let gap = bg_grid_gap(zoom);
assert!((10.0..=50.0).contains(&gap), "zoom={zoom} gap={gap}");
}
assert_eq!(bg_grid_gap(1.0), 20.0);
}
#[test]
fn fit_to_bounds_centers_content() {
let mut cam = EdgelessCamera::default();
let bounds = WorldRect::new(0.0, 0.0, 800.0, 600.0);
let viewport = size(px(1280.0), px(748.0));
cam.fit_to_bounds(bounds, viewport, 48.0);
assert!((cam.zoom - 1.0).abs() < 1e-4);
let center = cam.world_to_screen(point(px(400.0), px(300.0)), point(px(0.0), px(0.0)));
assert!((f32::from(center.x) - 640.0).abs() < 1e-3);
assert!((f32::from(center.y) - 374.0).abs() < 1e-3);
}
#[test]
fn parse_xywh_handles_valid_and_invalid() {
assert_eq!(
parse_xywh("[-40, 20.5, 800, 600]"),
Some(WorldRect::new(-40.0, 20.5, 800.0, 600.0))
);
assert_eq!(parse_xywh("[1,2,3]"), None);
assert_eq!(parse_xywh("bad"), None);
}
}
@@ -0,0 +1,898 @@
//! Spatial Edgeless canvas rendering: procedural dot-grid, `affine:frame`, `affine:note`,
//! `affine:edgeless-text`, cached per-note `BlockFlow` (zero relayout on pan/zoom), and
//! screen-space zoom controls (`chrome.edgeless_zoom`).
use std::{
collections::{BTreeMap, HashMap},
rc::Rc,
};
use blocksuite_playground_doc::read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot};
use serde_json::Value as JsonValue;
use ui::{
AnyElement, Background, BorderStyle, Bounds, ContentMask, Corners, Edges, Hsla, MouseButton,
Pixels, Point, ScaledPixels, SharedString, Size, TransformationMatrix, Window, canvas, div,
point, prelude::*, px, size,
};
use crate::{
block_flow::{
BlockFlow, BlockPaint, FlowInput, FlowLayout, ImageSlot, InlineAlign, InlineBaseline,
InlineStyle, layout_inline,
},
edgeless_camera::{EdgelessCamera, WorldRect, bg_grid_gap, parse_xywh},
theme::{FONT_SANS, Palette, PlaygroundTheme},
};
/// Snapshot id of the Edgeless spatial viewport under `root.canvas`.
pub const EDGELESS_VIEWPORT_ID: &str = "edgeless.viewport";
/// Inner padding of an `affine:note` card on the Edgeless canvas (world px).
pub const NOTE_CARD_PADDING: f32 = 24.0;
/// Default corner radius of an `affine:note` card (world px).
const CARD_RADIUS: f32 = 8.0;
/// Corner radius of an `affine:frame` container (world px, matching BlockSuite).
const FRAME_RADIUS: f32 = 2.0;
/// Frame title pill height and vertical gap above the frame top edge (world px).
const FRAME_TITLE_HEIGHT: f32 = 22.0;
const FRAME_TITLE_GAP: f32 = 6.0;
/// Screen-space zoom bar constants (concentric radii: outer 8 - pad 4 == inner 4).
const ZOOM_BAR_MARGIN: f32 = 12.0;
const ZOOM_BAR_PAD: f32 = 4.0;
const ZOOM_BAR_RADIUS: f32 = 8.0;
const ZOOM_BTN_RADIUS: f32 = 4.0;
const ZOOM_BTN_HEIGHT: f32 = 28.0;
type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64);
struct CachedNoteFlow {
flow: BlockFlow,
key: NoteLayoutKey,
layout: Rc<FlowLayout>,
}
/// Persistent Edgeless camera, interaction state, and cached per-Note/EdgelessText layouts.
#[derive(Default)]
pub struct EdgelessCanvasState {
pub camera: EdgelessCamera,
pub camera_initialized: bool,
pub drag_pan_anchor: Option<Point<Pixels>>,
note_flows: HashMap<String, CachedNoteFlow>,
text_flows: HashMap<String, CachedNoteFlow>,
/// Number of block bodies laid out during the most recent Edgeless frame.
pub last_frame_relayouts: u64,
}
/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`) from `root.children`
/// and any `BlockContent::Surface`'s children in document order.
fn spatial_blocks(root: &BlockNode) -> Vec<&BlockNode> {
let mut out = Vec::new();
for child in &root.children {
match &child.content {
BlockContent::Surface { .. } => {
for sub in &child.children {
if is_spatial_block(sub) {
out.push(sub);
}
}
}
_ if is_spatial_block(child) => out.push(child),
_ => {}
}
}
out
}
fn is_spatial_block(node: &BlockNode) -> bool {
match &node.content {
BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => true,
BlockContent::Note {
display_mode,
hidden: false,
..
} => *display_mode != NoteDisplayMode::DocOnly,
_ => false,
}
}
fn edgeless_prop<'a>(
node: &'a BlockNode,
flat_key: &str,
nested: &[&str],
) -> Option<&'a JsonValue> {
if let Some(v) = node.props.get(flat_key) {
return Some(v);
}
let mut cur = node.props.get("prop:edgeless")?;
for seg in nested {
cur = cur.get(*seg)?;
}
Some(cur)
}
fn note_scale(node: &BlockNode) -> f32 {
edgeless_prop(node, "prop:edgeless.scale", &["scale"])
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite())
.unwrap_or(1.0)
.clamp(0.1, 10.0)
}
fn note_collapse(node: &BlockNode) -> bool {
edgeless_prop(node, "prop:edgeless.collapse", &["collapse"])
.and_then(JsonValue::as_bool)
.unwrap_or(false)
}
fn note_collapsed_height(node: &BlockNode) -> Option<f32> {
edgeless_prop(node, "prop:edgeless.collapsedHeight", &["collapsedHeight"])
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite() && *v > 0.0)
}
fn note_border_style(node: &BlockNode) -> Option<(BorderStyle, f32)> {
let style = edgeless_prop(
node,
"prop:edgeless.style.borderStyle",
&["style", "borderStyle"],
)
.and_then(JsonValue::as_str)
.unwrap_or("none");
let border_style = match style {
"solid" => BorderStyle::Solid,
"dash" | "dashed" => BorderStyle::Dashed,
_ => return None,
};
let size = edgeless_prop(
node,
"prop:edgeless.style.borderSize",
&["style", "borderSize"],
)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(4.0);
if size <= 0.0 {
None
} else {
Some((border_style, size))
}
}
fn note_border_radius(node: &BlockNode) -> f32 {
edgeless_prop(
node,
"prop:edgeless.style.borderRadius",
&["style", "borderRadius"],
)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(CARD_RADIUS)
}
fn note_shadow_type(node: &BlockNode) -> &str {
edgeless_prop(
node,
"prop:edgeless.style.shadowType",
&["style", "shadowType"],
)
.and_then(JsonValue::as_str)
.unwrap_or("--affine-note-shadow-box")
}
impl EdgelessCanvasState {
pub fn new() -> Self {
Self::default()
}
pub fn set_camera(&mut self, pan_x: f32, pan_y: f32, zoom: f32) {
self.camera = EdgelessCamera::new(pan_x, pan_y, zoom);
self.camera_initialized = true;
}
pub fn set_zoom_centered(
&mut self,
zoom: f32,
viewport_origin: Point<Pixels>,
viewport_size: Size<Pixels>,
) {
let center = point(
px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5),
px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5),
);
self.camera.zoom_at(zoom, center, viewport_origin);
self.camera_initialized = true;
}
pub fn set_pan(&mut self, pan_x: f32, pan_y: f32) {
self.camera.pan_x = pan_x;
self.camera.pan_y = pan_y;
self.camera_initialized = true;
}
#[cfg(test)]
pub fn cached_note_layout(&self, id: &str) -> Option<Rc<FlowLayout>> {
self.note_flows.get(id).map(|entry| entry.layout.clone())
}
#[cfg(test)]
pub fn cached_text_layout(&self, id: &str) -> Option<Rc<FlowLayout>> {
self.text_flows.get(id).map(|entry| entry.layout.clone())
}
/// Compute the bounding box of all Edgeless-visible Frames, Notes, and EdgelessTexts.
pub fn scene_world_bounds(&self, snapshot: &PageSnapshot) -> WorldRect {
let mut union = WorldRect::default();
let Some(root) = &snapshot.root else {
return union;
};
for child in spatial_blocks(root) {
match &child.content {
BlockContent::Frame { xywh, .. } => {
if let Some(rect) = parse_xywh(xywh) {
let with_title = WorldRect::new(
rect.x,
rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP,
rect.w,
rect.h + FRAME_TITLE_HEIGHT + FRAME_TITLE_GAP,
);
union = union.union(with_title);
}
}
BlockContent::Note {
display_mode,
xywh,
hidden,
..
} if !hidden && *display_mode != NoteDisplayMode::DocOnly => {
let mut rect =
parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0));
if note_collapse(child) {
rect.h = note_collapsed_height(child).unwrap_or(rect.h);
} else if let Some(cached) = self.note_flows.get(&child.id) {
let scale = note_scale(child);
rect.h = rect
.h
.max((cached.layout.height + 2.0 * NOTE_CARD_PADDING) * scale);
}
union = union.union(rect);
}
BlockContent::EdgelessText { xywh } => {
if let Some(mut rect) = parse_xywh(xywh) {
let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0);
if let Some(cached) = self.text_flows.get(&child.id) {
rect.h = (cached.layout.height * scale).max(rect.h);
}
union = union.union(rect);
}
}
_ => {}
}
}
union
}
}
/// Resolved frame card ready to paint on the GPU canvas.
struct PaintFrame {
id: String,
rect: WorldRect,
title: String,
fill: Option<Hsla>,
}
/// Resolved note card with its cached `FlowLayout`.
struct PaintNote {
id: String,
rect: WorldRect,
scale: f32,
border: Option<(BorderStyle, f32)>,
border_radius: f32,
shadows: Vec<ui::BoxShadow>,
fill: Hsla,
layout: Rc<FlowLayout>,
}
/// Resolved edgeless-text block with its cached `FlowLayout` and rotation/scale.
struct PaintEdgelessText {
id: String,
rect: WorldRect,
scale: f32,
rotate_deg: f32,
layout: Rc<FlowLayout>,
}
/// Resolve a BlockSuite `{ light, dark }` color map or string color token against `theme`.
pub fn resolve_edgeless_color(value: &JsonValue, theme: PlaygroundTheme) -> Option<Hsla> {
let raw = match value {
JsonValue::String(s) => s.as_str(),
JsonValue::Object(map) => {
let key = match theme {
PlaygroundTheme::Light => "light",
PlaygroundTheme::Dark => "dark",
};
map.get(key)
.and_then(JsonValue::as_str)
.or_else(|| map.get("normal").and_then(JsonValue::as_str))?
}
_ => return None,
};
if raw.eq_ignore_ascii_case("transparent") || raw.is_empty() {
return Some(Hsla::transparent_black());
}
theme.css_color(raw)
}
fn prop_f32(node: &BlockNode, key: &str, default: f32) -> f32 {
node.props
.get(key)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite())
.unwrap_or(default)
}
fn prop_bool(node: &BlockNode, key: &str, default: bool) -> bool {
node.props
.get(key)
.and_then(JsonValue::as_bool)
.unwrap_or(default)
}
/// Inputs needed to prepare and build one Edgeless canvas frame.
pub struct EdgelessRenderInput<'a> {
pub snapshot: &'a PageSnapshot,
pub doc_rev: u64,
pub env_rev: u64,
pub theme: PlaygroundTheme,
pub palette: &'a Palette,
pub page_titles: &'a BTreeMap<String, String>,
pub images: &'a HashMap<String, ImageSlot>,
pub viewport_width: f32,
pub viewport_height: f32,
}
/// Prepare cached Note & EdgelessText layouts (zero relayout when camera moves), fit camera
/// on first render, and return the spatial canvas element plus screen-space snapshot markers.
pub fn build_edgeless_layer(
state: &mut EdgelessCanvasState,
input: &EdgelessRenderInput<'_>,
window: &Window,
zoom_controls: AnyElement,
) -> AnyElement {
state.last_frame_relayouts = 0;
let mut frames = Vec::new();
let mut notes = Vec::new();
let mut texts = Vec::new();
if let Some(root) = &input.snapshot.root {
let mut active_notes = Vec::new();
let mut active_texts = Vec::new();
for child in spatial_blocks(root) {
match &child.content {
BlockContent::Frame { title, xywh } => {
if let Some(rect) = parse_xywh(xywh) {
let fill = child
.props
.get("prop:background")
.and_then(|v| resolve_edgeless_color(v, input.theme))
.filter(|c| !c.is_transparent());
frames.push(PaintFrame {
id: child.id.clone(),
rect,
title: if title.plain.is_empty() {
"Frame".to_string()
} else {
title.plain.clone()
},
fill,
});
}
}
BlockContent::Note {
display_mode,
xywh,
background,
hidden,
} if !hidden && *display_mode != NoteDisplayMode::DocOnly => {
let mut rect =
parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0));
let scale = note_scale(child);
let collapse = note_collapse(child);
let collapsed_height = note_collapsed_height(child);
let border = note_border_style(child);
let border_radius = note_border_radius(child);
let shadows = input.theme.shadows(note_shadow_type(child));
let inner_width = (rect.w / scale - 2.0 * NOTE_CARD_PADDING).max(120.0);
let key = (
input.doc_rev,
inner_width.to_bits(),
scale.to_bits(),
input.theme,
input.env_rev,
);
let layout = match state.note_flows.get_mut(&child.id) {
Some(cached) if cached.key == key => cached.layout.clone(),
_ => {
let flow_input = FlowInput {
snapshot: input.snapshot,
width: inner_width,
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
env_rev: input.env_rev,
};
let entry =
state.note_flows.entry(child.id.clone()).or_insert_with(|| {
CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: inner_width,
height: 0.0,
stats: Default::default(),
}),
}
});
let laid_out =
entry
.flow
.layout_nodes(&child.children, &flow_input, window);
state.last_frame_relayouts += laid_out.stats.laid_out as u64;
let rc = Rc::new(laid_out);
entry.key = key;
entry.layout = rc.clone();
rc
}
};
if collapse {
rect.h = collapsed_height.unwrap_or(rect.h);
} else {
rect.h = rect
.h
.max((layout.height + 2.0 * NOTE_CARD_PADDING) * scale);
}
let fill = resolve_edgeless_color(background, input.theme)
.filter(|c| !c.is_transparent())
.unwrap_or(input.palette.background);
active_notes.push(child.id.clone());
notes.push(PaintNote {
id: child.id.clone(),
rect,
scale,
border,
border_radius,
shadows,
fill,
layout,
});
}
BlockContent::EdgelessText { xywh } => {
if let Some(mut rect) = parse_xywh(xywh) {
let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0);
let rotate_deg = prop_f32(child, "prop:rotate", 0.0);
let has_max_width = prop_bool(child, "prop:hasMaxWidth", true);
let text_width = if has_max_width {
(rect.w / scale).max(60.0)
} else {
(rect.w / scale).max(320.0)
};
let key = (
input.doc_rev,
text_width.to_bits(),
scale.to_bits(),
input.theme,
input.env_rev,
);
let layout = match state.text_flows.get_mut(&child.id) {
Some(cached) if cached.key == key => cached.layout.clone(),
_ => {
let flow_input = FlowInput {
snapshot: input.snapshot,
width: text_width,
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
env_rev: input.env_rev,
};
let entry = state
.text_flows
.entry(child.id.clone())
.or_insert_with(|| CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: text_width,
height: 0.0,
stats: Default::default(),
}),
});
let laid_out =
entry
.flow
.layout_nodes(&child.children, &flow_input, window);
state.last_frame_relayouts += laid_out.stats.laid_out as u64;
let rc = Rc::new(laid_out);
entry.key = key;
entry.layout = rc.clone();
rc
}
};
rect.h = (layout.height * scale).max(rect.h);
active_texts.push(child.id.clone());
texts.push(PaintEdgelessText {
id: child.id.clone(),
rect,
scale,
rotate_deg,
layout,
});
}
}
_ => {}
}
}
if state.note_flows.len() > active_notes.len() {
state.note_flows.retain(|id, _| active_notes.contains(id));
}
if state.text_flows.len() > active_texts.len() {
state.text_flows.retain(|id, _| active_texts.contains(id));
}
}
if !state.camera_initialized && input.viewport_width > 0.0 && input.viewport_height > 0.0 {
let bounds = state.scene_world_bounds(input.snapshot);
state.camera.fit_to_bounds(
bounds,
size(px(input.viewport_width), px(input.viewport_height)),
48.0,
);
state.camera_initialized = true;
}
let camera = state.camera;
let palette = *input.palette;
let theme = input.theme;
let visible_world =
camera.visible_world_bounds(size(px(input.viewport_width), px(input.viewport_height)));
// Record screen-space snapshot markers for fully-visible spatial items so `bs-harness audit`
// and tests can inspect their screen bounds without triggering false clipping violations.
let mut snapshot_markers: Vec<AnyElement> = Vec::new();
let vp_origin = point(px(0.0), px(0.0));
let push_marker =
|markers: &mut Vec<AnyElement>, id: String, rect: WorldRect, text: Option<String>| {
let tl = camera.world_to_screen(point(px(rect.x), px(rect.y)), vp_origin);
let br = camera.world_to_screen(point(px(rect.right()), px(rect.bottom())), vp_origin);
let x = f32::from(tl.x);
let y = f32::from(tl.y);
let w = f32::from(br.x) - x;
let h = f32::from(br.y) - y;
if x >= 0.0
&& y >= 0.0
&& x + w <= input.viewport_width
&& y + h <= input.viewport_height
&& w >= 1.0
&& h >= 1.0
{
let mut el = div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.snapshot(SharedString::from(id), Some(EDGELESS_VIEWPORT_ID));
if let Some(t) = text {
el = el.snapshot_text(t);
}
markers.push(el.into_any_element());
}
};
for frame in &frames {
push_marker(
&mut snapshot_markers,
format!("edgeless.frame.{}", frame.id),
frame.rect,
Some(frame.title.clone()),
);
}
for note in &notes {
push_marker(
&mut snapshot_markers,
format!("edgeless.note.{}", note.id),
note.rect,
None,
);
}
for et in &texts {
push_marker(
&mut snapshot_markers,
format!("edgeless.text.{}", et.id),
et.rect,
None,
);
}
let frame_border = theme
.css_var("--affine-v2-edgeless-frame-border")
.unwrap_or(palette.border);
let frame_pill_bg = palette.panel;
let paint_canvas = canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
// 1. Single-draw-call procedural dot-grid background.
let gap = bg_grid_gap(camera.zoom);
let (phase_x, phase_y) = camera.dot_grid_phase(gap);
window.paint_quad(ui::fill(
bounds,
Background::dot_grid(
palette.background,
palette.edgeless_grid,
gap,
1.0,
phase_x,
phase_y,
),
));
let cam_matrix = camera.to_transformation_matrix(bounds.origin);
let cull_world = visible_world.dilate(120.0);
window.with_content_mask(Some(ContentMask { bounds }), |window| {
window.with_paint_transformation(cam_matrix, |window| {
// 2. Frames (back layer).
for frame in &frames {
if !frame.rect.intersects(cull_world) {
continue;
}
let fb = Bounds::new(
point(px(frame.rect.x), px(frame.rect.y)),
size(px(frame.rect.w), px(frame.rect.h)),
);
window.paint_quad(ui::quad(
fb,
Corners::all(px(FRAME_RADIUS)),
frame.fill.unwrap_or_else(Hsla::transparent_black),
Edges::all(px(1.0)),
frame_border,
BorderStyle::Solid,
));
// Frame title pill above top-left corner.
let title_style =
InlineStyle::new(FONT_SANS, 12.0, 500.0, palette.text_secondary);
let title_inline = layout_inline(
&frame.title,
&title_style,
frame.rect.w.max(80.0),
FRAME_TITLE_HEIGHT,
InlineBaseline::Of(&title_style),
InlineAlign::Left,
window,
);
let pill_w =
(title_inline.content_width() + 16.0).min(frame.rect.w.max(80.0));
let pill_x = frame.rect.x;
let pill_y = frame.rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP;
window.paint_quad(ui::quad(
Bounds::new(
point(px(pill_x), px(pill_y)),
size(px(pill_w), px(FRAME_TITLE_HEIGHT)),
),
Corners::all(px(4.0)),
frame_pill_bg,
Edges::all(px(1.0)),
palette.border,
BorderStyle::Solid,
));
title_inline.paint(point(px(pill_x + 8.0), px(pill_y)), window, cx);
}
// 3. Notes (middle layer): shadow + card + scaled locally masked cached BlockFlow.
for note in &notes {
if !note.rect.intersects(cull_world) {
continue;
}
let nb = Bounds::new(
point(px(note.rect.x), px(note.rect.y)),
size(px(note.rect.w), px(note.rect.h)),
);
if !note.shadows.is_empty() {
window.paint_drop_shadows(
nb,
Corners::all(px(note.border_radius)),
&note.shadows,
);
}
let (border_widths, border_color, border_style) = match note.border {
Some((style, width)) => (Edges::all(px(width)), palette.border, style),
None => (
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
),
};
window.paint_quad(ui::quad(
nb,
Corners::all(px(note.border_radius)),
note.fill,
border_widths,
border_color,
border_style,
));
let scale_transform = TransformationMatrix::unit()
.translate(point(ScaledPixels(note.rect.x), ScaledPixels(note.rect.y)))
.scale(size(note.scale, note.scale))
.translate(point(
ScaledPixels(-note.rect.x),
ScaledPixels(-note.rect.y),
));
let inner_bounds = Bounds::new(
point(
px(note.rect.x + NOTE_CARD_PADDING),
px(note.rect.y + NOTE_CARD_PADDING),
),
size(
px((note.rect.w / note.scale - 2.0 * NOTE_CARD_PADDING).max(0.0)),
px((note.rect.h / note.scale - 2.0 * NOTE_CARD_PADDING).max(0.0)),
),
);
window.with_paint_transformation(scale_transform, |window| {
window.with_local_paint_mask(
ContentMask {
bounds: inner_bounds,
},
|window| {
for block in &note.layout.blocks {
let origin = point(
px(note.rect.x + NOTE_CARD_PADDING + block.x),
px(note.rect.y + NOTE_CARD_PADDING + block.y),
);
block.body.paint(origin, BlockPaint::default(), window, cx);
}
},
);
});
}
// 4. EdgelessText (front layer): scale from top-left, then rotate around visual center.
for et in &texts {
if !et.rect.intersects(cull_world) {
continue;
}
let (cx_w, cy_w) = et.rect.center();
let scale_from_tl = TransformationMatrix::unit()
.translate(point(ScaledPixels(et.rect.x), ScaledPixels(et.rect.y)))
.scale(size(et.scale, et.scale))
.translate(point(ScaledPixels(-et.rect.x), ScaledPixels(-et.rect.y)));
let rotate_around_center = TransformationMatrix::unit()
.translate(point(ScaledPixels(cx_w), ScaledPixels(cy_w)))
.rotate(ui::radians(et.rotate_deg.to_radians()))
.translate(point(ScaledPixels(-cx_w), ScaledPixels(-cy_w)));
let local_transform = rotate_around_center.compose(scale_from_tl);
window.with_paint_transformation(local_transform, |window| {
for block in &et.layout.blocks {
let origin =
point(px(et.rect.x + block.x), px(et.rect.y + block.y));
block.body.paint(origin, BlockPaint::default(), window, cx);
}
});
}
});
});
},
)
.size_full();
div()
.relative()
.flex_1()
.w_full()
.min_h_0()
.overflow_hidden()
.snapshot(EDGELESS_VIEWPORT_ID, Some("root.canvas"))
.child(paint_canvas)
.children(snapshot_markers)
.child(zoom_controls)
.into_any_element()
}
/// Build the bottom-right screen-space zoom control bar (`chrome.edgeless_zoom`).
pub fn build_zoom_controls<V: 'static>(
zoom: f32,
palette: &Palette,
theme: PlaygroundTheme,
on_out: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_reset: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_in: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_fit: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
cx: &mut ui::Context<V>,
) -> AnyElement {
let pct_label = format!("{}%", (zoom * 100.0).round() as i32);
let shadows = theme.shadows("--affine-toolbar-shadow");
let button = |id: &'static str, snap_id: &'static str, label: String, width: f32| {
div()
.id(id)
.w(px(width))
.h(px(ZOOM_BTN_HEIGHT))
.rounded(px(ZOOM_BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.text_size(px(12.0))
.font_weight(ui::FontWeight::MEDIUM)
.text_color(palette.text_primary)
.cursor_pointer()
.hover(|s| s.bg(palette.hover))
.snapshot(snap_id, Some("chrome.edgeless_zoom"))
.snapshot_text(label.clone())
.child(label)
};
let mut bar = div()
.absolute()
.right(px(ZOOM_BAR_MARGIN))
.bottom(px(ZOOM_BAR_MARGIN))
.p(px(ZOOM_BAR_PAD))
.rounded(px(ZOOM_BAR_RADIUS))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(4.0))
.snapshot("chrome.edgeless_zoom", Some(EDGELESS_VIEWPORT_ID))
.child(
button(
"edgeless-zoom-out",
"chrome.edgeless_zoom.out",
"-".into(),
28.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_out)),
)
.child(
button(
"edgeless-zoom-reset",
"chrome.edgeless_zoom.reset",
pct_label,
48.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_reset)),
)
.child(
button(
"edgeless-zoom-in",
"chrome.edgeless_zoom.in",
"+".into(),
28.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_in)),
)
.child(
button(
"edgeless-zoom-fit",
"chrome.edgeless_zoom.fit",
"Fit".into(),
36.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_fit)),
);
if !shadows.is_empty() {
bar = bar.shadow(shadows.into());
}
bar.into_any_element()
}
@@ -6,6 +6,8 @@
pub mod block_flow;
pub mod clipboard;
pub mod edgeless_camera;
pub mod edgeless_canvas;
pub mod editor_session;
pub mod overlays;
pub mod rich_text;
@@ -198,6 +200,7 @@ pub struct PlaygroundView {
max_scroll: f32,
/// Window size of the latest frame, in logical pixels.
window_size: (f32, f32),
edgeless: edgeless_canvas::EdgelessCanvasState,
overlays: Overlays,
/// Timer that ends a code block's `Copied` label; a newer copy replaces it.
copied_timer: Option<Task<()>>,
@@ -282,6 +285,7 @@ impl PlaygroundView {
scroll_y: 0.0,
max_scroll: 0.0,
window_size: (0.0, 0.0),
edgeless: edgeless_canvas::EdgelessCanvasState::new(),
overlays: Overlays::new(),
copied_timer: None,
_tasks: tasks,
@@ -298,6 +302,101 @@ impl PlaygroundView {
self.theme
}
pub fn edgeless_camera(&self) -> edgeless_camera::EdgelessCamera {
self.edgeless.camera
}
pub fn set_edgeless_camera(
&mut self,
pan_x: f32,
pan_y: f32,
zoom: f32,
cx: &mut Context<Self>,
) {
self.edgeless.set_camera(pan_x, pan_y, zoom);
cx.notify();
}
pub fn set_edgeless_zoom(&mut self, zoom: f32, cx: &mut Context<Self>) {
let (vw, vh) = self.edgeless_viewport_size();
self.edgeless.set_zoom_centered(
zoom,
point(px(0.0), px(TOPBAR_HEIGHT)),
size(px(vw), px(vh)),
);
cx.notify();
}
pub fn set_edgeless_pan(&mut self, pan_x: f32, pan_y: f32, cx: &mut Context<Self>) {
self.edgeless.set_pan(pan_x, pan_y);
cx.notify();
}
pub fn edgeless_last_frame_relayouts(&self) -> u64 {
self.edgeless.last_frame_relayouts
}
fn edgeless_viewport_size(&self) -> (f32, f32) {
let vw = self.window_size.0.max(1.0);
let vh = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0);
(vw, vh)
}
fn on_edgeless_scroll(&mut self, event: &ScrollEvent, _: &mut Window, cx: &mut Context<Self>) {
let delta = event.delta.pixel_delta(px(SCROLL_LINE));
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
if event.modifiers.control || event.modifiers.platform {
let factor = (-f32::from(delta.y) * 0.002).exp();
let target_zoom = self.edgeless.camera.zoom * factor;
self.edgeless
.camera
.zoom_at(target_zoom, event.position, vp_origin);
} else {
self.edgeless
.camera
.pan_by_screen_delta(f32::from(delta.x), f32::from(delta.y));
}
self.edgeless.camera_initialized = true;
cx.notify();
}
fn on_edgeless_pan_start(
&mut self,
event: &ui::MouseDownEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.edgeless.drag_pan_anchor = Some(event.position);
cx.notify();
}
fn on_edgeless_pan_move(
&mut self,
event: &ui::MouseMoveEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if let Some(prev) = self.edgeless.drag_pan_anchor {
let dx = f32::from(event.position.x) - f32::from(prev.x);
let dy = f32::from(event.position.y) - f32::from(prev.y);
self.edgeless.camera.pan_by_screen_delta(dx, dy);
self.edgeless.drag_pan_anchor = Some(event.position);
self.edgeless.camera_initialized = true;
cx.notify();
}
}
fn on_edgeless_pan_end(
&mut self,
_: &ui::MouseUpEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if self.edgeless.drag_pan_anchor.take().is_some() {
cx.notify();
}
}
pub fn set_theme(&mut self, theme: PlaygroundTheme, cx: &mut Context<Self>) {
if self.theme != theme {
self.theme = theme;
@@ -1141,57 +1240,89 @@ impl PlaygroundView {
)
}
fn render_edgeless(&self, palette: &Palette, viewport_width: f32) -> AnyElement {
let title_text = "Edgeless Spatial Canvas";
let body_text =
"Infinite spatial canvas mode active — click Page to return to document layout.";
let gutter = if viewport_width <= block_flow::NARROW_VIEWPORT {
24.0
} else {
48.0
fn render_edgeless(
&mut self,
palette: &Palette,
viewport_width: f32,
viewport_height: f32,
window: &Window,
cx: &mut Context<Self>,
) -> AnyElement {
let Some(snapshot) = self.snapshot.clone() else {
return div()
.flex_1()
.w_full()
.min_h_0()
.bg(palette.background_secondary)
.snapshot(edgeless_canvas::EDGELESS_VIEWPORT_ID, Some("root.canvas"))
.into_any_element();
};
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let vp_size = size(px(viewport_width.max(1.0)), px(viewport_height.max(1.0)));
let zoom_controls = edgeless_canvas::build_zoom_controls(
self.edgeless.camera.zoom,
palette,
self.theme,
move |this: &mut Self, _, _, cx| {
this.edgeless.camera.zoom_out(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
this.edgeless.camera.reset_zoom(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
this.edgeless.camera.zoom_in(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
if let Some(snap) = &this.snapshot {
let bounds = this.edgeless.scene_world_bounds(snap);
this.edgeless.camera.fit_to_bounds(bounds, vp_size, 48.0);
this.edgeless.camera_initialized = true;
cx.notify();
}
},
cx,
);
let input = edgeless_canvas::EdgelessRenderInput {
snapshot: &snapshot,
doc_rev: self.doc_rev,
env_rev: self.env_rev,
theme: self.theme,
palette,
page_titles: &self.page_titles,
images: &self.images,
viewport_width,
viewport_height,
};
let layer = edgeless_canvas::build_edgeless_layer(
&mut self.edgeless,
&input,
window,
zoom_controls,
);
div()
.flex_1()
.w_full()
.min_h_0()
.flex()
.justify_center()
.p(px(gutter))
.bg(palette.background_secondary)
.child(
div()
.w_full()
.max_w(px(block_flow::EDITOR_WIDTH))
.h_full()
.p(px(32.0))
.rounded(px(12.0))
.bg(palette.background)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(16.0))
.snapshot(PAGE_SURFACE_ID, Some("root.canvas"))
.child(
div()
.text_size(px(24.0))
.font_weight(FontWeight::BOLD)
.text_color(palette.text_primary)
.snapshot("page.title_block", Some(PAGE_SURFACE_ID))
.snapshot_text(title_text)
.child(title_text),
)
.child(div().w_full().h(px(1.0)).bg(palette.border))
.child(
div()
.text_size(px(14.0))
.font_weight(FontWeight::NORMAL)
.text_color(palette.text_secondary)
.snapshot("page.body_block", Some(PAGE_SURFACE_ID))
.snapshot_text(body_text)
.child(body_text),
),
.flex_col()
.on_scroll(cx.listener(Self::on_edgeless_scroll))
.on_mouse_down(
MouseButton::Middle,
cx.listener(Self::on_edgeless_pan_start),
)
.on_mouse_move(cx.listener(Self::on_edgeless_pan_move))
.on_mouse_up(MouseButton::Middle, cx.listener(Self::on_edgeless_pan_end))
.child(layer)
.into_any_element()
}
}
@@ -1232,7 +1363,9 @@ impl ui::Render for PlaygroundView {
window,
cx,
),
PlaygroundMode::Edgeless => self.render_edgeless(&palette, viewport_width),
PlaygroundMode::Edgeless => {
self.render_edgeless(&palette, viewport_width, viewport_height, window, cx)
}
};
let popovers = self.overlay_popovers(&palette, window, cx);
@@ -1469,9 +1602,20 @@ pub fn seed_showcase_doc() -> DocResult<DocState> {
BlockSpec::Surface,
Some("showcase-page"),
)?;
seed.add(
"showcase-frame",
BlockSpec::Frame {
title: "Workspace Overview".to_string(),
xywh: Some("[-40,-60,1240,1320]".to_string()),
presentation_index: Some("a0".to_string()),
},
Some("showcase-surface"),
)?;
seed.add(
"showcase-note",
BlockSpec::Note { xywh: None },
BlockSpec::Note {
xywh: Some("[0,0,760,1180]".to_string()),
},
Some("showcase-page"),
)?;
let note = "showcase-note";
@@ -1666,6 +1810,79 @@ pub fn seed_showcase_doc() -> DocResult<DocState> {
now_ms,
)?;
// Edgeless-only spatial blocks (excluded from Page mode by `is_edgeless_only`).
seed.add(
"showcase-edgeless-note",
BlockSpec::Note {
xywh: Some("[820,40,340,260]".to_string()),
},
Some("showcase-page"),
)?;
let now_ms = seed.tick();
seed.page.set_block_prop(
"showcase-edgeless-note",
"prop:displayMode",
SessionValue::Any(Any::String("edgeless".to_string())),
now_ms,
)?;
let now_ms = seed.tick();
seed.page.set_block_prop(
"showcase-edgeless-note",
"prop:background",
SessionValue::Any(Any::String(
"var(--affine-background-primary-color)".to_string(),
)),
now_ms,
)?;
seed.paragraph(
"showcase-edgeless-note-h",
ParagraphType::H3,
"Spatial Notes",
"showcase-edgeless-note",
)?;
seed.list(
"showcase-edgeless-note-b1",
ListType::Bulleted,
"GPU world-space transforms & crisp dot-grid",
false,
"showcase-edgeless-note",
)?;
seed.list(
"showcase-edgeless-note-b2",
ListType::Bulleted,
"Zero BlockFlow relayout during pan & zoom",
false,
"showcase-edgeless-note",
)?;
seed.add(
"showcase-edgeless-text",
BlockSpec::EdgelessText {
xywh: Some("[820,360,320,84]".to_string()),
},
Some("showcase-surface"),
)?;
let now_ms = seed.tick();
seed.page.set_block_prop(
"showcase-edgeless-text",
"prop:rotate",
SessionValue::Any(Any::Float64((-4.0_f64).into())),
now_ms,
)?;
let now_ms = seed.tick();
seed.page.set_block_prop(
"showcase-edgeless-text",
"prop:scale",
SessionValue::Any(Any::Float64((1.0_f64).into())),
now_ms,
)?;
seed.paragraph(
"showcase-edgeless-text-p",
ParagraphType::H4,
"Rotated EdgelessText on GPU",
"showcase-edgeless-text",
)?;
let image = showcase_gradient_png();
if !image.is_empty() {
state
@@ -1959,9 +2176,17 @@ mod tests {
page_snap.elements["page.title_block"].text.as_deref(),
Some("Native BlockSuite Playground")
);
assert_ne!(
page_snap.elements["page.title_block"].text,
edgeless_snap.elements["page.title_block"].text
assert!(
edgeless_snap.elements.contains_key("edgeless.viewport"),
"edgeless viewport missing from FrameSnapshot"
);
assert!(
edgeless_snap.elements.contains_key("chrome.edgeless_zoom"),
"edgeless zoom bar missing from FrameSnapshot"
);
assert!(
!edgeless_snap.elements.contains_key("page.title_block"),
"page.title_block should not remain mounted in Edgeless mode"
);
assert_ne!(
page_img.as_raw(),
@@ -3984,4 +4209,406 @@ mod tests {
"ws://127.0.0.1:9000/native-sync/rooms/r"
);
}
#[test]
fn edgeless_surface_parentage_includes_frame_text_and_note() {
let mut doc = DocState::new("surf-tree", client_id_from_seed(0x501)).expect("state");
doc.workspace.initialize_meta().expect("meta");
doc.workspace
.create_page(HOME_PAGE_ID, "Surface Tree", 1)
.expect("page");
let page = doc.workspace.ensure_page(HOME_PAGE_ID).expect("page");
let mut seed = ShowcaseSeed { page, now_ms: 0 };
seed.add(
"s-page",
BlockSpec::Page {
title: "Surface Tree".to_string(),
},
None,
)
.expect("page");
seed.add("s-surface", BlockSpec::Surface, Some("s-page"))
.expect("surface");
seed.add(
"s-frame",
BlockSpec::Frame {
title: "Surface Frame".to_string(),
xywh: Some("[0,0,700,420]".to_string()),
presentation_index: Some("a0".to_string()),
},
Some("s-surface"),
)
.expect("frame under surface");
seed.add(
"s-text",
BlockSpec::EdgelessText {
xywh: Some("[440,60,220,60]".to_string()),
},
Some("s-surface"),
)
.expect("edgeless text under surface");
seed.paragraph("s-text-p", ParagraphType::H4, "Under Surface", "s-text")
.expect("text child");
seed.add(
"s-note",
BlockSpec::Note {
xywh: Some("[40,40,360,240]".to_string()),
},
Some("s-page"),
)
.expect("note under page");
seed.paragraph("s-note-p", ParagraphType::Text, "Page note body", "s-note")
.expect("note child");
let session = open(
1280,
800,
PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
);
session.view(|view, cx| view.set_document(doc, cx));
let (snap, _) = session.frame();
assert_no_violations(&snap, "Edgeless surface tree");
assert!(
snap.elements.contains_key("edgeless.frame.s-frame"),
"Frame under Surface missing from snapshot"
);
assert!(
snap.elements.contains_key("edgeless.text.s-text"),
"EdgelessText under Surface missing from snapshot"
);
assert!(
snap.elements.contains_key("edgeless.note.s-note"),
"Note under Page missing from snapshot"
);
}
#[test]
fn edgeless_panned_code_and_bookmark_render_glyph_ink_across_zooms() {
let mut doc = DocState::new("pan-clip", client_id_from_seed(0x502)).expect("state");
doc.workspace.initialize_meta().expect("meta");
doc.workspace
.create_page(HOME_PAGE_ID, "Pan Clip", 1)
.expect("page");
let page = doc.workspace.ensure_page(HOME_PAGE_ID).expect("page");
let mut seed = ShowcaseSeed { page, now_ms: 0 };
seed.add(
"p-page",
BlockSpec::Page {
title: "Pan Clip".to_string(),
},
None,
)
.expect("page");
seed.add("p-surface", BlockSpec::Surface, Some("p-page"))
.expect("surface");
seed.add(
"p-note",
BlockSpec::Note {
xywh: Some("[2000,100,600,360]".to_string()),
},
Some("p-page"),
)
.expect("note");
seed.add(
"p-code",
BlockSpec::Code {
text: "fn edgeless_local_clip() -> u32 { 42 }".to_string(),
language: Some("rust".to_string()),
caption: String::new(),
},
Some("p-note"),
)
.expect("code");
let now_ms = seed.tick();
seed.page
.set_block_prop("p-code", "prop:wrap", SessionValue::Any(Any::False), now_ms)
.expect("unwrap code");
seed.add(
"p-bookmark",
BlockSpec::Bookmark {
url: "https://affine.pro/docs".to_string(),
title: Some("AFFiNE Docs".to_string()),
description: Some(
"Local-first collaborative workspace description text.".to_string(),
),
},
Some("p-note"),
)
.expect("bookmark");
let session = open(
1280,
800,
PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
);
session.view(|view, cx| view.set_document(doc, cx));
for zoom in [0.5_f32, 1.0, 2.0] {
let pan_x = 2000.0 - 50.0 / zoom;
let pan_y = 100.0 - 40.0 / zoom;
session.view(|view, cx| view.set_edgeless_camera(pan_x, pan_y, zoom, cx));
let (_, img) = session.frame();
// Count distinct non-white ink pixels inside the rendered Note card region
// where the code language header ("rust"), code line, and bookmark description sit.
let card_left = 50_u32;
let card_top = (TOPBAR_HEIGHT + 40.0) as u32;
let card_w = (600.0 * zoom).min(1200.0) as u32;
let card_h = (320.0 * zoom).min(680.0) as u32;
let mut dark_ink_pixels = 0_u64;
for y in card_top..(card_top + card_h).min(img.height()) {
for x in card_left..(card_left + card_w).min(img.width()) {
let p = img.get_pixel(x, y);
// Text ink in light theme is significantly darker than the white/gray card surface.
if p[0] < 180 && p[1] < 180 && p[2] < 180 {
dark_ink_pixels += 1;
}
}
}
assert!(
dark_ink_pixels > 150,
"zoom={zoom}: expected visible glyph ink for code header/line + bookmark description, got only {dark_ink_pixels} dark pixels"
);
// Also verify the GPU scene emitted monochrome glyph sprites for the panned note
// (language label + code + bookmark title/description/url > 40 glyphs).
let glyph_count = session.app.update(|cx| {
session
.window
.update(cx, |_, window, _| {
window.rendered_scene().monochrome_sprites.len()
})
.expect("read scene")
});
assert!(
glyph_count > 60,
"zoom={zoom}: expected >60 glyph sprites in scene, got {glyph_count}"
);
}
}
#[test]
fn edgeless_scale_2x_wraps_at_half_logical_width_with_zero_camera_relayout() {
let mut doc = DocState::new("scale-2x", client_id_from_seed(0x503)).expect("state");
doc.workspace.initialize_meta().expect("meta");
doc.workspace
.create_page(HOME_PAGE_ID, "Scale 2x", 1)
.expect("page");
let page = doc.workspace.ensure_page(HOME_PAGE_ID).expect("page");
let mut seed = ShowcaseSeed { page, now_ms: 0 };
seed.add(
"sc-page",
BlockSpec::Page {
title: "Scale 2x".to_string(),
},
None,
)
.expect("page");
seed.add("sc-surface", BlockSpec::Surface, Some("sc-page"))
.expect("surface");
seed.add(
"sc-note",
BlockSpec::Note {
xywh: Some("[0,0,400,200]".to_string()),
},
Some("sc-page"),
)
.expect("note");
let mut edgeless_map = AHashMap::default();
edgeless_map.insert("scale".to_string(), Any::Float64(2.0_f64.into()));
let now_ms = seed.tick();
seed.page
.set_block_prop(
"sc-note",
"prop:edgeless",
SessionValue::Any(Any::Object(Box::new(edgeless_map))),
now_ms,
)
.expect("note scale");
seed.paragraph(
"sc-note-p",
ParagraphType::Text,
"Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu",
"sc-note",
)
.expect("note text");
seed.add(
"sc-text",
BlockSpec::EdgelessText {
xywh: Some("[460,0,400,80]".to_string()),
},
Some("sc-surface"),
)
.expect("edgeless text");
let now_ms = seed.tick();
seed.page
.set_block_prop(
"sc-text",
"prop:scale",
SessionValue::Any(Any::Float64(2.0_f64.into())),
now_ms,
)
.expect("text scale");
let now_ms = seed.tick();
seed.page
.set_block_prop(
"sc-text",
"prop:hasMaxWidth",
SessionValue::Any(Any::True),
now_ms,
)
.expect("hasMaxWidth");
seed.paragraph(
"sc-text-p",
ParagraphType::Text,
"Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu",
"sc-text",
)
.expect("text paragraph");
let session = open(
1280,
800,
PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
);
session.view(|view, cx| view.set_document(doc, cx));
let _ = session.frame();
let (note_w, text_w, text_lines) = session.view(|view, _| {
let note_layout = view
.edgeless
.cached_note_layout("sc-note")
.expect("cached note layout");
let text_layout = view
.edgeless
.cached_text_layout("sc-text")
.expect("cached text layout");
let lines = text_layout
.block("sc-text-p")
.and_then(|b| b.body.text.as_ref())
.map_or(0, |t| t.layout.line_count());
(note_layout.width, text_layout.width, lines)
});
assert!(
(note_w - (400.0 / 2.0 - 2.0 * edgeless_canvas::NOTE_CARD_PADDING)).abs() < 0.01,
"expected Note logical width 152.0, got {note_w}"
);
assert!(
(text_w - 200.0).abs() < 0.01,
"expected EdgelessText logical width 200.0, got {text_w}"
);
assert!(
text_lines >= 2,
"expected EdgelessText at 200px logical width to wrap into >=2 lines, got {text_lines}"
);
// Subsequent camera pan + zoom must trigger zero BlockFlow relayouts.
for zoom in [0.5_f32, 1.5, 2.0] {
session.view(|view, cx| view.set_edgeless_camera(-20.0, -20.0, zoom, cx));
let _ = session.frame();
let relayouts = session.view(|view, _| view.edgeless_last_frame_relayouts());
assert_eq!(
relayouts, 0,
"camera zoom={zoom} must cause 0 BlockFlow relayouts"
);
}
}
#[test]
fn edgeless_collapsed_note_clips_overflow_content_to_stored_height() {
let mut doc = DocState::new("collapse-note", client_id_from_seed(0x504)).expect("state");
doc.workspace.initialize_meta().expect("meta");
doc.workspace
.create_page(HOME_PAGE_ID, "Collapsed Note", 1)
.expect("page");
let page = doc.workspace.ensure_page(HOME_PAGE_ID).expect("page");
let mut seed = ShowcaseSeed { page, now_ms: 0 };
seed.add(
"c-page",
BlockSpec::Page {
title: "Collapsed Note".to_string(),
},
None,
)
.expect("page");
seed.add(
"c-note",
BlockSpec::Note {
xywh: Some("[40,40,420,120]".to_string()),
},
Some("c-page"),
)
.expect("note");
let mut edgeless_map = AHashMap::default();
edgeless_map.insert("collapse".to_string(), Any::True);
edgeless_map.insert(
"collapsedHeight".to_string(),
Any::Float64(120.0_f64.into()),
);
let now_ms = seed.tick();
seed.page
.set_block_prop(
"c-note",
"prop:edgeless",
SessionValue::Any(Any::Object(Box::new(edgeless_map))),
now_ms,
)
.expect("collapse prop");
for i in 0..12 {
seed.paragraph(
&format!("c-p-{i}"),
ParagraphType::Text,
"Overflowing dark text line that must be clipped below collapsed height",
"c-note",
)
.expect("paragraph");
}
let session = open(
1280,
800,
PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
);
session.view(|view, cx| {
view.set_document(doc, cx);
view.set_edgeless_camera(0.0, 0.0, 1.0, cx);
});
let (snap, img) = session.frame();
let note_bounds = snap.elements["edgeless.note.c-note"].bounds;
assert!(
(note_bounds.height - 120.0).abs() < 1.0,
"collapsed note height must stay clamped to 120, got {}",
note_bounds.height
);
// Region well below the 120px collapsed card (and its drop shadow) must contain no dark text ink.
let check_top = (TOPBAR_HEIGHT + 40.0 + 120.0 + 36.0) as u32;
let check_bottom = (check_top + 160).min(img.height());
let mut leaked_dark = 0_u64;
for y in check_top..check_bottom {
for x in 60..440 {
let p = img.get_pixel(x, y);
if p[0] < 160 && p[1] < 160 && p[2] < 160 {
leaked_dark += 1;
}
}
}
assert_eq!(
leaked_dark, 0,
"collapsed note leaked {leaked_dark} dark text pixels below its clamped height"
);
}
}
@@ -13,9 +13,11 @@
//! module feeds it input and carries each edit out through the editor's document session
//! as one undo step.
//!
//! Popovers are placed by the pure [`place_popover`]. A popover that is fully transparent
//! is not mounted at all, and one that is fading out carries no handlers, so nothing
//! invisible can be clicked.
//! Popovers are placed by the pure [`place_popover`]. Opening popovers mount on frame 1
//! with opacity clamped to at least `0.01` so interactive controls are immediately clickable
//! without triggering `zero-opacity-hit-through`; a popover that is fully closed is not
//! mounted at all, and one that is fading out carries no handlers, so nothing invisible can
//! be clicked.
use std::{collections::HashMap, ops::Range, time::Duration};
@@ -2456,10 +2458,15 @@ impl Overlays {
let menu = self.slash.as_mut()?;
menu.rect = None;
let progress = menu.presence.progress(now_ms);
if progress <= 0.0 {
if menu.presence.closing && progress <= 0.0 {
return None;
}
let interactive = !menu.presence.closing;
let progress = if interactive {
progress.max(0.01)
} else {
progress
};
let anchor_world = menu
.anchor_world
.or_else(|| caret_world_rect(scene.layout, &menu.block_id, menu.utf16_offset))?;
@@ -2711,10 +2718,15 @@ impl Overlays {
let toolbar = self.toolbar.as_mut()?;
toolbar.rect = None;
let progress = toolbar.presence.progress(now_ms);
if progress <= 0.0 {
if toolbar.presence.closing && progress <= 0.0 {
return None;
}
let interactive = !toolbar.presence.closing;
let progress = if interactive {
progress.max(0.01)
} else {
progress
};
if !scene
.page_viewport()
.intersects(&toolbar.selection.anchor_world)
@@ -4633,9 +4645,11 @@ mod tests {
utf16_offset: 0,
anchor: None,
});
// Fully transparent at the start of its fade, the menu is not mounted at all.
// Opening mounts on its first frame with live hitboxes and minimal non-zero opacity.
let first = session.frame();
assert!(!first.elements.contains_key("overlay.slash_menu"));
let first_menu = element(&first, "overlay.slash_menu");
assert!(first_menu.opacity > 0.0 && first_menu.opacity <= 0.02);
assert!(first_menu.interactive);
let opened = session.settle();
assert_no_violations(&opened, "slash menu");
let menu = element(&opened, "overlay.slash_menu");
@@ -693,6 +693,7 @@ pub(crate) enum BackgroundTag {
LinearGradient = 1,
PatternSlash = 2,
Checkerboard = 3,
DotGrid = 4,
}
/// A color space for color interpolation.
@@ -751,6 +752,14 @@ impl std::fmt::Debug for Background {
"Checkerboard({:?}, {})",
self.solid, self.gradient_angle_or_pattern_height
),
BackgroundTag::DotGrid => write!(
f,
"DotGrid({:?}, {:?}, gap={}, r={})",
self.solid,
self.colors[0].color,
self.gradient_angle_or_pattern_height,
self.colors[0].percentage
),
}
}
}
@@ -882,6 +891,51 @@ impl Background {
background
}
/// Creates a procedural single-draw-call dot-grid background.
pub fn dot_grid(
bg_color: Hsla,
dot_color: Hsla,
gap_px: f32,
dot_radius_px: f32,
phase_x_px: f32,
phase_y_px: f32,
) -> Background {
Background {
tag: BackgroundTag::DotGrid,
color_space: ColorSpace::Srgb,
solid: bg_color,
gradient_angle_or_pattern_height: gap_px,
colors: [
LinearColorStop {
color: dot_color,
percentage: dot_radius_px,
},
LinearColorStop {
color: Hsla {
h: phase_x_px,
s: phase_y_px,
l: 0.0,
a: 0.0,
},
percentage: 0.0,
},
],
pad: 0,
}
}
/// Scales pixel-space parameters of procedural backgrounds by `scale_factor`.
pub fn scale(&self, scale_factor: f32) -> Self {
let mut bg = *self;
if bg.tag == BackgroundTag::DotGrid {
bg.gradient_angle_or_pattern_height *= scale_factor;
bg.colors[0].percentage *= scale_factor;
bg.colors[1].color.h *= scale_factor;
bg.colors[1].color.s *= scale_factor;
}
bg
}
/// Returns whether the background color is transparent.
pub fn is_transparent(&self) -> bool {
match self.tag {
@@ -889,6 +943,9 @@ impl Background {
BackgroundTag::LinearGradient => self.colors.iter().all(|c| c.color.is_transparent()),
BackgroundTag::PatternSlash => self.solid.is_transparent(),
BackgroundTag::Checkerboard => self.solid.is_transparent(),
BackgroundTag::DotGrid => {
self.solid.is_transparent() && self.colors[0].color.is_transparent()
}
}
}
}
@@ -122,6 +122,26 @@ pub(crate) struct GlyphRunRendering {
dilation: u8,
}
/// Quantize a non-unit transform scale into quarter-octave buckets so zoomed text
/// stays crisp without re-laying out paragraphs.
#[inline]
pub(crate) fn glyph_zoom_bucket(transform: &TransformationMatrix) -> Option<f32> {
let s = transform.rotation_scale[0][0]
.hypot(transform.rotation_scale[1][0])
.max(1e-3);
if (s - 1.0).abs() > 1e-3 {
Some(
2.0_f32
.powf((4.0 * s.log2()).round() / 4.0)
.clamp(0.25, 8.0),
)
} else {
None
}
}
/// [`Window::paint_glyph`], for a glyph in a run whose rendering and
/// snapped content mask the caller has already worked out.
impl Window {
/// How the glyphs of a run in `font_id` at `font_size` and in `color` are
/// rendered, which [`Window::paint_glyph_in_run`] takes so that painting a
@@ -157,16 +177,36 @@ impl Window {
let element_opacity = self.element_opacity();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let is_unit = transformation == TransformationMatrix::unit();
let zoom_bucket = glyph_zoom_bucket(&transformation);
let (integer_origin, subpixel_variant) = quantize_origin(glyph_origin);
let GlyphRunRendering {
subpixel_rendering,
dilation,
} = rendering;
let (integer_origin, subpixel_variant, raster_font_size, subpixel_rendering) =
if let Some(bucket) = zoom_bucket {
(
glyph_origin,
Point::default(),
Pixels(font_size.0 * bucket),
false,
)
} else {
let (integer_origin, subpixel_variant) = quantize_origin(glyph_origin);
(
integer_origin,
subpixel_variant,
font_size,
is_unit && subpixel_rendering,
)
};
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
font_size: raster_font_size,
subpixel_variant,
scale_factor,
is_emoji: false,
@@ -182,7 +222,11 @@ impl Window {
(raster_bounds, None, None)
}
};
let sprite_origin = integer_origin + raster_bounds.origin.map(Into::into);
let inv_bucket = 1.0 / zoom_bucket.unwrap_or(1.0);
let sprite_origin = Point::new(
ScaledPixels(integer_origin.x.0 + raster_bounds.origin.x.0 as f32 * inv_bucket),
ScaledPixels(integer_origin.y.0 + raster_bounds.origin.y.0 as f32 * inv_bucket),
);
if !raster_bounds.is_zero() {
let tile = match tile {
Some(tile) => tile,
@@ -190,7 +234,15 @@ impl Window {
// where the sprite's size is known, drop it before looking up
// its tile.
None if sprite_size.is_some_and(|size| {
Bounds::new(sprite_origin, size.map(Into::into))
let local_bounds = Bounds::new(
sprite_origin,
Size::new(
ScaledPixels(size.width.0 as f32 * inv_bucket),
ScaledPixels(size.height.0 as f32 * inv_bucket),
),
);
transformation
.map_bounds(local_bounds)
.intersect(&content_mask.bounds)
.is_empty()
}) =>
@@ -211,7 +263,10 @@ impl Window {
};
let bounds = Bounds {
origin: sprite_origin,
size: tile.bounds.size.map(Into::into),
size: Size::new(
ScaledPixels(tile.bounds.size.width.0 as f32 * inv_bucket),
ScaledPixels(tile.bounds.size.height.0 as f32 * inv_bucket),
),
};
if subpixel_rendering {
@@ -222,7 +277,8 @@ impl Window {
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
transformation,
local_content_mask,
});
} else {
self.next_frame.scene.insert_primitive(MonochromeSprite {
@@ -232,7 +288,8 @@ impl Window {
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
transformation,
local_content_mask,
});
}
}
@@ -248,6 +305,7 @@ impl Window {
pub(crate) struct LineGlyphPainter {
snapped_content_mask: ContentMask<ScaledPixels>,
content_mask: Bounds<Pixels>,
is_transformed: bool,
reach: GlyphReach,
run_rendering: Option<(FontId, Hsla, GlyphRunRendering)>,
}
@@ -257,6 +315,7 @@ impl LineGlyphPainter {
Self {
snapped_content_mask: window.snapped_content_mask(),
content_mask: window.content_mask().bounds,
is_transformed: window.paint_transformation() != TransformationMatrix::unit(),
reach: GlyphReach::UNSET,
run_rendering: None,
}
@@ -288,6 +347,9 @@ impl LineGlyphPainter {
baseline: Pixels,
mask: &Bounds<Pixels>,
) -> bool {
if self.is_transformed {
return true;
}
debug_assert_eq!(*mask, self.content_mask);
if !self.reach.is_for(line_glyph.size) {
self.reach = GlyphReach::new(line_glyph.size, &self.content_mask);
@@ -91,6 +91,9 @@ pub(crate) fn compile(scene: &mut Scene) {
padding: 0,
bounds: Default::default(),
},
transformation: crate::TransformationMatrix::unit(),
local_content_mask: crate::scene::unbounded_scaled_content_mask(),
pad2: [0; 2],
});
}
PaintOperation::Primitive(primitive) => stack
@@ -274,11 +274,14 @@ fn write_vertices(
.flat_map(|batch| &scene.paths[batch.paths.clone()])
.flat_map(|path| {
let bounds = path.bounds.intersect(&path.content_mask.bounds);
let local_content_mask = path.local_content_mask;
path.vertices.iter().map(move |v| PathRasterizationVertex {
xy_position: v.xy_position,
st_position: v.st_position,
color: path.color,
bounds,
local_position: v.local_position,
local_content_mask,
})
});
// The plan counted these same vertices, so the iterator yields exactly
@@ -164,8 +164,15 @@ pub struct PathRasterizationVertex {
pub st_position: Point<f32>,
pub color: Background,
pub bounds: Bounds<ScaledPixels>,
pub local_position: Point<ScaledPixels>,
pub local_content_mask: ContentMask<ScaledPixels>,
}
const _: () = assert!(
std::mem::size_of::<PathRasterizationVertex>() == 128
&& std::mem::size_of::<PathRasterizationVertex>().is_multiple_of(16)
);
impl MetalRenderer {
/// Creates a new MetalRenderer with a CAMetalLayer for window-based rendering.
pub fn new(
@@ -992,6 +999,8 @@ impl MetalRenderer {
st_position: v.st_position,
color: path.color,
bounds: path.bounds.intersect(&path.content_mask.bounds),
local_position: v.local_position,
local_content_mask: path.local_content_mask,
}));
}
let vertex_instance_bindings = writer.write(&vertices)?;
@@ -44,9 +44,26 @@ struct GradientColor {
};
GradientColor prepare_fill_color(uint tag, uint color_space, Hsla solid, Hsla color0, Hsla color1);
float transform_scale(TransformationMatrix t) {
return max(length(float2(t.rotation_scale[0][0], t.rotation_scale[1][0])), 1e-4);
}
bool outside_local_mask(float2 pos, Bounds_ScaledPixels mask) {
return pos.x < mask.origin.x ||
pos.x > mask.origin.x + mask.size.width ||
pos.y < mask.origin.y ||
pos.y > mask.origin.y + mask.size.height;
}
float2 to_local_position(float2 unit_vertex, Bounds_ScaledPixels bounds) {
return unit_vertex * float2(bounds.size.width, bounds.size.height) +
float2(bounds.origin.x, bounds.origin.y);
}
struct QuadVertexOutput {
uint quad_id [[flat]];
float4 position [[position]];
float2 local_position;
float4 border_color [[flat]];
float4 background_solid [[flat]];
float4 background_color0 [[flat]];
@@ -57,6 +74,7 @@ struct QuadVertexOutput {
struct QuadFragmentInput {
uint quad_id [[flat]];
float4 position [[position]];
float2 local_position;
float4 border_color [[flat]];
float4 background_solid [[flat]];
float4 background_color0 [[flat]];
@@ -73,10 +91,11 @@ vertex QuadVertexOutput quad_vertex(uint unit_vertex_id [[vertex_id]],
[[buffer(QuadInputIndex_ViewportSize)]]) {
float2 unit_vertex = unit_vertices[unit_vertex_id];
Quad quad = quads[quad_id];
float4 device_position =
to_device_position(unit_vertex, quad.bounds, viewport_size);
float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds,
quad.content_mask.bounds);
float2 local_position = to_local_position(unit_vertex, quad.bounds);
float4 device_position = to_device_position_transformed(
unit_vertex, quad.bounds, quad.transformation, viewport_size);
float4 clip_distance = distance_from_clip_rect_transformed(
unit_vertex, quad.bounds, quad.content_mask.bounds, quad.transformation);
float4 border_color = hsla_to_rgba(quad.border_color);
GradientColor gradient = prepare_fill_color(
@@ -90,6 +109,7 @@ vertex QuadVertexOutput quad_vertex(uint unit_vertex_id [[vertex_id]],
return QuadVertexOutput{
quad_id,
device_position,
local_position,
border_color,
gradient.solid,
gradient.color0,
@@ -101,7 +121,10 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]],
constant Quad *quads
[[buffer(QuadInputIndex_Quads)]]) {
Quad quad = quads[input.quad_id];
float4 background_color = fill_color(quad.background, input.position.xy, quad.bounds,
if (outside_local_mask(input.local_position, quad.local_content_mask.bounds)) {
return float4(0.0);
}
float4 background_color = fill_color(quad.background, input.local_position, quad.bounds,
input.background_solid, input.background_color0, input.background_color1);
bool unrounded = quad.corner_radii.top_left == 0.0 &&
@@ -109,8 +132,12 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]],
quad.corner_radii.top_right == 0.0 &&
quad.corner_radii.bottom_right == 0.0;
// Fast path when the quad is not rounded and doesn't have any border
if (quad.border_widths.top == 0.0 &&
bool axis_aligned = fabs(quad.transformation.rotation_scale[0][1]) <= 1e-5 &&
fabs(quad.transformation.rotation_scale[1][0]) <= 1e-5;
// Fast path when the quad is axis-aligned, not rounded, and doesn't have any border
if (axis_aligned &&
quad.border_widths.top == 0.0 &&
quad.border_widths.left == 0.0 &&
quad.border_widths.right == 0.0 &&
quad.border_widths.bottom == 0.0 &&
@@ -118,14 +145,15 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]],
return background_color;
}
float scale = transform_scale(quad.transformation);
float2 size = float2(quad.bounds.size.width, quad.bounds.size.height);
float2 half_size = size / 2.0;
float2 point = input.position.xy - float2(quad.bounds.origin.x, quad.bounds.origin.y);
float2 point = input.local_position - float2(quad.bounds.origin.x, quad.bounds.origin.y);
float2 center_to_point = point - half_size;
// Signed distance field threshold for inclusion of pixels. 0.5 is the
// minimum distance between the center of the pixel and the edge.
const float antialias_threshold = 0.5;
// Signed distance field threshold for inclusion of pixels. 0.5 device pixels
// expressed in local coordinates.
float antialias_threshold = 0.5 / scale;
// Radius of the nearest corner
float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
@@ -390,10 +418,10 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]],
// between the two as we slide inside the background.
float4 blended_border = over(background_color, border_color);
color = mix(background_color, blended_border,
saturate(antialias_threshold - inner_sdf));
saturate(0.5 - inner_sdf * scale));
}
return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf));
return color * float4(1.0, 1.0, 1.0, saturate(0.5 - outer_sdf * scale));
}
// Returns the dash velocity of a corner given the dash velocity of the two
@@ -448,6 +476,7 @@ float quarter_ellipse_sdf(float2 point, float2 radii) {
struct ShadowVertexOutput {
float4 position [[position]];
float2 local_position;
float4 color [[flat]];
uint shadow_id [[flat]];
float clip_distance [[clip_distance]][4];
@@ -455,6 +484,7 @@ struct ShadowVertexOutput {
struct ShadowFragmentInput {
float4 position [[position]];
float2 local_position;
float4 color [[flat]];
uint shadow_id [[flat]];
};
@@ -481,14 +511,16 @@ vertex ShadowVertexOutput shadow_vertex(
bounds.size.height += 2. * margin;
}
float4 device_position =
to_device_position(unit_vertex, bounds, viewport_size);
float4 clip_distance =
distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask.bounds);
float2 local_position = to_local_position(unit_vertex, bounds);
float4 device_position = to_device_position_transformed(
unit_vertex, bounds, shadow.transformation, viewport_size);
float4 clip_distance = distance_from_clip_rect_transformed(
unit_vertex, bounds, shadow.content_mask.bounds, shadow.transformation);
float4 color = hsla_to_rgba(shadow.color);
return ShadowVertexOutput{
device_position,
local_position,
color,
shadow_id,
{clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
@@ -498,12 +530,16 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]],
constant Shadow *shadows
[[buffer(ShadowInputIndex_Shadows)]]) {
Shadow shadow = shadows[input.shadow_id];
if (outside_local_mask(input.local_position, shadow.local_content_mask.bounds)) {
return float4(0.0);
}
float scale = transform_scale(shadow.transformation);
float2 origin = float2(shadow.bounds.origin.x, shadow.bounds.origin.y);
float2 size = float2(shadow.bounds.size.width, shadow.bounds.size.height);
float2 half_size = size / 2.;
float2 center = origin + half_size;
float2 point = input.position.xy - center;
float2 point = input.local_position - center;
float corner_radius;
if (point.x < 0.) {
if (point.y < 0.) {
@@ -521,8 +557,8 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]],
float alpha;
if (shadow.blur_radius == 0.) {
float distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii);
alpha = saturate(0.5 - distance);
float distance = quad_sdf(input.local_position, shadow.bounds, shadow.corner_radii);
alpha = saturate(0.5 - distance * scale);
} else {
// The signal is only non-zero in a limited range, so don't waste samples
float low = point.y - half_size.y;
@@ -546,9 +582,9 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]],
// The inset shadow is the complement of the (blurred) hole rect, clipped to the element.
// `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0.
alpha = 1. - alpha;
float element_distance = quad_sdf(input.position.xy, shadow.element_bounds,
float element_distance = quad_sdf(input.local_position, shadow.element_bounds,
shadow.element_corner_radii);
alpha *= saturate(0.5 - element_distance);
alpha *= saturate(0.5 - element_distance * scale);
}
return input.color * float4(1., 1., 1., alpha);
@@ -556,6 +592,7 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]],
struct UnderlineVertexOutput {
float4 position [[position]];
float2 local_position;
float4 color [[flat]];
uint underline_id [[flat]];
float clip_distance [[clip_distance]][4];
@@ -563,6 +600,7 @@ struct UnderlineVertexOutput {
struct UnderlineFragmentInput {
float4 position [[position]];
float2 local_position;
float4 color [[flat]];
uint underline_id [[flat]];
};
@@ -575,13 +613,15 @@ vertex UnderlineVertexOutput underline_vertex(
[[buffer(ShadowInputIndex_ViewportSize)]]) {
float2 unit_vertex = unit_vertices[unit_vertex_id];
Underline underline = underlines[underline_id];
float4 device_position =
to_device_position(unit_vertex, underline.bounds, viewport_size);
float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds,
underline.content_mask.bounds);
float2 local_position = to_local_position(unit_vertex, underline.bounds);
float4 device_position = to_device_position_transformed(
unit_vertex, underline.bounds, underline.transformation, viewport_size);
float4 clip_distance = distance_from_clip_rect_transformed(
unit_vertex, underline.bounds, underline.content_mask.bounds, underline.transformation);
float4 color = hsla_to_rgba(underline.color);
return UnderlineVertexOutput{
device_position,
local_position,
color,
underline_id,
{clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
@@ -594,12 +634,16 @@ fragment float4 underline_fragment(UnderlineFragmentInput input [[stage_in]],
const float WAVE_HEIGHT_RATIO = 0.8;
Underline underline = underlines[input.underline_id];
if (outside_local_mask(input.local_position, underline.local_content_mask.bounds)) {
return float4(0.0);
}
if (underline.wavy) {
float scale = transform_scale(underline.transformation);
float half_thickness = underline.thickness * 0.5;
float2 origin =
float2(underline.bounds.origin.x, underline.bounds.origin.y);
float2 st = ((input.position.xy - origin) / underline.bounds.size.height) -
float2 st = ((input.local_position - origin) / underline.bounds.size.height) -
float2(0., 0.5);
float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.height;
float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.height;
@@ -611,7 +655,7 @@ fragment float4 underline_fragment(UnderlineFragmentInput input [[stage_in]],
float distance_from_top_border = distance_in_pixels - half_thickness;
float distance_from_bottom_border = distance_in_pixels + half_thickness;
float alpha = saturate(
0.5 - max(-distance_from_bottom_border, distance_from_top_border));
0.5 - max(-distance_from_bottom_border, distance_from_top_border) * scale);
return input.color * float4(1., 1., 1., alpha);
} else {
return input.color;
@@ -623,6 +667,7 @@ struct MonochromeSpriteVertexOutput {
float2 tile_position;
float4 color [[flat]];
float4 clip_distance;
float4 local_clip_distance;
};
struct MonochromeSpriteFragmentInput {
@@ -630,6 +675,7 @@ struct MonochromeSpriteFragmentInput {
float2 tile_position;
float4 color [[flat]];
float4 clip_distance;
float4 local_clip_distance;
};
vertex MonochromeSpriteVertexOutput monochrome_sprite_vertex(
@@ -646,20 +692,23 @@ vertex MonochromeSpriteVertexOutput monochrome_sprite_vertex(
to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation, viewport_size);
float4 clip_distance = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds,
sprite.content_mask.bounds, sprite.transformation);
float4 local_clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds,
sprite.local_content_mask.bounds);
float2 tile_position = to_tile_position(unit_vertex, sprite.tile, atlas_size);
float4 color = hsla_to_rgba(sprite.color);
return MonochromeSpriteVertexOutput{
device_position,
tile_position,
color,
{clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
clip_distance,
local_clip_distance};
}
fragment float4 monochrome_sprite_fragment(
MonochromeSpriteFragmentInput input [[stage_in]],
constant MonochromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]],
texture2d<float> atlas_texture [[texture(SpriteInputIndex_AtlasTexture)]]) {
if (any(input.clip_distance < float4(0.0))) {
if (any(input.clip_distance < float4(0.0)) || any(input.local_clip_distance < float4(0.0))) {
return float4(0.0);
}
@@ -674,6 +723,7 @@ fragment float4 monochrome_sprite_fragment(
struct PolychromeSpriteVertexOutput {
float4 position [[position]];
float2 local_position;
float2 tile_position;
uint sprite_id [[flat]];
float clip_distance [[clip_distance]][4];
@@ -681,6 +731,7 @@ struct PolychromeSpriteVertexOutput {
struct PolychromeSpriteFragmentInput {
float4 position [[position]];
float2 local_position;
float2 tile_position;
uint sprite_id [[flat]];
};
@@ -696,13 +747,15 @@ vertex PolychromeSpriteVertexOutput polychrome_sprite_vertex(
float2 unit_vertex = unit_vertices[unit_vertex_id];
PolychromeSprite sprite = sprites[sprite_id];
float4 device_position =
to_device_position(unit_vertex, sprite.bounds, viewport_size);
float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds,
sprite.content_mask.bounds);
float2 local_position = to_local_position(unit_vertex, sprite.bounds);
float4 device_position = to_device_position_transformed(
unit_vertex, sprite.bounds, sprite.transformation, viewport_size);
float4 clip_distance = distance_from_clip_rect_transformed(
unit_vertex, sprite.bounds, sprite.content_mask.bounds, sprite.transformation);
float2 tile_position = to_tile_position(unit_vertex, sprite.tile, atlas_size);
return PolychromeSpriteVertexOutput{
device_position,
local_position,
tile_position,
sprite_id,
{clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
@@ -713,12 +766,16 @@ fragment float4 polychrome_sprite_fragment(
constant PolychromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]],
texture2d<float> atlas_texture [[texture(SpriteInputIndex_AtlasTexture)]]) {
PolychromeSprite sprite = sprites[input.sprite_id];
if (outside_local_mask(input.local_position, sprite.local_content_mask.bounds)) {
return float4(0.0);
}
constexpr sampler atlas_texture_sampler(mag_filter::linear,
min_filter::linear);
float4 sample =
atlas_texture.sample(atlas_texture_sampler, input.tile_position);
float scale = transform_scale(sprite.transformation);
float distance =
quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
quad_sdf(input.local_position, sprite.bounds, sprite.corner_radii);
float4 color = sample;
if (sprite.grayscale) {
@@ -727,7 +784,7 @@ fragment float4 polychrome_sprite_fragment(
color.g = grayscale;
color.b = grayscale;
}
color.a *= sprite.opacity * saturate(0.5 - distance);
color.a *= sprite.opacity * saturate(0.5 - distance * scale);
return color;
}
@@ -735,6 +792,7 @@ struct PathRasterizationVertexOutput {
float4 position [[position]];
float2 st_position;
uint vertex_id [[flat]];
float4 local_clip_distance;
float clip_rect_distance [[clip_distance]][4];
};
@@ -742,6 +800,7 @@ struct PathRasterizationFragmentInput {
float4 position [[position]];
float2 st_position;
uint vertex_id [[flat]];
float4 local_clip_distance;
};
vertex PathRasterizationVertexOutput path_rasterization_vertex(
@@ -756,10 +815,18 @@ vertex PathRasterizationVertexOutput path_rasterization_vertex(
0.,
1.
);
Bounds_ScaledPixels lm = v.local_content_mask.bounds;
float4 local_clip = float4(
v.local_position.x - lm.origin.x,
lm.origin.x + lm.size.width - v.local_position.x,
v.local_position.y - lm.origin.y,
lm.origin.y + lm.size.height - v.local_position.y
);
return PathRasterizationVertexOutput{
position,
float2(v.st_position.x, v.st_position.y),
vertex_id,
local_clip,
{
v.xy_position.x - v.bounds.origin.x,
v.bounds.origin.x + v.bounds.size.width - v.xy_position.x,
@@ -775,6 +842,9 @@ fragment float4 path_rasterization_fragment(
) {
float2 dx = dfdx(input.st_position);
float2 dy = dfdy(input.st_position);
if (any(input.local_clip_distance < float4(0.0))) {
return float4(0.0);
}
PathRasterizationVertex v = vertices[input.vertex_id];
Background background = v.color;
@@ -1155,6 +1225,9 @@ GradientColor prepare_fill_color(uint tag, uint color_space, Hsla solid,
GradientColor out;
if (tag == 0 || tag == 2 || tag == 3) {
out.solid = hsla_to_rgba(solid);
} else if (tag == 4) {
out.solid = hsla_to_rgba(solid);
out.color0 = hsla_to_rgba(color0);
} else if (tag == 1) {
out.color0 = hsla_to_rgba(color0);
out.color1 = hsla_to_rgba(color1);
@@ -1273,6 +1346,18 @@ float4 fill_color(Background background,
color.a *= saturate(should_be_colored);
break;
}
case 4: {
// procedural dot grid
float gap = max(background.gradient_angle_or_pattern_height, 1.0);
float dot_radius = max(background.colors[0].percentage, 0.5);
float2 phase = float2(background.colors[1].color.h, background.colors[1].color.s);
float2 rel = position - float2(bounds.origin.x, bounds.origin.y) - phase;
float2 cell = rel - floor(rel / gap + 0.5) * gap;
float alpha = clamp(0.5 - (length(cell) - dot_radius), 0.0, 1.0);
float4 dot = float4(color0.rgb, color0.a * alpha);
color = dot.a > 0.0 ? over(solid_color, dot) : solid_color;
break;
}
}
return color;
@@ -351,12 +351,15 @@ fn plan_paths(
let mut union = first_path.clipped_bounds();
for path in paths {
let bounds = path.clipped_bounds();
let local_content_mask = path.local_content_mask;
union = union.union(&bounds);
vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex {
xy_position: v.xy_position,
st_position: v.st_position,
color: path.color,
bounds,
local_position: v.local_position,
local_content_mask,
}));
}
@@ -167,6 +167,21 @@ struct TransformationMatrix {
translation: vec2<f32>,
}
fn transform_scale(transform: TransformationMatrix) -> f32 {
return max(length(vec2<f32>(transform.rotation_scale[0][0], transform.rotation_scale[1][0])), 1e-4);
}
fn to_local_position(unit_vertex: vec2<f32>, bounds: Bounds) -> vec2<f32> {
return unit_vertex * bounds.size + bounds.origin;
}
fn outside_local_mask(pos: vec2<f32>, mask: Bounds) -> bool {
return pos.x < mask.origin.x ||
pos.x > mask.origin.x + mask.size.x ||
pos.y < mask.origin.y ||
pos.y > mask.origin.y + mask.size.y;
}
fn to_device_position_impl(position: vec2<f32>) -> vec4<f32> {
let device_position = position / globals.viewport_size * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0);
return vec4<f32>(device_position, 0.0, 1.0);
@@ -407,6 +422,9 @@ fn prepare_gradient_color(tag: u32, color_space: u32,
if (tag == 0u || tag == 2u || tag == 3u) {
result.solid = hsla_to_rgba(solid);
} else if (tag == 4u) {
result.solid = hsla_to_rgba(solid);
result.color0 = hsla_to_rgba(colors[0].color);
} else if (tag == 1u) {
// The hsla_to_rgba is returns a linear sRGB color
result.color0 = hsla_to_rgba(colors[0].color);
@@ -509,6 +527,21 @@ fn gradient_color(background: Background, position: vec2<f32>, bounds: Bounds,
background_color = solid_color;
background_color.a *= saturate(should_be_colored);
}
case 4u: {
// procedural dot grid
let gap = max(background.gradient_angle_or_pattern_height, 1.0);
let dot_radius = max(background.colors[0].percentage, 0.5);
let phase = vec2<f32>(background.colors[1].color.h, background.colors[1].color.s);
let rel = position - bounds.origin - phase;
let cell = rel - floor(rel / gap + 0.5) * gap;
let alpha = clamp(0.5 - (length(cell) - dot_radius), 0.0, 1.0);
let dot_color = vec4<f32>(color0.rgb, color0.a * alpha);
if (dot_color.a > 0.0) {
background_color = over(solid_color, dot_color);
} else {
background_color = solid_color;
}
}
}
return background_color;
@@ -525,6 +558,9 @@ struct Quad {
border_color: Hsla,
corner_radii: Corners,
border_widths: Edges,
transformation: TransformationMatrix,
local_content_mask: Bounds,
pad: vec2<u32>,
}
struct QuadVarying {
@@ -536,6 +572,7 @@ struct QuadVarying {
@location(3) @interpolate(flat) background_solid: vec4<f32>,
@location(4) @interpolate(flat) background_color0: vec4<f32>,
@location(5) @interpolate(flat) background_color1: vec4<f32>,
@location(6) local_position: vec2<f32>,
}
@vertex
@@ -544,7 +581,8 @@ fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) insta
let quad = load_quad(instance_id);
var out = QuadVarying();
out.position = to_device_position(unit_vertex, quad.bounds);
out.position = to_device_position_transformed(unit_vertex, quad.bounds, quad.transformation);
out.local_position = to_local_position(unit_vertex, quad.bounds);
let gradient = prepare_gradient_color(
quad.background.tag,
@@ -557,7 +595,7 @@ fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) insta
out.background_color1 = gradient.color1;
out.border_color = hsla_to_rgba(quad.border_color);
out.quad_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, quad.bounds, quad.content_mask, quad.transformation);
return out;
}
@@ -569,8 +607,11 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
}
let quad = load_quad(input.quad_id);
if (outside_local_mask(input.local_position, quad.local_content_mask)) {
return vec4<f32>(0.0);
}
let background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
let background_color = gradient_color(quad.background, input.local_position, quad.bounds,
input.background_solid, input.background_color0, input.background_color1);
let unrounded = quad.corner_radii.top_left == 0.0 &&
@@ -578,8 +619,12 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
quad.corner_radii.top_right == 0.0 &&
quad.corner_radii.bottom_right == 0.0;
// Fast path when the quad is not rounded and doesn't have any border
if (quad.border_widths.top == 0.0 &&
let axis_aligned = abs(quad.transformation.rotation_scale[0][1]) <= 1e-5 &&
abs(quad.transformation.rotation_scale[1][0]) <= 1e-5;
// Fast path when the quad is axis-aligned, not rounded, and doesn't have any border
if (axis_aligned &&
quad.border_widths.top == 0.0 &&
quad.border_widths.left == 0.0 &&
quad.border_widths.right == 0.0 &&
quad.border_widths.bottom == 0.0 &&
@@ -587,14 +632,15 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
return blend_color(background_color, 1.0);
}
let scale = transform_scale(quad.transformation);
let size = quad.bounds.size;
let half_size = size / 2.0;
let point = input.position.xy - quad.bounds.origin;
let point = input.local_position - quad.bounds.origin;
let center_to_point = point - half_size;
// Signed distance field threshold for inclusion of pixels. 0.5 is the
// minimum distance between the center of the pixel and the edge.
let antialias_threshold = 0.5;
// Signed distance field threshold for inclusion of pixels. 0.5 device pixels
// expressed in local coordinates.
let antialias_threshold = 0.5 / scale;
// Radius of the nearest corner
let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
@@ -886,10 +932,10 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
// between the two as we slide inside the background.
let blended_border = over(background_color, border_color);
color = mix(background_color, blended_border,
saturate(antialias_threshold - inner_sdf));
saturate(0.5 - inner_sdf * scale));
}
return blend_color(color, saturate(antialias_threshold - outer_sdf));
return blend_color(color, saturate(0.5 - outer_sdf * scale));
}
// Returns the dash velocity of a corner given the dash velocity of the two
@@ -962,12 +1008,16 @@ struct Shadow {
// 0 = drop shadow, 1 = inset shadow.
inset: u32,
pad: u32, // align to 8 bytes
transformation: TransformationMatrix,
local_content_mask: Bounds,
pad2: vec2<u32>,
}
struct ShadowVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) color: vec4<f32>,
@location(1) @interpolate(flat) shadow_id: u32,
@location(2) local_position: vec2<f32>,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@@ -989,10 +1039,11 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins
}
var out = ShadowVarying();
out.position = to_device_position(unit_vertex, geometry);
out.position = to_device_position_transformed(unit_vertex, geometry, shadow.transformation);
out.local_position = to_local_position(unit_vertex, geometry);
out.color = hsla_to_rgba(shadow.color);
out.shadow_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, geometry, shadow.content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, geometry, shadow.content_mask, shadow.transformation);
return out;
}
@@ -1004,16 +1055,20 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
}
let shadow = load_shadow(input.shadow_id);
if (outside_local_mask(input.local_position, shadow.local_content_mask)) {
return vec4<f32>(0.0);
}
let scale = transform_scale(shadow.transformation);
let half_size = shadow.bounds.size / 2.0;
let center = shadow.bounds.origin + half_size;
let center_to_point = input.position.xy - center;
let center_to_point = input.local_position - center;
let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii);
var alpha: f32;
if (shadow.blur_radius == 0.0) {
let distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii);
alpha = saturate(0.5 - distance);
let distance = quad_sdf(input.local_position, shadow.bounds, shadow.corner_radii);
alpha = saturate(0.5 - distance * scale);
} else {
// The signal is only non-zero in a limited range, so don't waste samples
let low = center_to_point.y - half_size.y;
@@ -1037,9 +1092,9 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
// The inset shadow is the complement of the (blurred) hole rect, clipped to the element.
// `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0.
alpha = 1.0 - alpha;
let element_distance = quad_sdf(input.position.xy, shadow.element_bounds,
let element_distance = quad_sdf(input.local_position, shadow.element_bounds,
shadow.element_corner_radii);
alpha *= saturate(0.5 - element_distance);
alpha *= saturate(0.5 - element_distance * scale);
}
return blend_color(input.color, alpha);
@@ -1052,6 +1107,8 @@ struct PathRasterizationVertex {
st_position: vec2<f32>,
color: Background,
bounds: Bounds,
local_position: vec2<f32>,
local_content_mask: Bounds,
}
@@ -1060,6 +1117,7 @@ struct PathRasterizationVarying {
@builtin(position) position: vec4<f32>,
@location(0) st_position: vec2<f32>,
@location(1) @interpolate(flat) vertex_id: u32,
@location(2) local_clip_distances: vec4<f32>,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@@ -1072,6 +1130,7 @@ fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasteriza
out.position = to_device_position_impl(v.xy_position);
out.st_position = v.st_position;
out.vertex_id = vertex_id;
out.local_clip_distances = distance_from_clip_rect_impl(v.local_position, v.local_content_mask);
out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds);
return out;
}
@@ -1080,7 +1139,7 @@ fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasteriza
fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4<f32> {
let dx = dpdx(input.st_position);
let dy = dpdy(input.st_position);
if (any(input.clip_distances < vec4<f32>(0.0))) {
if (any(input.clip_distances < vec4<f32>(0.0)) || any(input.local_clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
@@ -1154,6 +1213,9 @@ struct Underline {
color: Hsla,
thickness: f32,
wavy: u32,
transformation: TransformationMatrix,
local_content_mask: Bounds,
pad2: vec2<u32>,
}
@@ -1161,6 +1223,7 @@ struct UnderlineVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) color: vec4<f32>,
@location(1) @interpolate(flat) underline_id: u32,
@location(2) local_position: vec2<f32>,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@@ -1171,10 +1234,11 @@ fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index)
let underline = load_underline(instance_id);
var out = UnderlineVarying();
out.position = to_device_position(unit_vertex, underline.bounds);
out.position = to_device_position_transformed(unit_vertex, underline.bounds, underline.transformation);
out.local_position = to_local_position(unit_vertex, underline.bounds);
out.color = hsla_to_rgba(underline.color);
out.underline_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, underline.bounds, underline.content_mask, underline.transformation);
return out;
}
@@ -1189,14 +1253,18 @@ fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
}
let underline = load_underline(input.underline_id);
if (outside_local_mask(input.local_position, underline.local_content_mask)) {
return vec4<f32>(0.0);
}
if (underline.wavy == 0u)
{
return blend_color(input.color, input.color.a);
}
let scale = transform_scale(underline.transformation);
let half_thickness = underline.thickness * 0.5;
let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
let st = (input.local_position - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
let frequency = M_PI_F * WAVE_FREQUENCY * underline.thickness / underline.bounds.size.y;
let amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
@@ -1206,7 +1274,7 @@ fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
let distance_in_pixels = distance * underline.bounds.size.y;
let distance_from_top_border = distance_in_pixels - half_thickness;
let distance_from_bottom_border = distance_in_pixels + half_thickness;
let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border));
let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border) * scale);
return blend_color(input.color, alpha * input.color.a);
}
@@ -1220,6 +1288,7 @@ struct MonochromeSprite {
content_mask: Bounds,
color: Hsla,
transformation: TransformationMatrix,
local_content_mask: Bounds,
}
@@ -1227,6 +1296,7 @@ struct MonoSpriteVarying {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) @interpolate(flat) color: vec4<f32>,
@location(2) local_clip_distances: vec4<f32>,
@location(3) clip_distances: vec4<f32>,
}
@@ -1240,6 +1310,7 @@ fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.color = hsla_to_rgba(sprite.color);
out.local_clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.local_content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
return out;
}
@@ -1250,7 +1321,7 @@ fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4<f32> {
let alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, gamma_params.grayscale_enhanced_contrast, gamma_params.gamma_ratios);
// Alpha clip after using the derivatives.
if (any(input.clip_distances < vec4<f32>(0.0))) {
if (any(input.clip_distances < vec4<f32>(0.0)) || any(input.local_clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
@@ -1268,6 +1339,9 @@ struct PolychromeSprite {
bounds: Bounds,
content_mask: Bounds,
corner_radii: Corners,
transformation: TransformationMatrix,
local_content_mask: Bounds,
pad2: vec2<u32>,
}
@@ -1275,6 +1349,7 @@ struct PolySpriteVarying {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) @interpolate(flat) sprite_id: u32,
@location(2) local_position: vec2<f32>,
@location(3) clip_distances: vec4<f32>,
}
@@ -1284,10 +1359,11 @@ fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index
let sprite = load_poly_sprite(instance_id);
var out = PolySpriteVarying();
out.position = to_device_position(unit_vertex, sprite.bounds);
out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
out.local_position = to_local_position(unit_vertex, sprite.bounds);
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.sprite_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
return out;
}
@@ -1300,14 +1376,18 @@ fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4<f32> {
}
let sprite = load_poly_sprite(input.sprite_id);
let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
if (outside_local_mask(input.local_position, sprite.local_content_mask)) {
return vec4<f32>(0.0);
}
let scale = transform_scale(sprite.transformation);
let distance = quad_sdf(input.local_position, sprite.bounds, sprite.corner_radii);
var color = sample;
if (sprite.grayscale != 0u) {
let grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
color = vec4<f32>(vec3<f32>(grayscale), sample.a);
}
return blend_color(color, sprite.opacity * saturate(0.5 - distance));
return blend_color(color, sprite.opacity * saturate(0.5 - distance * scale));
}
// --- surfaces --- //
@@ -8,6 +8,7 @@ struct SubpixelSprite {
content_mask: Bounds,
color: Hsla,
transformation: TransformationMatrix,
local_content_mask: Bounds,
}
@group(1) @binding(0) var<storage, read> b_subpixel_sprites: array<SubpixelSprite>;
@@ -15,6 +16,7 @@ struct SubpixelSpriteOutput {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) @interpolate(flat) color: vec4<f32>,
@location(2) local_clip_distances: vec4<f32>,
@location(3) clip_distances: vec4<f32>,
}
@@ -32,6 +34,7 @@ fn vs_subpixel_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_i
out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.color = hsla_to_rgba(sprite.color);
out.local_clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.local_content_mask);
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
return out;
}
@@ -45,7 +48,7 @@ fn fs_subpixel_sprite(input: SubpixelSpriteOutput) -> SubpixelSpriteFragmentOutp
let alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, gamma_params.subpixel_enhanced_contrast, gamma_params.gamma_ratios);
// Alpha clip after using the derivatives.
if (any(input.clip_distances < vec4<f32>(0.0))) {
if (any(input.clip_distances < vec4<f32>(0.0)) || any(input.local_clip_distances < vec4<f32>(0.0))) {
return SubpixelSpriteFragmentOutput(vec4<f32>(0.0), vec4<f32>(0.0));
}
@@ -138,7 +138,7 @@ fn read_transformation(cursor: ptr<function, InstanceCursor>) -> TransformationM
fn load_quad(instance_id: u32) -> Quad {
// Keep this fixed-layout decoder explicit. Some WebGL shader compilers fail
// to optimize the cursor's branches and dynamic vector indexing for quads.
let first_texel_index = instance_id * 10u;
let first_texel_index = instance_id * 13u;
let width = textureDimensions(t_instances).x;
let texel0 = fetch_instance_texel(first_texel_index, width);
let texel1 = fetch_instance_texel(first_texel_index + 1u, width);
@@ -150,6 +150,9 @@ fn load_quad(instance_id: u32) -> Quad {
let texel7 = fetch_instance_texel(first_texel_index + 7u, width);
let texel8 = fetch_instance_texel(first_texel_index + 8u, width);
let texel9 = fetch_instance_texel(first_texel_index + 9u, width);
let texel10 = fetch_instance_texel(first_texel_index + 10u, width);
let texel11 = fetch_instance_texel(first_texel_index + 11u, width);
let texel12 = fetch_instance_texel(first_texel_index + 12u, width);
let values0 = bitcast<vec4<f32>>(texel0);
let values1 = bitcast<vec4<f32>>(texel1);
@@ -161,6 +164,9 @@ fn load_quad(instance_id: u32) -> Quad {
let values7 = bitcast<vec4<f32>>(texel7);
let values8 = bitcast<vec4<f32>>(texel8);
let values9 = bitcast<vec4<f32>>(texel9);
let values10 = bitcast<vec4<f32>>(texel10);
let values11 = bitcast<vec4<f32>>(texel11);
let values12 = bitcast<vec4<f32>>(texel12);
return Quad(
texel0.x,
@@ -187,11 +193,17 @@ fn load_quad(instance_id: u32) -> Quad {
Hsla(values7.x, values7.y, values7.z, values7.w),
Corners(values8.x, values8.y, values8.z, values8.w),
Edges(values9.x, values9.y, values9.z, values9.w),
TransformationMatrix(
mat2x2<f32>(values10.xy, values10.zw),
values11.xy,
),
Bounds(values11.zw, values12.xy),
vec2<u32>(texel12.z, texel12.w),
);
}
fn load_shadow(instance_id: u32) -> Shadow {
var cursor = instance_cursor(instance_id * 28u);
var cursor = instance_cursor(instance_id * 40u);
return Shadow(
read_word(&cursor),
read_f32(&cursor),
@@ -203,16 +215,21 @@ fn load_shadow(instance_id: u32) -> Shadow {
read_corners(&cursor),
read_word(&cursor),
read_word(&cursor),
read_transformation(&cursor),
read_bounds(&cursor),
vec2<u32>(read_word(&cursor), read_word(&cursor)),
);
}
fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex {
var cursor = instance_cursor(vertex_id * 26u);
var cursor = instance_cursor(vertex_id * 32u);
return PathRasterizationVertex(
read_vec2_f32(&cursor),
read_vec2_f32(&cursor),
read_background(&cursor),
read_bounds(&cursor),
read_vec2_f32(&cursor),
read_bounds(&cursor),
);
}
@@ -222,7 +239,7 @@ fn load_path_sprite(instance_id: u32) -> PathSprite {
}
fn load_underline(instance_id: u32) -> Underline {
var cursor = instance_cursor(instance_id * 16u);
var cursor = instance_cursor(instance_id * 28u);
return Underline(
read_word(&cursor),
read_word(&cursor),
@@ -231,11 +248,14 @@ fn load_underline(instance_id: u32) -> Underline {
read_hsla(&cursor),
read_f32(&cursor),
read_word(&cursor),
read_transformation(&cursor),
read_bounds(&cursor),
vec2<u32>(read_word(&cursor), read_word(&cursor)),
);
}
fn load_mono_sprite(instance_id: u32) -> MonochromeSprite {
var cursor = instance_cursor(instance_id * 28u);
var cursor = instance_cursor(instance_id * 32u);
return MonochromeSprite(
read_word(&cursor),
read_word(&cursor),
@@ -244,11 +264,12 @@ fn load_mono_sprite(instance_id: u32) -> MonochromeSprite {
read_bounds(&cursor),
read_hsla(&cursor),
read_transformation(&cursor),
read_bounds(&cursor),
);
}
fn load_poly_sprite(instance_id: u32) -> PolychromeSprite {
var cursor = instance_cursor(instance_id * 24u);
var cursor = instance_cursor(instance_id * 36u);
return PolychromeSprite(
read_word(&cursor),
read_word(&cursor),
@@ -258,5 +279,8 @@ fn load_poly_sprite(instance_id: u32) -> PolychromeSprite {
read_bounds(&cursor),
read_bounds(&cursor),
read_corners(&cursor),
read_transformation(&cursor),
read_bounds(&cursor),
vec2<u32>(read_word(&cursor), read_word(&cursor)),
);
}
@@ -109,8 +109,15 @@ pub(crate) struct PathRasterizationVertex {
pub(crate) st_position: Point<f32>,
pub(crate) color: Background,
pub(crate) bounds: Bounds<ScaledPixels>,
pub(crate) local_position: Point<ScaledPixels>,
pub(crate) local_content_mask: crate::ContentMask<ScaledPixels>,
}
const _: () = assert!(
std::mem::size_of::<PathRasterizationVertex>() == 128
&& std::mem::size_of::<PathRasterizationVertex>().is_multiple_of(16)
);
pub struct WgpuSurfaceConfig {
pub size: Size<DevicePixels>,
pub transparent: bool,
@@ -1874,11 +1881,14 @@ impl WgpuRendererCore {
let mut vertices = Vec::new();
for path in paths {
let bounds = path.clipped_bounds();
let local_content_mask = path.local_content_mask;
vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex {
xy_position: v.xy_position,
st_position: v.st_position,
color: path.color,
bounds,
local_position: v.local_position,
local_content_mask,
}));
}
@@ -90,7 +90,7 @@ impl Scene {
pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
let mut primitive = primitive.into();
let clipped_bounds = primitive
.bounds()
.screen_bounds()
.intersect(&primitive.content_mask().bounds);
if clipped_bounds.is_empty() {
@@ -228,6 +228,21 @@ impl Primitive {
}
}
pub fn screen_bounds(&self) -> Bounds<ScaledPixels> {
match self {
Primitive::Shadow(shadow) => shadow.transformation.map_bounds(shadow.bounds),
Primitive::Quad(quad) => quad.transformation.map_bounds(quad.bounds),
Primitive::Path(path) => path.bounds,
Primitive::Underline(underline) => {
underline.transformation.map_bounds(underline.bounds)
}
Primitive::MonochromeSprite(sprite) => sprite.transformation.map_bounds(sprite.bounds),
Primitive::SubpixelSprite(sprite) => sprite.transformation.map_bounds(sprite.bounds),
Primitive::PolychromeSprite(sprite) => sprite.transformation.map_bounds(sprite.bounds),
Primitive::Surface(surface) => surface.bounds,
}
}
pub fn content_mask(&self) -> &ContentMask<ScaledPixels> {
match self {
Primitive::Shadow(shadow) => &shadow.content_mask,
@@ -498,6 +513,25 @@ impl PrimitiveBatch {
}
}
/// Unbounded local-space content mask (1e12 px extent, safe under HiDPI scaling without f32 overflow).
pub(crate) fn unbounded_local_content_mask() -> ContentMask<Pixels> {
ContentMask {
bounds: Bounds::new(
point(Pixels(-1.0e12), Pixels(-1.0e12)),
Size::new(Pixels(2.0e12), Pixels(2.0e12)),
),
}
}
pub(crate) fn unbounded_scaled_content_mask() -> ContentMask<ScaledPixels> {
ContentMask {
bounds: Bounds::new(
point(ScaledPixels(-1.0e12), ScaledPixels(-1.0e12)),
Size::new(ScaledPixels(2.0e12), ScaledPixels(2.0e12)),
),
}
}
#[derive(Default, Debug, Copy, Clone)]
#[repr(C)]
#[expect(missing_docs)]
@@ -510,6 +544,9 @@ pub struct Quad {
pub border_color: Hsla,
pub corner_radii: Corners<ScaledPixels>,
pub border_widths: Edges<ScaledPixels>,
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
pub pad: [u32; 2],
}
impl From<Quad> for Primitive {
@@ -529,6 +566,9 @@ pub struct Underline {
pub color: Hsla,
pub thickness: ScaledPixels,
pub wavy: PaddedBool32,
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
pub pad2: [u32; 2],
}
impl From<Underline> for Primitive {
@@ -552,6 +592,9 @@ pub struct Shadow {
/// 0 = drop shadow (rendered outside the element), 1 = inset shadow (rendered inside).
pub inset: u32,
pub pad: u32, // align to 8 bytes
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
pub pad2: [u32; 2],
}
impl From<Shadow> for Primitive {
@@ -667,9 +710,27 @@ impl TransformationMatrix {
Point::new(output[0].into(), output[1].into())
}
/// Apply transformation to a device-pixel point.
#[inline]
pub fn apply_scaled(&self, point: Point<ScaledPixels>) -> Point<ScaledPixels> {
let x = point.x.0;
let y = point.y.0;
Point::new(
ScaledPixels(
self.rotation_scale[0][0] * x + self.rotation_scale[0][1] * y + self.translation[0],
),
ScaledPixels(
self.rotation_scale[1][0] * x + self.rotation_scale[1][1] * y + self.translation[1],
),
)
}
/// Maps a local-space axis-aligned rectangle through this 2D linear-plus-translation transform
/// and returns the conservative axis-aligned bounding box of its four corners.
pub fn map_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
if *self == Self::unit() {
return bounds;
}
let x0 = bounds.origin.x.0;
let y0 = bounds.origin.y.0;
let x1 = x0 + bounds.size.width.0;
@@ -700,6 +761,64 @@ impl TransformationMatrix {
}
}
/// Computes the inverse of this 2D linear-plus-translation transform, returning `None` if singular.
pub fn inverse(&self) -> Option<Self> {
let a = self.rotation_scale[0][0];
let b = self.rotation_scale[0][1];
let c = self.rotation_scale[1][0];
let d = self.rotation_scale[1][1];
let det = a * d - b * c;
if det.abs() <= 1e-12 {
return None;
}
let inv_det = 1.0 / det;
let ia = d * inv_det;
let ib = -b * inv_det;
let ic = -c * inv_det;
let id = a * inv_det;
let tx = self.translation[0];
let ty = self.translation[1];
Some(Self {
rotation_scale: [[ia, ib], [ic, id]],
translation: [-(ia * tx + ib * ty), -(ic * tx + id * ty)],
})
}
/// Maps a logical-pixel axis-aligned rectangle through this transform and returns
/// the conservative axis-aligned bounding box of its four corners.
pub fn map_bounds_pixels(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
if *self == Self::unit() {
return bounds;
}
let x0 = bounds.origin.x.0;
let y0 = bounds.origin.y.0;
let x1 = x0 + bounds.size.width.0;
let y1 = y0 + bounds.size.height.0;
let mut min_x = f32::INFINITY;
let mut min_y = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut max_y = f32::NEG_INFINITY;
for (cx, cy) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] {
let tx = self.rotation_scale[0][0] * cx
+ self.rotation_scale[0][1] * cy
+ self.translation[0];
let ty = self.rotation_scale[1][0] * cx
+ self.rotation_scale[1][1] * cy
+ self.translation[1];
min_x = min_x.min(tx);
min_y = min_y.min(ty);
max_x = max_x.max(tx);
max_y = max_y.max(ty);
}
Bounds {
origin: Point::new(Pixels(min_x), Pixels(min_y)),
size: Size::new(
Pixels((max_x - min_x).max(0.0)),
Pixels((max_y - min_y).max(0.0)),
),
}
}
/// Scales the translation component into device pixels while preserving rotation/scale.
#[inline]
pub fn scale_translation(&self, scale_factor: f32) -> Self {
@@ -730,6 +849,7 @@ pub struct MonochromeSprite {
pub content_mask: ContentMask<ScaledPixels>,
pub color: Hsla,
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
}
impl From<MonochromeSprite> for Primitive {
@@ -749,6 +869,7 @@ pub struct SubpixelSprite {
pub content_mask: ContentMask<ScaledPixels>,
pub color: Hsla,
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
}
impl From<SubpixelSprite> for Primitive {
@@ -769,8 +890,35 @@ pub struct PolychromeSprite {
pub bounds: Bounds<ScaledPixels>,
pub content_mask: ContentMask<ScaledPixels>,
pub corner_radii: Corners<ScaledPixels>,
pub transformation: TransformationMatrix,
pub local_content_mask: ContentMask<ScaledPixels>,
pub pad2: [u32; 2],
}
// WebGL2 packs GPU instance structs into RGBA32U texels (16 bytes each).
const _: () = {
assert!(std::mem::size_of::<Quad>() == 208 && std::mem::size_of::<Quad>().is_multiple_of(16));
assert!(
std::mem::size_of::<Shadow>() == 160 && std::mem::size_of::<Shadow>().is_multiple_of(16)
);
assert!(
std::mem::size_of::<Underline>() == 112
&& std::mem::size_of::<Underline>().is_multiple_of(16)
);
assert!(
std::mem::size_of::<MonochromeSprite>() == 128
&& std::mem::size_of::<MonochromeSprite>().is_multiple_of(16)
);
assert!(
std::mem::size_of::<SubpixelSprite>() == 128
&& std::mem::size_of::<SubpixelSprite>().is_multiple_of(16)
);
assert!(
std::mem::size_of::<PolychromeSprite>() == 144
&& std::mem::size_of::<PolychromeSprite>().is_multiple_of(16)
);
};
impl From<PolychromeSprite> for Primitive {
fn from(sprite: PolychromeSprite) -> Self {
Primitive::PolychromeSprite(sprite)
@@ -805,6 +953,7 @@ pub struct Path<P: Clone + Debug + Default + PartialEq> {
pub order: DrawOrder,
pub bounds: Bounds<P>,
pub content_mask: ContentMask<P>,
pub local_content_mask: ContentMask<P>,
pub vertices: Vec<PathVertex<P>>,
pub color: Background,
start: Point<P>,
@@ -826,6 +975,7 @@ impl Path<Pixels> {
size: Default::default(),
},
content_mask: Default::default(),
local_content_mask: unbounded_local_content_mask(),
color: Default::default(),
contour_count: 0,
}
@@ -833,15 +983,48 @@ impl Path<Pixels> {
/// Scale this path by the given factor.
pub fn scale(&self, factor: f32) -> Path<ScaledPixels> {
self.scale_transformed(
factor,
TransformationMatrix::unit(),
self.local_content_mask.scale(factor),
)
}
/// Scale and transform this path's vertices into screen space while preserving local coordinates.
pub fn scale_transformed(
&self,
factor: f32,
transform: TransformationMatrix,
local_content_mask: ContentMask<ScaledPixels>,
) -> Path<ScaledPixels> {
let is_unit = transform == TransformationMatrix::unit();
let scaled_bounds = self.bounds.scale(factor);
Path {
id: self.id,
order: self.order,
bounds: self.bounds.scale(factor),
bounds: if is_unit {
scaled_bounds
} else {
transform.map_bounds(scaled_bounds)
},
content_mask: self.content_mask.scale(factor),
local_content_mask,
vertices: self
.vertices
.iter()
.map(|vertex| vertex.scale(factor))
.map(|vertex| {
let local_pos = vertex.xy_position.scale(factor);
PathVertex {
xy_position: if is_unit {
local_pos
} else {
transform.apply_scaled(local_pos)
},
local_position: local_pos,
st_position: vertex.st_position,
content_mask: vertex.content_mask.scale(factor),
}
})
.collect(),
start: self.start.map(|start| start.scale(factor)),
current: self.current.scale(factor),
@@ -909,16 +1092,19 @@ impl Path<Pixels> {
self.vertices.push(PathVertex {
xy_position: xy.0,
local_position: xy.0,
st_position: st.0,
content_mask: Default::default(),
});
self.vertices.push(PathVertex {
xy_position: xy.1,
local_position: xy.1,
st_position: st.1,
content_mask: Default::default(),
});
self.vertices.push(PathVertex {
xy_position: xy.2,
local_position: xy.2,
st_position: st.2,
content_mask: Default::default(),
});
@@ -947,6 +1133,7 @@ impl From<Path<ScaledPixels>> for Primitive {
#[expect(missing_docs)]
pub struct PathVertex<P: Clone + Debug + Default + PartialEq> {
pub xy_position: Point<P>,
pub local_position: Point<P>,
pub st_position: Point<f32>,
pub content_mask: ContentMask<P>,
}
@@ -954,8 +1141,10 @@ pub struct PathVertex<P: Clone + Debug + Default + PartialEq> {
#[expect(missing_docs)]
impl PathVertex<Pixels> {
pub fn scale(&self, factor: f32) -> PathVertex<ScaledPixels> {
let scaled = self.xy_position.scale(factor);
PathVertex {
xy_position: self.xy_position.scale(factor),
xy_position: scaled,
local_position: scaled,
st_position: self.st_position,
content_mask: self.content_mask.scale(factor),
}
@@ -971,7 +1160,7 @@ pub(crate) struct LayerKey(pub u32);
pub(crate) enum LayerContent {
#[default]
Empty,
Scene(std::sync::Arc<Scene>),
Scene(std::rc::Rc<Scene>),
}
impl LayerContent {
@@ -985,7 +1174,7 @@ impl LayerContent {
impl From<Scene> for LayerContent {
fn from(scene: Scene) -> Self {
Self::Scene(std::sync::Arc::new(scene))
Self::Scene(std::rc::Rc::new(scene))
}
}
@@ -2380,7 +2380,8 @@ impl Style {
Some(color) => match color.tag {
BackgroundTag::Solid
| BackgroundTag::PatternSlash
| BackgroundTag::Checkerboard => color.solid,
| BackgroundTag::Checkerboard
| BackgroundTag::DotGrid => color.solid,
BackgroundTag::LinearGradient => color
.colors
@@ -474,6 +474,11 @@ impl TextSystem {
self.read_metrics(font_id, |metrics| metrics.descent(font_size))
}
/// Get the recommended additional space between lines for the given font.
pub fn line_gap(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.read_metrics(font_id, |metrics| metrics.line_gap(font_size))
}
/// Get the recommended baseline offset for the given font and line height.
pub fn baseline_offset(
&self,
@@ -1196,6 +1196,8 @@ pub struct Window {
pub(crate) element_offset_stack: Vec<Point<Pixels>>,
pub(crate) element_opacity: f32,
pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
pub(crate) paint_transformation_stack: Vec<TransformationMatrix>,
pub(crate) local_content_mask_stack: Vec<ContentMask<Pixels>>,
pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
/// The [`TextInputConfiguration`] most recently forwarded to the platform
/// window, so that only actual changes are forwarded (reconfiguring a live
@@ -2157,6 +2159,8 @@ impl Window {
rendered_entity_stack: Vec::new(),
element_offset_stack: Vec::new(),
content_mask_stack: Vec::new(),
paint_transformation_stack: Vec::new(),
local_content_mask_stack: Vec::new(),
element_opacity: 1.0,
requested_autoscroll: None,
last_text_input_configuration: None,
@@ -3283,7 +3287,7 @@ impl Window {
) {
self.invalidator.debug_assert_paint();
let underline = self.underline(origin, width, style);
if exclusions.is_empty() {
if exclusions.is_empty() || underline.transformation != TransformationMatrix::unit() {
self.next_frame.scene.insert_primitive(underline);
return;
}
@@ -3342,6 +3346,9 @@ impl Window {
.opacity(self.element_opacity()),
thickness: self.snap_stroke(style.thickness),
wavy: style.wavy.into(),
transformation: self.active_gpu_transformation(),
local_content_mask: self.active_local_content_mask(),
pad2: [0; 2],
}
}
@@ -4141,6 +4148,81 @@ impl Window {
}
}
/// Returns the active world-to-screen paint transformation matrix.
#[inline]
pub fn paint_transformation(&self) -> TransformationMatrix {
self.paint_transformation_stack
.last()
.copied()
.unwrap_or_else(TransformationMatrix::unit)
}
/// Composes `transform` onto the active paint transformation stack for the duration of `f`.
///
/// If a local paint mask is active in the outer coordinate frame, its conservative
/// axis-aligned inverse image under `transform` is pushed for the duration of `f` so
/// nested local masks remain expressed in the inner local coordinate space.
#[inline]
pub fn with_paint_transformation<R>(
&mut self,
transform: TransformationMatrix,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
let next = self.paint_transformation().compose(transform);
self.paint_transformation_stack.push(next);
let mapped_mask = self.local_content_mask_stack.last().and_then(|active| {
transform.inverse().map(|inv| ContentMask {
bounds: inv.map_bounds_pixels(active.bounds),
})
});
if let Some(mask) = mapped_mask {
self.local_content_mask_stack.push(mask);
}
let result = f(self);
if mapped_mask.is_some() {
self.local_content_mask_stack.pop();
}
self.paint_transformation_stack.pop();
result
}
/// Intersects `mask` with the active pre-transform local paint mask for the duration of `f`.
///
/// Masks are axis-aligned in the active local coordinate space. When a nested
/// [`Self::with_paint_transformation`] carries rotation or shear, outer masks are
/// projected into the inner space as conservative axis-aligned bounding boxes.
#[inline]
pub fn with_local_paint_mask<R>(
&mut self,
mask: ContentMask<Pixels>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
let next = match self.local_content_mask_stack.last() {
Some(current) => mask.intersect(current),
None => mask,
};
self.local_content_mask_stack.push(next);
let result = f(self);
self.local_content_mask_stack.pop();
result
}
#[inline]
pub(crate) fn active_gpu_transformation(&self) -> TransformationMatrix {
self.paint_transformation()
.scale_translation(self.scale_factor())
}
#[inline]
pub(crate) fn active_local_content_mask(&self) -> ContentMask<ScaledPixels> {
self.local_content_mask_stack
.last()
.map(|mask| mask.scale(self.scale_factor()))
.unwrap_or_else(crate::scene::unbounded_scaled_content_mask)
}
/// Returns the structured element snapshot recorded during the most recent rendered frame.
#[inline]
pub fn frame_snapshot(&self) -> &crate::FrameSnapshot {
@@ -4511,12 +4593,12 @@ impl Window {
pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
self.invalidator.debug_assert_paint();
let content_mask = self.content_mask();
let clipped_bounds = bounds.intersect(&content_mask.bounds);
let transformed = self
.active_gpu_transformation()
.map_bounds(self.cover_bounds(bounds));
let clipped_bounds = transformed.intersect(&self.snapped_content_mask().bounds);
if !clipped_bounds.is_empty() {
self.next_frame
.scene
.push_layer(self.cover_bounds(clipped_bounds));
self.next_frame.scene.push_layer(clipped_bounds);
}
let result = f(self);
@@ -4543,6 +4625,8 @@ impl Window {
let scale_factor = self.scale_factor();
let content_mask = self.snapped_content_mask();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let opacity = self.element_opacity();
let element_bounds = self.cover_bounds(bounds);
let element_corner_radii = corner_radii.scale(scale_factor);
@@ -4562,6 +4646,9 @@ impl Window {
element_corner_radii,
inset: 0,
pad: 0,
transformation,
local_content_mask,
pad2: [0; 2],
});
}
}
@@ -4579,6 +4666,8 @@ impl Window {
let scale_factor = self.scale_factor();
let content_mask = self.snapped_content_mask();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let opacity = self.element_opacity();
let element_bounds = self.cover_bounds(bounds);
let element_corner_radii = corner_radii.scale(scale_factor);
@@ -4607,6 +4696,9 @@ impl Window {
element_corner_radii,
inset: 1,
pad: 0,
transformation,
local_content_mask,
pad2: [0; 2],
});
}
}
@@ -4662,21 +4754,27 @@ impl Window {
pub fn paint_quad(&mut self, quad: PaintQuad) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let opacity = self.element_opacity();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let snapped_bounds = self.snap_bounds(quad.bounds);
let snapped_border_widths = self.snap_border_widths(quad.border_widths);
let quad = Quad {
order: 0,
bounds: snapped_bounds,
content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
background: quad.background.scale(scale_factor).opacity(opacity),
border_color: quad.border_color.opacity(opacity),
corner_radii: quad.corner_radii.scale(self.scale_factor()),
corner_radii: quad.corner_radii.scale(scale_factor),
border_widths: snapped_border_widths,
border_style: quad.border_style,
transformation,
local_content_mask,
pad: [0; 2],
};
if !quad.background.is_transparent() {
if !quad.background.is_transparent() || transformation != TransformationMatrix::unit() {
self.next_frame.scene.insert_primitive(quad);
return;
}
@@ -4735,13 +4833,19 @@ impl Window {
let scale_factor = self.scale_factor();
let content_mask = self.content_mask();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let opacity = self.element_opacity();
path.content_mask = content_mask;
let color: Background = color.into();
path.color = color.opacity(opacity);
path.color = color.scale(scale_factor).opacity(opacity);
self.next_frame
.scene
.insert_primitive(path.scale(scale_factor));
.insert_primitive(path.scale_transformed(
scale_factor,
transformation,
local_content_mask,
));
}
/// Paint an underline into the scene for the next frame at the current z-index.
@@ -4785,6 +4889,9 @@ impl Window {
thickness: self.snap_stroke(style.thickness),
color: style.color.unwrap_or_default().opacity(opacity),
wavy: false.into(),
transformation: self.active_gpu_transformation(),
local_content_mask: self.active_local_content_mask(),
pad2: [0; 2],
});
}
@@ -4809,14 +4916,34 @@ impl Window {
let element_opacity = self.element_opacity();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
let is_unit = transformation == TransformationMatrix::unit();
let zoom_bucket = crate::fast::glyphs::glyph_zoom_bucket(&transformation);
let (integer_origin, subpixel_variant) = crate::fast::glyphs::quantize_origin(glyph_origin);
let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
let (integer_origin, subpixel_variant, raster_font_size, subpixel_rendering) =
if let Some(bucket) = zoom_bucket {
(
glyph_origin,
Point::default(),
Pixels(font_size.0 * bucket),
false,
)
} else {
let (integer_origin, subpixel_variant) =
crate::fast::glyphs::quantize_origin(glyph_origin);
(
integer_origin,
subpixel_variant,
font_size,
is_unit && self.should_use_subpixel_rendering(font_id, font_size),
)
};
let dilation = self.text_system().glyph_dilation_for_color(color);
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
font_size: raster_font_size,
subpixel_variant,
scale_factor,
is_emoji: false,
@@ -4833,9 +4960,16 @@ impl Window {
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
let inv_bucket = 1.0 / zoom_bucket.unwrap_or(1.0);
let bounds = Bounds {
origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
origin: Point::new(
ScaledPixels(integer_origin.x.0 + raster_bounds.origin.x.0 as f32 * inv_bucket),
ScaledPixels(integer_origin.y.0 + raster_bounds.origin.y.0 as f32 * inv_bucket),
),
size: Size::new(
ScaledPixels(tile.bounds.size.width.0 as f32 * inv_bucket),
ScaledPixels(tile.bounds.size.height.0 as f32 * inv_bucket),
),
};
let content_mask = self.snapped_content_mask();
@@ -4847,7 +4981,8 @@ impl Window {
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
transformation,
local_content_mask,
});
} else {
self.next_frame.scene.insert_primitive(MonochromeSprite {
@@ -4857,7 +4992,8 @@ impl Window {
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
transformation,
local_content_mask,
});
}
}
@@ -4932,6 +5068,8 @@ impl Window {
};
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
@@ -4942,6 +5080,9 @@ impl Window {
content_mask,
tile,
opacity,
transformation,
local_content_mask,
pad2: [0; 2],
});
}
Ok(())
@@ -4999,6 +5140,8 @@ impl Window {
.map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
.map_size(|size| size.ceil());
let transformation = self.active_gpu_transformation().compose(transformation);
let local_content_mask = self.active_local_content_mask();
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
pad: 0,
@@ -5007,6 +5150,7 @@ impl Window {
color: color.opacity(element_opacity),
tile,
transformation,
local_content_mask,
});
Ok(())
@@ -5104,6 +5248,8 @@ impl Window {
.clamp_radii_for_quad_size(visible_bounds.size)
.scale(self.scale_factor());
let opacity = self.element_opacity();
let transformation = self.active_gpu_transformation();
let local_content_mask = self.active_local_content_mask();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
@@ -5114,6 +5260,9 @@ impl Window {
corner_radii,
tile: sub_tile,
opacity,
transformation,
local_content_mask,
pad2: [0; 2],
});
Ok(())
}
@@ -36,6 +36,7 @@ const BENCHMARK_TIMING_KEYS = new Set([
const BENCHMARK_COUNTER_KEYS = new Set([
'layout_single_keystroke_blocks_relayout',
'edgeless_1k_pan_zoom_blocks_relayout',
]);
const ALL_BENCHMARK_KEYS = [
@@ -45,6 +46,7 @@ const ALL_BENCHMARK_KEYS = [
'layout_single_keystroke_ms',
'layout_single_keystroke_blocks_relayout',
'edgeless_1k_pan_zoom_frame_ms',
'edgeless_1k_pan_zoom_blocks_relayout',
'headless_frame_render_ms',
];
@@ -723,3 +723,80 @@ test('partial-metrics baseline to expanded-metrics current yields BOOTSTRAP on n
assert.equal(byKey.get('benchmarks.doc_1k_edits_ms')?.status, 'BOOTSTRAP');
assert.equal(byKey.get('artifacts_bytes.web_wasm_raw')?.status, 'BOOTSTRAP');
});
test('edgeless_1k_pan_zoom_blocks_relayout: 0->0 passes and 0->1 flags deterministic hard regression', () => {
const mkPayload = (commitChar, relayouts) => ({
schema_version: 1,
commit: commitChar.repeat(40),
timestamp_utc: '2026-11-22T06:00:00Z',
ci_wall_ms: {
headless_linux: 50_000,
lint_and_wasm: 35_000,
total_critical_path: 50_000,
},
artifacts_bytes: {
headless_bin: 14_500_000,
web_wasm_raw: 1_800_000,
web_wasm_gzip: 620_000,
},
benchmarks: {
doc_1k_edits_ms: { median: 10.0, p95: 12.0 },
room_sync_1k_ops_ms: { median: 18.0, p95: 21.0 },
layout_10k_blocks_cold_ms: { median: 120.0, p95: 135.0 },
layout_single_keystroke_ms: { median: 0.5, p95: 0.7 },
layout_single_keystroke_blocks_relayout: 1,
edgeless_1k_pan_zoom_frame_ms: { median: 2.5, p95: 3.1 },
edgeless_1k_pan_zoom_blocks_relayout: relayouts,
headless_frame_render_ms: { median: 8.0, p95: 9.5 },
},
});
const baseline = mkPayload('a', 0);
const currentPass = mkPayload('b', 0);
const passVerdict = comparePerfMetrics({ current: currentPass, baseline });
assert.equal(passVerdict.has_hard_regression, false);
const passMetric = passVerdict.metrics.find(
m => m.key === 'benchmarks.edgeless_1k_pan_zoom_blocks_relayout'
);
assert.equal(passMetric?.status, 'PASS');
assert.equal(passMetric?.regressed, false);
const currentRegressed = mkPayload('c', 1);
const failVerdict = comparePerfMetrics({ current: currentRegressed, baseline });
assert.equal(failVerdict.has_hard_regression, true);
const failMetric = failVerdict.metrics.find(
m => m.key === 'benchmarks.edgeless_1k_pan_zoom_blocks_relayout'
);
assert.equal(failMetric?.status, 'REGRESSED');
assert.equal(failMetric?.regressed, true);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'compare-n3-edgeless-'));
try {
const basePath = path.join(dir, 'baseline.json');
const passPath = path.join(dir, 'pass.json');
const failPath = path.join(dir, 'fail.json');
fs.writeFileSync(basePath, JSON.stringify(baseline));
fs.writeFileSync(passPath, JSON.stringify(currentPass));
fs.writeFileSync(failPath, JSON.stringify(currentRegressed));
execFileSync(
process.execPath,
[CLI_PATH, '--current', passPath, '--baseline', basePath, '--fail-on-regression'],
{ encoding: 'utf8' }
);
let failedExit = 0;
try {
execFileSync(
process.execPath,
[CLI_PATH, '--current', failPath, '--baseline', basePath, '--fail-on-regression'],
{ encoding: 'utf8' }
);
} catch (err) {
failedExit = err.status ?? 0;
}
assert.equal(failedExit, 1);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
@@ -103,6 +103,11 @@
{ "type": "null" }
]
},
"edgeless_1k_pan_zoom_blocks_relayout": {
"type": ["integer", "null"],
"minimum": 0,
"description": "Number of blocks re-laid out during a 30-step Edgeless pan and zoom sweep."
},
"headless_frame_render_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
@@ -369,7 +369,8 @@ async function checkLinkField(cdp) {
await mouse('mousePressed',from,1);
await mouse('mouseMoved',to,1);
await mouse('mouseReleased',to,0);
await sleep(400);
await evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
await sleep(100);
const paragraph = await mirror();
if (!paragraph.value.startsWith('This page')) {
throw new Error(`Unable to select in the second showcase block: ${JSON.stringify(paragraph)}`);
@@ -479,6 +480,8 @@ async function main() {
}
});
await cdp.send('Emulation.setFocusEmulationEnabled', { enabled: true });
await cdp.send('Page.bringToFront');
const pageUrl = `http://127.0.0.1:${port}/${args.query ? `?${args.query}` : ''}`;
await cdp.send('Page.navigate', { url: pageUrl });
@@ -581,6 +584,28 @@ async function main() {
if (diffPx < 5000) {
throw new Error(`Clicking Edgeless did not produce expected visual transition (diffPixels=${diffPx})`);
}
const edgelessInk = countDarkInkPixels(img2, 40, 80, 1240, 760);
console.log(`Web Wasm Edgeless canvas ink=${edgelessInk}`);
if (edgelessInk < 500) {
throw new Error(`Expected non-trivial Edgeless canvas ink (>=500), got ${edgelessInk}`);
}
if (!args.query) {
// Also verify direct `?mode=edgeless` cold load without WebGL2/WebGPU shader errors.
await cdp.send('Page.navigate', { url: `http://127.0.0.1:${port}/?mode=edgeless` });
let edgelessDirectInk = 0;
for (let attempt = 0; attempt < 40; attempt += 1) {
await sleep(300);
const shot3 = await cdp.send('Page.captureScreenshot', { format: 'png' });
const img3 = decodePngRgba(Buffer.from(shot3.data, 'base64'));
edgelessDirectInk = countDarkInkPixels(img3, 40, 80, 1240, 760);
if (edgelessDirectInk >= 500) break;
}
console.log(`Web Wasm direct ?mode=edgeless ink=${edgelessDirectInk}`);
if (edgelessDirectInk < 500) {
throw new Error(`Direct ?mode=edgeless rendered insufficient ink (${edgelessDirectInk})`);
}
}
if (errors.length > 0) {
throw new Error(`Uncaught browser errors during Wasm smoke test:\n${errors.join('\n')}`);
}