Add porting plan and first pure slice: geometry, color, scene

docs/PORTING.md maps GPUI's architecture onto MoonBit packages, separates
pure logic from platform code, surveys mooncakes packages and their backends,
recommends a js + Canvas2D first backend behind a small Platform trait, lists
the Rust idioms that need a different design, and gives an ordered roadmap.

First slice (pure, tested on wasm, wasm-gc, js and native):
- geometry: Pixels/ScaledPixels/DevicePixels/Rems, Absolute/Definite/Length
  with parsing, Point/Size/Bounds/Edges/Corners, Anchor, Axis, ContentMask
- color: Rgba/Hsla with conversions, hex parsing, blending, Background
  (solid, linear gradient, patterns)
- scene: primitives (Quad, Shadow, Path, Underline, sprites), transformation
  matrix, BoundsTree draw ordering, layers, finish/batches, replay

Derived from Zed's GPUI (Apache-2.0); see LICENSE and NOTICE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SpriteandClaude Opus 5.5 committed 2026-11-24 21:23:48 +00:00
1 parent b9d1949688
commit 8c0685fe01
24 files changed
+5856 -1

No files matched your search

+246
View File
@@ -0,0 +1,246 @@
// Port of gpui/src/bounds_tree.rs: an R-tree-like structure that assigns draw
// orders. Each inserted rectangle gets an order one greater than the highest
// order of any earlier rectangle it overlaps (or the same order, if the
// overlapped primitive's kind may share a level with the new one). Primitives
// with the same order never overlap, so they can be batched freely.
///|
let max_children : Int32 = 12
///|
#derive(Eq, Compare)
priv struct Key {
ordering : Int32
kind : PrimitiveKind
}
///|
priv enum NodeKind {
Leaf(Key)
Internal(Array[Int32])
}
///|
priv struct Node[U] {
mut bounds : @geometry.Bounds[U]
mut max_key : Key
kind : NodeKind
}
///|
/// Assigns draw orders to rectangles; see the module comment.
pub struct BoundsTree[U] {
priv nodes : Array[Node[U]]
priv mut root : Int32?
priv mut max_leaf : Int32?
priv insert_path : Array[Int32]
}
///|
pub fn[U] BoundsTree::new() -> BoundsTree[U] {
{ nodes: [], root: None, max_leaf: None, insert_path: [], }
}
///|
pub fn[U] BoundsTree::clear(self : BoundsTree[U]) -> Unit {
self.nodes.clear()
self.root = None
self.max_leaf = None
self.insert_path.clear()
}
///|
/// Inserts `new_bounds` and returns its draw order (starting at 1).
pub fn[U : Add + Sub + Compare] BoundsTree::insert(
self : BoundsTree[U],
new_bounds : @geometry.Bounds[U],
kind : PrimitiveKind,
max_shared_kind : PrimitiveKind,
) -> Int32 {
let ordering = match self.find_max_key(new_bounds) {
None => 1
Some(max_key) =>
if max_key.kind <= max_shared_kind {
max_key.ordering
} else {
max_key.ordering + 1
}
}
let key = { ordering, kind, }
let new_leaf = self.insert_leaf(new_bounds, key)
match self.max_leaf {
None => self.max_leaf = Some(new_leaf)
Some(old) =>
if self.nodes[old].max_key < key {
self.max_leaf = Some(new_leaf)
}
}
ordering
}
///|
fn[U : Add + Compare] BoundsTree::find_max_key(
self : BoundsTree[U],
query : @geometry.Bounds[U],
) -> Key? {
guard self.root is Some(root) else { return None }
// Fast path: the most recent maximum often overlaps the query.
if self.max_leaf is Some(max_idx) {
let max_node = self.nodes[max_idx]
if query.intersects(max_node.bounds) {
return Some(max_node.max_key)
}
}
let stack = [root]
let mut max_found : Key? = None
while stack.pop() is Some(idx) {
let node = self.nodes[idx]
if max_found is Some(found) && node.max_key <= found {
continue
}
if !query.intersects(node.bounds) {
continue
}
match node.kind {
Leaf(key) =>
max_found = match max_found {
Some(found) if found >= key => Some(found)
_ => Some(key)
}
Internal(children) =>
for child in children {
let child_key = self.nodes[child].max_key
let worth_visiting = match max_found {
None => true
Some(found) => child_key > found
}
if worth_visiting {
stack.push(child)
}
}
}
}
max_found
}
///|
fn[U : Add + Sub + Compare] BoundsTree::insert_leaf(
self : BoundsTree[U],
bounds : @geometry.Bounds[U],
key : Key,
) -> Int32 {
let new_leaf = self.nodes.length()
self.nodes.push({ bounds, max_key: key, kind: Leaf(key), })
guard self.root is Some(root) else {
self.root = Some(new_leaf)
return new_leaf
}
if self.nodes[root].kind is Leaf(_) {
let root_node = self.nodes[root]
let children = if key > root_node.max_key {
[root, new_leaf]
} else {
[new_leaf, root]
}
let new_root = self.nodes.length()
self.nodes.push({
bounds: root_node.bounds.union(bounds),
max_key: if root_node.max_key >= key {
root_node.max_key
} else {
key
},
kind: Internal(children),
})
self.root = Some(new_root)
return new_leaf
}
self.insert_path.clear()
let mut current = root
while true {
guard self.nodes[current].kind is Internal(children) else {
abort("BoundsTree: should only traverse internal nodes")
}
self.insert_path.push(current)
// Choose the child whose bounds grow the least (half-perimeter heuristic).
let mut best_child = children[0]
let mut best_pos = 0
let mut best_cost = bounds
.union(self.nodes[best_child].bounds)
.half_perimeter()
for pos in 1..<children.length() {
let child = children[pos]
let cost = bounds.union(self.nodes[child].bounds).half_perimeter()
if cost < best_cost {
best_cost = cost
best_child = child
best_pos = pos
}
}
if self.nodes[best_child].kind is Internal(_) {
current = best_child
continue
}
if children.length() < max_children {
// Add the leaf directly; keep the child with the max key last.
let node = self.nodes[current]
children.push(new_leaf)
if key <= node.max_key {
let last = children.length() - 1
children.swap(last - 1, last)
}
node.bounds = node.bounds.union(bounds)
if key > node.max_key {
node.max_key = key
}
} else {
// Full: replace the best leaf with an internal node holding both.
let sibling = self.nodes[best_child]
let new_children = if key > sibling.max_key {
[best_child, new_leaf]
} else {
[new_leaf, best_child]
}
let new_internal = self.nodes.length()
let new_internal_max = if sibling.max_key >= key {
sibling.max_key
} else {
key
}
self.nodes.push({
bounds: sibling.bounds.union(bounds),
max_key: new_internal_max,
kind: Internal(new_children),
})
let parent = self.nodes[current]
children[best_pos] = new_internal
if new_internal_max > parent.max_key {
children.swap(best_pos, children.length() - 1)
}
}
break
}
// Propagate bounds and max keys up the insertion path.
let mut updated_child : Int32? = None
for i = self.insert_path.length() - 1; i >= 0; i = i - 1 {
let node_idx = self.insert_path[i]
let node = self.nodes[node_idx]
node.bounds = node.bounds.union(bounds)
if node.max_key < key {
node.max_key = key
if updated_child is Some(child) && node.kind is Internal(children) {
let last = children.length() - 1
for pos, c in children {
if c == child {
if pos != last {
children.swap(pos, last)
}
break
}
}
}
}
updated_child = Some(node_idx)
}
new_leaf
}
+9
View File
@@ -0,0 +1,9 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"moonbitlang/core/math",
}
import {
"moonbitlang/core/random",
} for "test"
+209
View File
@@ -0,0 +1,209 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/scene"
import {
"experiments/gpui/color",
"experiments/gpui/geometry",
"moonbitlang/core/debug",
}
// Values
pub fn quad_depth(Int32, Double) -> Double
pub fn quad_depth_scale(Int32) -> Double
// Errors
// Types and methods
#derive(Eq, Hash, @debug.Debug)
pub(all) struct AtlasTextureId {
index : Int32
kind : AtlasTextureKind
}
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) enum AtlasTextureKind {
Monochrome
Polychrome
Subpixel
}
#derive(Eq, Hash, @debug.Debug)
pub(all) struct AtlasTile {
texture_id : AtlasTextureId
tile_id : Int32
padding : Int32
bounds : @geometry.Bounds[@geometry.DevicePixels]
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum BorderStyle {
Solid
Dashed
}
pub impl Default for BorderStyle
pub struct BoundsTree[U] {
// private fields
}
pub fn[U] BoundsTree::clear(Self[U]) -> Unit
pub fn[U : Add + Sub + Compare] BoundsTree::insert(Self[U], @geometry.Bounds[U], PrimitiveKind, PrimitiveKind) -> Int32
pub fn[U] BoundsTree::new() -> Self[U]
#derive(Eq, @debug.Debug)
pub(all) struct MonochromeSprite {
order : Int32
tile : AtlasTile
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
transformation : TransformationMatrix
}
#derive(Eq, @debug.Debug)
pub(all) struct PaintedPath {
order : Int32
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Background
even_odd : Bool
contours : Array[Array[@geometry.Point[@geometry.ScaledPixels]]]
}
pub fn PaintedPath::new(Array[Array[@geometry.Point[@geometry.Pixels]]], Double, @geometry.ContentMask[@geometry.Pixels], @color.Background, even_odd? : Bool) -> Self
#derive(Eq, @debug.Debug)
pub(all) struct PolychromeSprite {
order : Int32
tile : AtlasTile
grayscale : Bool
opacity : Double
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
}
#derive(Eq, @debug.Debug)
pub(all) enum Primitive {
Shadow(Shadow)
Quad(Quad)
Path(PaintedPath)
Underline(Underline)
MonochromeSprite(MonochromeSprite)
SubpixelSprite(SubpixelSprite)
PolychromeSprite(PolychromeSprite)
}
pub fn Primitive::bounds(Self) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn Primitive::clipped_bounds(Self) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn Primitive::content_mask(Self) -> @geometry.ContentMask[@geometry.ScaledPixels]
pub fn Primitive::kind(Self) -> PrimitiveKind
#derive(Eq, @debug.Debug)
pub(all) enum PrimitiveBatch {
Shadows(start~ : Int32, end~ : Int32)
Quads(start~ : Int32, end~ : Int32)
Paths(start~ : Int32, end~ : Int32)
Underlines(start~ : Int32, end~ : Int32)
MonochromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
SubpixelSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
PolychromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
}
pub fn PrimitiveBatch::label(Self) -> String
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) enum PrimitiveKind {
Shadow
Quad
Path
Underline
MonochromeSprite
SubpixelSprite
PolychromeSprite
}
pub fn PrimitiveKind::max_shared_kind(Self) -> Self
#derive(Default, Eq, @debug.Debug)
pub(all) struct Quad {
order : Int32
border_style : BorderStyle
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
background : @color.Background
border_color : @color.Hsla
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
border_widths : @geometry.Edges[@geometry.ScaledPixels]
}
pub struct Scene {
shadows : Array[Shadow]
quads : Array[Quad]
paths : Array[PaintedPath]
underlines : Array[Underline]
monochrome_sprites : Array[MonochromeSprite]
subpixel_sprites : Array[SubpixelSprite]
polychrome_sprites : Array[PolychromeSprite]
// private fields
}
pub fn Scene::batches(Self) -> Array[PrimitiveBatch]
pub fn Scene::clear(Self) -> Unit
pub fn Scene::finish(Self) -> Unit
pub fn Scene::insert_primitive(Self, Primitive) -> Unit
pub fn Scene::len(Self) -> Int32
pub fn Scene::new() -> Self
pub fn Scene::pop_layer(Self) -> Unit
pub fn Scene::push_layer(Self) -> Unit
pub fn Scene::replay(Self, Self, Int32, Int32) -> Unit
#derive(Default, Eq, @debug.Debug)
pub(all) struct Shadow {
order : Int32
blur_radius : @geometry.ScaledPixels
bounds : @geometry.Bounds[@geometry.ScaledPixels]
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
shape_bounds : @geometry.Bounds[@geometry.ScaledPixels]
shape_corner_radii : @geometry.Corners[@geometry.ScaledPixels]
inset : Bool
}
#derive(Eq, @debug.Debug)
pub(all) struct SubpixelSprite {
order : Int32
tile : AtlasTile
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
transformation : TransformationMatrix
}
#derive(Eq, @debug.Debug)
pub(all) struct TransformationMatrix {
xx : Double
xy : Double
yx : Double
yy : Double
tx : Double
ty : Double
}
pub fn TransformationMatrix::apply(Self, @geometry.Point[@geometry.Pixels]) -> @geometry.Point[@geometry.Pixels]
pub fn TransformationMatrix::compose(Self, Self) -> Self
pub fn TransformationMatrix::rotate(Self, @geometry.Radians) -> Self
pub fn TransformationMatrix::scale(Self, @geometry.Size[Double]) -> Self
pub fn TransformationMatrix::transform_bounds(Self, @geometry.Bounds[@geometry.ScaledPixels]) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn TransformationMatrix::translate(Self, @geometry.Point[@geometry.ScaledPixels]) -> Self
pub fn TransformationMatrix::unit() -> Self
pub impl Default for TransformationMatrix
#derive(Default, Eq, @debug.Debug)
pub(all) struct Underline {
order : Int32
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
thickness : @geometry.ScaledPixels
wavy : Bool
}
// Type aliases
// Traits
+437
View File
@@ -0,0 +1,437 @@
// Scene primitives, ported from gpui/src/scene.rs (and AtlasTile & co. from
// gpui/src/platform.rs).
//
// Deviations from GPUI (see docs/PORTING.md, "Scene"):
// - Primitives are plain immutable records; GPUI's `#[repr(C)]` padding fields
// (`pad`, `PaddedBool32`) are dropped. A renderer packs them into GPU
// buffers explicitly.
// - `PaintedPath` stores flattened polygon contours instead of GPUI's tiled
// path representation (`PathTiles`, built by lyon in `path_builder.rs`);
// tiling belongs to the renderer milestone.
// - `PaintSurface` (macOS CVPixelBuffer) and `PaintNativeView` (embedded native
// views) are not ported yet. Sprite animations are not ported yet.
///|
type ScaledPixels = @geometry.ScaledPixels
///|
type Bounds = @geometry.Bounds[ScaledPixels]
///|
type ContentMask = @geometry.ContentMask[ScaledPixels]
///|
/// The kind of a primitive. The declaration order is significant: it breaks
/// ties between primitives with equal draw order (GPUI derives `Ord`).
#derive(Eq, Compare, Hash, Debug)
pub(all) enum PrimitiveKind {
Shadow
Quad
Path
Underline
MonochromeSprite
SubpixelSprite
PolychromeSprite
}
///|
/// The highest kind that may share a draw order with this kind without being
/// drawn in the wrong order. Glyph sprites can share a level with underlines
/// and with each other because they are always drawn after them.
pub fn PrimitiveKind::max_shared_kind(self : PrimitiveKind) -> PrimitiveKind {
match self {
MonochromeSprite => Underline
SubpixelSprite => MonochromeSprite
PolychromeSprite => SubpixelSprite
kind => kind
}
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum BorderStyle {
Solid
Dashed
}
///|
pub impl Default for BorderStyle with fn default() {
Solid
}
///|
/// A 2D affine transformation: `[[xx, xy], [yx, yy]]` rotation/scale plus a
/// translation `(tx, ty)`.
#derive(Eq, Debug)
pub(all) struct TransformationMatrix {
xx : Double
xy : Double
yx : Double
yy : Double
tx : Double
ty : Double
}
///|
pub fn TransformationMatrix::unit() -> TransformationMatrix {
{ xx: 1.0, xy: 0.0, yx: 0.0, yy: 1.0, tx: 0.0, ty: 0.0, }
}
///|
pub impl Default for TransformationMatrix with fn default() {
TransformationMatrix::unit()
}
///|
/// `self` followed by `other` applied first (matrix product `self * other`).
pub fn TransformationMatrix::compose(
self : TransformationMatrix,
other : TransformationMatrix,
) -> TransformationMatrix {
if other == TransformationMatrix::unit() {
return self
}
{
xx: self.xx * other.xx + self.xy * other.yx,
xy: self.xx * other.xy + self.xy * other.yy,
yx: self.yx * other.xx + self.yy * other.yx,
yy: self.yx * other.xy + self.yy * other.yy,
tx: self.tx + self.xx * other.tx + self.xy * other.ty,
ty: self.ty + self.yx * other.tx + self.yy * other.ty,
}
}
///|
pub fn TransformationMatrix::translate(
self : TransformationMatrix,
point : @geometry.Point[ScaledPixels],
) -> TransformationMatrix {
self.compose({ ..TransformationMatrix::unit(), tx: point.x.0, ty: point.y.0, })
}
///|
pub fn TransformationMatrix::rotate(
self : TransformationMatrix,
angle : @geometry.Radians,
) -> TransformationMatrix {
let cos = @math.cos(angle.0)
let sin = @math.sin(angle.0)
self.compose({ xx: cos, xy: -sin, yx: sin, yy: cos, tx: 0.0, ty: 0.0, })
}
///|
pub fn TransformationMatrix::scale(
self : TransformationMatrix,
size : @geometry.Size[Double],
) -> TransformationMatrix {
self.compose({
xx: size.width,
xy: 0.0,
yx: 0.0,
yy: size.height,
tx: 0.0,
ty: 0.0,
})
}
///|
/// Applies the transformation to a point.
pub fn TransformationMatrix::apply(
self : TransformationMatrix,
point : @geometry.Point[@geometry.Pixels],
) -> @geometry.Point[@geometry.Pixels] {
{
x: @geometry.px(self.tx + self.xx * point.x.0 + self.xy * point.y.0),
y: @geometry.px(self.ty + self.yx * point.x.0 + self.yy * point.y.0),
}
}
///|
/// The axis-aligned bounding box of the transformed bounds.
pub fn TransformationMatrix::transform_bounds(
self : TransformationMatrix,
bounds : Bounds,
) -> Bounds {
if self == TransformationMatrix::unit() {
return bounds
}
let transform = fn(
corner : @geometry.Point[ScaledPixels],
) -> @geometry.Point[ScaledPixels] {
{
x: ScaledPixels(self.xx * corner.x.0 + self.xy * corner.y.0 + self.tx),
y: ScaledPixels(self.yx * corner.x.0 + self.yy * corner.y.0 + self.ty),
}
}
let first = transform(bounds.origin)
let mut top_left = first
let mut bottom_right = first
for
corner in [bounds.top_right(), bounds.bottom_left(), bounds.bottom_right()] {
let p = transform(corner)
top_left = top_left.min(p)
bottom_right = bottom_right.max(p)
}
@geometry.Bounds::from_corners(top_left, bottom_right)
}
// ---------------------------------------------------------------------------
// Atlas references (GPUI: platform.rs). Will move to the platform package once
// it exists; kept here because sprites reference them.
// ---------------------------------------------------------------------------
///|
#derive(Eq, Compare, Hash, Debug)
pub(all) enum AtlasTextureKind {
Monochrome
Polychrome
Subpixel
}
///|
#derive(Eq, Hash, Debug)
pub(all) struct AtlasTextureId {
/// The index of this texture in the atlas.
index : Int32
/// The kind of content stored in this texture.
kind : AtlasTextureKind
}
///|
/// A rectangle allocated in an atlas texture.
#derive(Eq, Hash, Debug)
pub(all) struct AtlasTile {
texture_id : AtlasTextureId
tile_id : Int32
/// Padding around the tile content, in device pixels.
padding : Int32
bounds : @geometry.Bounds[@geometry.DevicePixels]
}
// ---------------------------------------------------------------------------
// Primitives
// ---------------------------------------------------------------------------
///|
/// A rectangle with optional rounded corners, borders and a fill.
#derive(Eq, Default, Debug)
pub(all) struct Quad {
order : Int32
border_style : BorderStyle
bounds : Bounds
content_mask : ContentMask
background : @color.Background
border_color : @color.Hsla
corner_radii : @geometry.Corners[ScaledPixels]
border_widths : @geometry.Edges[ScaledPixels]
}
///|
/// A (box) shadow cast by, or inset into, a rounded rectangle.
#derive(Eq, Default, Debug)
pub(all) struct Shadow {
order : Int32
blur_radius : ScaledPixels
bounds : Bounds
corner_radii : @geometry.Corners[ScaledPixels]
content_mask : ContentMask
color : @color.Hsla
/// The shape casting the shadow (used to clip inset shadows).
shape_bounds : Bounds
shape_corner_radii : @geometry.Corners[ScaledPixels]
inset : Bool
}
///|
/// A straight or wavy text underline (also used for strikethrough).
#derive(Eq, Default, Debug)
pub(all) struct Underline {
order : Int32
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
thickness : ScaledPixels
wavy : Bool
}
///|
/// A single-channel (alpha mask) sprite tinted with `color`, e.g. a glyph.
#derive(Eq, Debug)
pub(all) struct MonochromeSprite {
order : Int32
tile : AtlasTile
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
transformation : TransformationMatrix
}
///|
/// A glyph rendered with per-channel (subpixel) coverage.
#derive(Eq, Debug)
pub(all) struct SubpixelSprite {
order : Int32
tile : AtlasTile
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
transformation : TransformationMatrix
}
///|
/// A full-color sprite, e.g. an image or an emoji.
#derive(Eq, Debug)
pub(all) struct PolychromeSprite {
order : Int32
tile : AtlasTile
grayscale : Bool
opacity : Double
bounds : Bounds
content_mask : ContentMask
corner_radii : @geometry.Corners[ScaledPixels]
}
///|
/// A filled vector path made of closed polygon contours.
#derive(Eq, Debug)
pub(all) struct PaintedPath {
order : Int32
/// Bounding box of all contours.
bounds : Bounds
content_mask : ContentMask
color : @color.Background
/// Even-odd fill rule if true, non-zero winding otherwise.
even_odd : Bool
contours : Array[Array[@geometry.Point[ScaledPixels]]]
}
///|
/// Creates a path primitive from contours given in logical pixels.
///
/// Fails loudly if there are no points: an empty path has no bounds and would
/// silently disappear.
pub fn PaintedPath::new(
contours : Array[Array[@geometry.Point[@geometry.Pixels]]],
scale_factor : Double,
content_mask : @geometry.ContentMask[@geometry.Pixels],
color : @color.Background,
even_odd~ : Bool = false,
) -> PaintedPath {
let scaled = contours.map(fn(contour) {
contour.map(fn(p) { p.scale(scale_factor) })
})
let mut top_left : @geometry.Point[ScaledPixels]? = None
let mut bottom_right : @geometry.Point[ScaledPixels]? = None
for contour in scaled {
for p in contour {
top_left = Some(
match top_left {
None => p
Some(tl) => tl.min(p)
},
)
bottom_right = Some(
match bottom_right {
None => p
Some(br) => br.max(p)
},
)
}
}
guard top_left is Some(tl) && bottom_right is Some(br) else {
abort("PaintedPath::new: path has no points")
}
{
order: 0,
bounds: @geometry.Bounds::from_corners(tl, br),
content_mask: content_mask.scale(scale_factor),
color,
even_odd,
contours: scaled,
}
}
///|
/// Any primitive that can be inserted into a `Scene`.
#derive(Eq, Debug)
pub(all) enum Primitive {
Shadow(Shadow)
Quad(Quad)
Path(PaintedPath)
Underline(Underline)
MonochromeSprite(MonochromeSprite)
SubpixelSprite(SubpixelSprite)
PolychromeSprite(PolychromeSprite)
}
///|
pub fn Primitive::kind(self : Primitive) -> PrimitiveKind {
match self {
Shadow(_) => PrimitiveKind::Shadow
Quad(_) => PrimitiveKind::Quad
Path(_) => PrimitiveKind::Path
Underline(_) => PrimitiveKind::Underline
MonochromeSprite(_) => PrimitiveKind::MonochromeSprite
SubpixelSprite(_) => PrimitiveKind::SubpixelSprite
PolychromeSprite(_) => PrimitiveKind::PolychromeSprite
}
}
///|
pub fn Primitive::bounds(self : Primitive) -> Bounds {
match self {
Shadow(p) => p.bounds
Quad(p) => p.bounds
Path(p) => p.bounds
Underline(p) => p.bounds
MonochromeSprite(p) => p.bounds
SubpixelSprite(p) => p.bounds
PolychromeSprite(p) => p.bounds
}
}
///|
pub fn Primitive::content_mask(self : Primitive) -> ContentMask {
match self {
Shadow(p) => p.content_mask
Quad(p) => p.content_mask
Path(p) => p.content_mask
Underline(p) => p.content_mask
MonochromeSprite(p) => p.content_mask
SubpixelSprite(p) => p.content_mask
PolychromeSprite(p) => p.content_mask
}
}
///|
fn Primitive::transformation(self : Primitive) -> TransformationMatrix {
match self {
MonochromeSprite(p) => p.transformation
SubpixelSprite(p) => p.transformation
_ => TransformationMatrix::unit()
}
}
///|
/// The bounds actually affected by this primitive: transformed bounds clipped
/// to the content mask.
pub fn Primitive::clipped_bounds(self : Primitive) -> Bounds {
self
.transformation()
.transform_bounds(self.bounds())
.intersect(self.content_mask().bounds)
}
///|
/// The same primitive with its draw order replaced.
fn Primitive::with_order(self : Primitive, order : Int32) -> Primitive {
match self {
Shadow(p) => Shadow({ ..p, order, })
Quad(p) => Quad({ ..p, order, })
Path(p) => Path({ ..p, order, })
Underline(p) => Underline({ ..p, order, })
MonochromeSprite(p) => MonochromeSprite({ ..p, order, })
SubpixelSprite(p) => SubpixelSprite({ ..p, order, })
PolychromeSprite(p) => PolychromeSprite({ ..p, order, })
}
}
+425
View File
@@ -0,0 +1,425 @@
// Port of `Scene` from gpui/src/scene.rs: collects primitives for one frame,
// assigns draw orders via `BoundsTree`, and groups them into batches a
// renderer can draw with one pipeline/texture binding each.
///|
priv enum PaintOperation {
Op(Primitive)
StartLayer
EndLayer
}
///|
priv struct Layer {
/// Index ranges `[start, end)` into `paint_operations`.
ranges : Array[(Int32, Int32)]
mut bounds : Bounds
mut max_kind : PrimitiveKind
mut max_shared_kind : PrimitiveKind
}
///|
/// The primitives painted in one frame, sorted for rendering by `finish`.
pub struct Scene {
priv paint_operations : Array[PaintOperation]
priv primitive_bounds : BoundsTree[ScaledPixels]
priv layer_stack : Array[Int32]
priv layers : Array[Layer]
shadows : Array[Shadow]
quads : Array[Quad]
paths : Array[PaintedPath]
underlines : Array[Underline]
monochrome_sprites : Array[MonochromeSprite]
subpixel_sprites : Array[SubpixelSprite]
polychrome_sprites : Array[PolychromeSprite]
}
///|
pub fn Scene::new() -> Scene {
{
paint_operations: [],
primitive_bounds: BoundsTree::new(),
layer_stack: [],
layers: [],
shadows: [],
quads: [],
paths: [],
underlines: [],
monochrome_sprites: [],
subpixel_sprites: [],
polychrome_sprites: [],
}
}
///|
pub fn Scene::clear(self : Scene) -> Unit {
self.paint_operations.clear()
self.primitive_bounds.clear()
self.layer_stack.clear()
self.layers.clear()
self.shadows.clear()
self.quads.clear()
self.paths.clear()
self.underlines.clear()
self.monochrome_sprites.clear()
self.subpixel_sprites.clear()
self.polychrome_sprites.clear()
}
///|
/// Number of recorded paint operations (primitives plus layer markers). Views
/// use ranges of these to replay cached paints into the next frame.
pub fn Scene::len(self : Scene) -> Int32 {
self.paint_operations.length()
}
///|
/// Starts a layer: primitives inserted until the matching `pop_layer` are
/// ordered as one unit, above everything they overlap that came before.
pub fn Scene::push_layer(self : Scene) -> Unit {
self.layer_stack.push(self.layers.length())
self.layers.push({
ranges: [],
bounds: Default::default(),
max_kind: PrimitiveKind::Shadow,
// The highest kind, i.e. "no restriction yet" for the minimum below.
max_shared_kind: PrimitiveKind::PolychromeSprite,
})
self.paint_operations.push(StartLayer)
}
///|
pub fn Scene::pop_layer(self : Scene) -> Unit {
guard self.layer_stack.pop() is Some(_) else {
abort("Scene::pop_layer without matching push_layer")
}
if self.layer_stack.is_empty() {
let layers = self.layers.copy()
self.layers.clear()
for layer in layers {
self.insert_layer(layer)
}
}
self.paint_operations.push(EndLayer)
}
///|
fn Scene::insert_layer(self : Scene, layer : Layer) -> Unit {
if layer.ranges.is_empty() {
return
}
let order = self.primitive_bounds.insert(
layer.bounds,
layer.max_kind,
layer.max_shared_kind,
)
for range in layer.ranges {
let (start, end) = range
for index in start..<end {
if self.paint_operations[index] is Op(primitive) {
self.push_primitive(primitive, order)
}
}
}
}
///|
/// Adds a primitive. Primitives whose clipped bounds are empty are dropped
/// (they would not be visible).
pub fn Scene::insert_primitive(self : Scene, primitive : Primitive) -> Unit {
let clipped_bounds = primitive.clipped_bounds()
if clipped_bounds.is_empty() {
return
}
let kind = primitive.kind()
match self.layer_stack.last() {
Some(layer_index) => {
let layer = self.layers[layer_index]
layer.bounds = layer.bounds.join(clipped_bounds)
if kind > layer.max_kind {
layer.max_kind = kind
}
if kind.max_shared_kind() < layer.max_shared_kind {
layer.max_shared_kind = kind.max_shared_kind()
}
let index = self.paint_operations.length()
match layer.ranges.last() {
Some((start, end)) if end == index =>
layer.ranges[layer.ranges.length() - 1] = (start, end + 1)
_ => layer.ranges.push((index, index + 1))
}
}
None => {
let order = self.primitive_bounds.insert(
clipped_bounds,
kind,
kind.max_shared_kind(),
)
self.push_primitive(primitive, order)
}
}
self.paint_operations.push(Op(primitive))
}
///|
fn Scene::push_primitive(
self : Scene,
primitive : Primitive,
order : Int32,
) -> Unit {
match primitive.with_order(order) {
Shadow(p) => self.shadows.push(p)
Quad(p) => self.quads.push(p)
Path(p) => self.paths.push(p)
Underline(p) => self.underlines.push(p)
MonochromeSprite(p) => self.monochrome_sprites.push(p)
SubpixelSprite(p) => self.subpixel_sprites.push(p)
PolychromeSprite(p) => self.polychrome_sprites.push(p)
}
}
///|
/// Re-inserts the paint operations `[start, end)` of `prev_scene` (used to
/// reuse the paint output of cached views).
pub fn Scene::replay(
self : Scene,
prev_scene : Scene,
start : Int32,
end : Int32,
) -> Unit {
guard start >= 0 &&
start <= end &&
end <= prev_scene.paint_operations.length() else {
abort(
"Scene::replay: range \{start}..\{end} out of bounds (len \{prev_scene.paint_operations.length()})",
)
}
for index in start..<end {
match prev_scene.paint_operations[index] {
Op(primitive) => self.insert_primitive(primitive)
StartLayer => self.push_layer()
EndLayer => self.pop_layer()
}
}
}
///|
/// Stable sort by `(major, minor)`; equal keys keep their insertion order.
fn[T] sort_by_order(items : Array[T], key : (T) -> (Int32, Int32)) -> Unit {
let keyed = items.mapi(fn(i, item) {
let (major, minor) = key(item)
(major, minor, i)
})
keyed.sort()
let sorted = keyed.map(fn(k) { items[k.2] })
for i, item in sorted {
items[i] = item
}
}
///|
/// Finishes the frame: sorts every primitive list by draw order (sprites also
/// by texture, so batches can bind one texture). Fails loudly if layers are
/// unbalanced.
pub fn Scene::finish(self : Scene) -> Unit {
guard self.layer_stack.is_empty() else {
abort("Scene::finish: unbalanced scene layers")
}
sort_by_order(self.shadows, fn(p) { (p.order, 0) })
sort_by_order(self.quads, fn(p) { (p.order, 0) })
sort_by_order(self.paths, fn(p) { (p.order, 0) })
sort_by_order(self.underlines, fn(p) { (p.order, 0) })
sort_by_order(self.monochrome_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
sort_by_order(self.subpixel_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
sort_by_order(self.polychrome_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
}
// ---------------------------------------------------------------------------
// Batching
// ---------------------------------------------------------------------------
///|
/// A run of primitives of one kind that can be drawn together. Ranges are
/// `[start, end)` into the corresponding `Scene` array.
#derive(Eq, Debug)
pub(all) enum PrimitiveBatch {
Shadows(start~ : Int32, end~ : Int32)
Quads(start~ : Int32, end~ : Int32)
Paths(start~ : Int32, end~ : Int32)
Underlines(start~ : Int32, end~ : Int32)
MonochromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
SubpixelSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
PolychromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
}
///|
/// A short human-readable description, e.g. `"quads (3)"`.
pub fn PrimitiveBatch::label(self : PrimitiveBatch) -> String {
match self {
Shadows(start~, end~) => "shadows (\{end - start})"
Quads(start~, end~) => "quads (\{end - start})"
Paths(start~, end~) => "paths (\{end - start})"
Underlines(start~, end~) => "underlines (\{end - start})"
MonochromeSprites(texture_id~, start~, end~) =>
"monochrome sprites (\{end - start}) on atlas \{texture_id.index}"
SubpixelSprites(texture_id~, start~, end~) =>
"subpixel sprites (\{end - start}) on atlas \{texture_id.index}"
PolychromeSprites(texture_id~, start~, end~) =>
"polychrome sprites (\{end - start}) on atlas \{texture_id.index}"
}
}
///|
let all_kinds : Array[PrimitiveKind] = [
Shadow,
Quad,
Path,
Underline,
MonochromeSprite,
SubpixelSprite,
PolychromeSprite,
]
///|
fn Scene::count_of(self : Scene, kind : PrimitiveKind) -> Int32 {
match kind {
Shadow => self.shadows.length()
Quad => self.quads.length()
Path => self.paths.length()
Underline => self.underlines.length()
MonochromeSprite => self.monochrome_sprites.length()
SubpixelSprite => self.subpixel_sprites.length()
PolychromeSprite => self.polychrome_sprites.length()
}
}
///|
fn Scene::order_at(self : Scene, kind : PrimitiveKind, index : Int32) -> Int32 {
match kind {
Shadow => self.shadows[index].order
Quad => self.quads[index].order
Path => self.paths[index].order
Underline => self.underlines[index].order
MonochromeSprite => self.monochrome_sprites[index].order
SubpixelSprite => self.subpixel_sprites[index].order
PolychromeSprite => self.polychrome_sprites[index].order
}
}
///|
fn Scene::texture_at(
self : Scene,
kind : PrimitiveKind,
index : Int32,
) -> AtlasTextureId? {
match kind {
MonochromeSprite => Some(self.monochrome_sprites[index].tile.texture_id)
SubpixelSprite => Some(self.subpixel_sprites[index].tile.texture_id)
PolychromeSprite => Some(self.polychrome_sprites[index].tile.texture_id)
_ => None
}
}
///|
fn kind_index(kind : PrimitiveKind) -> Int32 {
match kind {
Shadow => 0
Quad => 1
Path => 2
Underline => 3
MonochromeSprite => 4
SubpixelSprite => 5
PolychromeSprite => 6
}
}
///|
let no_order : Int32 = 2147483647
///|
/// Groups the (finished) scene into batches in painting order. Mirrors GPUI's
/// `BatchIterator`: repeatedly take the kind with the lowest `(order, kind)`
/// head, and extend the batch while its next element still sorts before the
/// head of every other kind (and, for sprites, uses the same texture).
pub fn Scene::batches(self : Scene) -> Array[PrimitiveBatch] {
let cursors = all_kinds.map(fn(_) { 0 })
let batches = []
let head = fn(kind : PrimitiveKind) -> (Int32, PrimitiveKind) {
let i = cursors[kind_index(kind)]
if i < self.count_of(kind) {
(self.order_at(kind, i), kind)
} else {
(no_order, kind)
}
}
while true {
let heads = all_kinds.map(head)
heads.sort()
let (first_order, batch_kind) = heads[0]
if first_order == no_order {
break
}
let limit = heads[1]
let k = kind_index(batch_kind)
let start = cursors[k]
let texture_id = self.texture_at(batch_kind, start)
let count = self.count_of(batch_kind)
let mut end = start + 1
while end < count &&
(self.order_at(batch_kind, end), batch_kind) < limit &&
self.texture_at(batch_kind, end) == texture_id {
end = end + 1
}
cursors[k] = end
let batch = match (batch_kind, texture_id) {
(Shadow, _) => Shadows(start~, end~)
(Quad, _) => Quads(start~, end~)
(Path, _) => Paths(start~, end~)
(Underline, _) => Underlines(start~, end~)
(MonochromeSprite, Some(texture_id)) =>
MonochromeSprites(texture_id~, start~, end~)
(SubpixelSprite, Some(texture_id)) =>
SubpixelSprites(texture_id~, start~, end~)
(PolychromeSprite, Some(texture_id)) =>
PolychromeSprites(texture_id~, start~, end~)
(_, None) => abort("Scene::batches: sprite without texture")
}
batches.push(batch)
}
batches
}
// ---------------------------------------------------------------------------
// Depth helpers used by renderers that z-test quads.
// ---------------------------------------------------------------------------
///|
/// Scale such that `quad_depth(i, scale)` stays below 1.0 for every quad.
pub fn quad_depth_scale(quad_count : Int32) -> Double {
let capped = if quad_count < (1 << 24) - 1 {
quad_count
} else {
(1 << 24) - 1
}
let mut denominator = 1
while denominator < capped + 1 {
denominator = denominator * 2
}
1.0 / denominator.to_double()
}
///|
pub fn quad_depth(quad_id : Int32, scale : Double) -> Double {
let depth = (quad_id + 1).to_double() * scale
if depth < 1.0 {
depth
} else {
1.0
}
}
+379
View File
@@ -0,0 +1,379 @@
///|
fn sb(
x : Double,
y : Double,
w : Double,
h : Double,
) -> @geometry.Bounds[@geometry.ScaledPixels] {
{
origin: { x: ScaledPixels(x), y: ScaledPixels(y), },
size: { width: ScaledPixels(w), height: ScaledPixels(h), },
}
}
///|
fn quad_at(x : Double, y~ : Double = 0.0) -> @scene.Primitive {
let bounds = sb(x, y, 10.0, 10.0)
Quad({ ..Default::default(), bounds, content_mask: { bounds, }, })
}
///|
fn shadow_at(x : Double) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
Shadow({ ..Default::default(), bounds, content_mask: { bounds, }, })
}
///|
fn underline_at(x : Double) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
Underline({
..Default::default(),
bounds,
content_mask: { bounds, },
thickness: ScaledPixels(1.0),
})
}
///|
fn glyph_at(x : Double, texture : Int32) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
MonochromeSprite({
order: 0,
tile: {
texture_id: { index: texture, kind: Monochrome, },
tile_id: 0,
padding: 0,
bounds: Default::default(),
},
bounds,
content_mask: { bounds, },
color: @color.black(),
transformation: @scene.TransformationMatrix::unit(),
})
}
///|
fn labels(scene : @scene.Scene) -> Array[String] {
scene.finish()
scene.batches().map(fn(batch) { batch.label() })
}
///|
/// Port of GPUI's bounds_tree `test_insert`.
test "bounds tree assigns increasing orders to overlapping bounds" {
let tree : @scene.BoundsTree[Double] = @scene.BoundsTree::new()
let b = fn(x : Double, y : Double) -> @geometry.Bounds[Double] {
{ origin: { x, y, }, size: { width: 10.0, height: 10.0, }, }
}
assert_eq(tree.insert(b(0.0, 0.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(5.0, 5.0), Quad, Shadow), 2)
assert_eq(tree.insert(b(10.0, 10.0), Quad, Shadow), 3)
// Non-overlapping bounds reuse orders.
assert_eq(tree.insert(b(20.0, 20.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(40.0, 40.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(25.0, 25.0), Quad, Shadow), 2)
}
///|
/// Port of GPUI's bounds_tree `test_random_iterations`: compare against a
/// brute-force computation of the expected ordering.
test "bounds tree matches brute force on random input" {
let kinds : Array[@scene.PrimitiveKind] = [Shadow, Quad, Path, Underline]
for seed in 1..<=200 {
let seed_bytes = Bytes::makei(32, fn(i) { (seed * 31 + i).to_byte() })
let rng = @random.Rand::chacha8(seed=seed_bytes)
let tree : @scene.BoundsTree[Double] = @scene.BoundsTree::new()
let expected : Array[
(@geometry.Bounds[Double], Int32, @scene.PrimitiveKind),
] = []
let count = rng.int(limit=100) + 1
for _ in 0..<count {
let bounds : @geometry.Bounds[Double] = {
origin: {
x: rng.double(min=-100.0, max=100.0),
y: rng.double(min=-100.0, max=100.0),
},
size: {
width: rng.double(min=0.0, max=50.0),
height: rng.double(min=0.0, max=50.0),
},
}
let kind = kinds[rng.int(limit=kinds.length())]
let max_shared_kind = kinds[rng.int(limit=kinds.length())]
let mut max_intersecting : (Int32, @scene.PrimitiveKind)? = None
for entry in expected {
let (other, ordering, other_kind) = entry
if other.intersects(bounds) {
max_intersecting = match max_intersecting {
Some(current) if current >= (ordering, other_kind) => Some(current)
_ => Some((ordering, other_kind))
}
}
}
let expected_ordering = match max_intersecting {
None => 1
Some((ordering, max_kind)) =>
if max_kind <= max_shared_kind {
ordering
} else {
ordering + 1
}
}
expected.push((bounds, expected_ordering, kind))
assert_eq(tree.insert(bounds, kind, max_shared_kind), expected_ordering)
}
}
}
///|
test "primitive kind order and sharing" {
assert_true(@scene.PrimitiveKind::Shadow < Quad)
assert_true(@scene.PrimitiveKind::Quad < Path)
assert_true(@scene.PrimitiveKind::Underline < MonochromeSprite)
assert_true(@scene.PrimitiveKind::SubpixelSprite < PolychromeSprite)
assert_eq(@scene.PrimitiveKind::MonochromeSprite.max_shared_kind(), Underline)
assert_eq(@scene.PrimitiveKind::Quad.max_shared_kind(), Quad)
}
///|
test "same-kind overlaps share an order and keep paint order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(100.0))
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(quad_at(5.0))
scene.finish()
// A kind may share a level with itself: within a batch, instances are drawn
// in insertion order, so overlapping quads need no new order.
assert_eq(scene.quads.map(fn(q) { q.order }), [1, 1, 1])
assert_eq(scene.quads.map(fn(q) { q.bounds.origin.x.0 }), [100.0, 0.0, 5.0])
assert_eq(scene.batches(), [Quads(start=0, end=3)])
}
///|
test "a higher kind below forces a new order" {
let scene = @scene.Scene::new()
scene.insert_primitive(underline_at(0.0))
scene.insert_primitive(quad_at(5.0))
scene.insert_primitive(quad_at(50.0))
scene.finish()
assert_eq(scene.quads.map(fn(q) { q.order }), [1, 2])
assert_eq(scene.quads.map(fn(q) { q.bounds.origin.x.0 }), [50.0, 5.0])
}
///|
test "batches interleave kinds by order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(shadow_at(0.0))
scene.insert_primitive(quad_at(0.0))
assert_eq(labels(scene), ["quads (1)", "shadows (1)", "quads (1)"])
}
///|
test "shadows sort before quads at the same order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(shadow_at(50.0))
assert_eq(labels(scene), ["shadows (1)", "quads (1)"])
}
///|
test "glyphs share an order with underlines and batch by texture" {
let scene = @scene.Scene::new()
let wide = sb(0.0, 0.0, 100.0, 10.0)
scene.insert_primitive(
Underline({
..Default::default(),
bounds: wide,
content_mask: { bounds: wide, },
thickness: ScaledPixels(1.0),
}),
)
scene.insert_primitive(glyph_at(0.0, 0))
scene.insert_primitive(glyph_at(20.0, 1))
scene.insert_primitive(glyph_at(40.0, 0))
scene.finish()
// Monochrome sprites may share a level with underlines.
assert_eq(scene.underlines[0].order, 1)
assert_eq(scene.monochrome_sprites.map(fn(s) { s.order }), [1, 1, 1])
// Sorted by texture within the order, so each atlas is bound once.
assert_eq(scene.batches().map(fn(b) { b.label() }), [
"underlines (1)", "monochrome sprites (2) on atlas 0", "monochrome sprites (1) on atlas 1",
])
}
///|
test "overlapping glyphs are ordered (sprites cannot share with themselves)" {
let scene = @scene.Scene::new()
scene.insert_primitive(glyph_at(0.0, 0))
scene.insert_primitive(glyph_at(5.0, 0))
scene.finish()
assert_eq(scene.monochrome_sprites.map(fn(s) { s.order }), [1, 2])
assert_eq(scene.batches().length(), 1)
}
///|
test "primitives clipped to nothing are dropped" {
let scene = @scene.Scene::new()
let bounds = sb(0.0, 0.0, 10.0, 10.0)
scene.insert_primitive(
Quad({
..Default::default(),
bounds,
content_mask: { bounds: sb(50.0, 50.0, 5.0, 5.0), },
}),
)
scene.insert_primitive(
Quad({
..Default::default(),
bounds: sb(0.0, 0.0, 0.0, 10.0),
content_mask: { bounds, },
}),
)
assert_eq(scene.len(), 0)
assert_eq(labels(scene), [])
}
///|
test "a layer is ordered as one unit" {
let scene = @scene.Scene::new()
scene.insert_primitive(underline_at(0.0))
scene.push_layer()
// The second quad does not overlap the underline itself, but the layer as a
// whole does, so both quads are lifted above it.
scene.insert_primitive(quad_at(5.0))
scene.insert_primitive(quad_at(5.0, y=50.0))
scene.pop_layer()
// Control: outside a layer, a quad that does not overlap the underline
// stays at order 1.
scene.insert_primitive(quad_at(200.0))
scene.finish()
assert_eq(scene.quads.map(fn(q) { (q.order, q.bounds.origin.x.0) }), [
(1, 200.0),
(2, 5.0),
(2, 5.0),
])
assert_eq(scene.len(), 6)
assert_eq(labels(scene), ["quads (1)", "underlines (1)", "quads (2)"])
}
///|
test "nested layers resolve when the outermost layer pops" {
let scene = @scene.Scene::new()
scene.push_layer()
scene.insert_primitive(quad_at(0.0))
scene.push_layer()
scene.insert_primitive(shadow_at(0.0))
scene.pop_layer()
assert_eq(scene.quads.length(), 0)
scene.pop_layer()
scene.finish()
assert_eq(scene.quads.length(), 1)
assert_eq(scene.shadows.length(), 1)
// The inner layer overlaps the outer one, so it is drawn above it.
assert_true(scene.shadows[0].order > scene.quads[0].order)
}
///|
test "replay reproduces a range of paint operations" {
let prev = @scene.Scene::new()
prev.insert_primitive(quad_at(0.0))
prev.push_layer()
prev.insert_primitive(shadow_at(0.0))
prev.pop_layer()
prev.insert_primitive(quad_at(0.0))
let next = @scene.Scene::new()
next.replay(prev, 0, prev.len())
assert_eq(next.len(), prev.len())
assert_eq(labels(next), labels(prev))
let partial = @scene.Scene::new()
partial.replay(prev, 1, 4)
assert_eq(labels(partial), ["shadows (1)"])
}
///|
test "clear resets the scene" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.clear()
assert_eq(scene.len(), 0)
scene.insert_primitive(quad_at(0.0))
scene.finish()
assert_eq(scene.quads[0].order, 1)
}
///|
test "transformation matrix" {
let unit = @scene.TransformationMatrix::unit()
assert_eq(unit.compose(unit), unit)
let moved = unit.translate({ x: ScaledPixels(10.0), y: ScaledPixels(5.0), })
assert_eq(moved.apply({ x: @geometry.px(1.0), y: @geometry.px(2.0), }), {
x: @geometry.px(11.0),
y: @geometry.px(7.0),
})
let scaled = unit.scale({ width: 2.0, height: 3.0, })
assert_eq(
scaled.transform_bounds(sb(1.0, 1.0, 2.0, 2.0)),
sb(2.0, 3.0, 4.0, 6.0),
)
// A quarter turn maps the box (0,0)-(2,1) onto (-1,0)-(0,2).
let rotated = unit.rotate(@geometry.radians(@math.PI / 2.0))
let rb = rotated.transform_bounds(sb(0.0, 0.0, 2.0, 1.0))
assert_true((rb.origin.x.0 - -1.0).abs() < 1.0e-9)
assert_true((rb.size.height.0 - 2.0).abs() < 1.0e-9)
}
///|
test "transformed sprites are clipped by their transformed bounds" {
let bounds = sb(0.0, 0.0, 10.0, 10.0)
let sprite : @scene.Primitive = match glyph_at(0.0, 0) {
MonochromeSprite(s) =>
@scene.Primitive::MonochromeSprite({
..s,
content_mask: { bounds: sb(0.0, 0.0, 100.0, 100.0), },
transformation: @scene.TransformationMatrix::unit().translate({
x: ScaledPixels(50.0),
y: ScaledPixels(0.0),
}),
})
_ => abort("unreachable")
}
assert_eq(sprite.bounds(), bounds)
assert_eq(sprite.clipped_bounds(), sb(50.0, 0.0, 10.0, 10.0))
}
///|
test "painted path bounds and scaling" {
let mask : @geometry.ContentMask[@geometry.Pixels] = {
bounds: {
origin: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
size: @geometry.size(@geometry.px(100.0), @geometry.px(100.0)),
},
}
let triangle = [
@geometry.point(@geometry.px(10.0), @geometry.px(10.0)),
@geometry.point(@geometry.px(30.0), @geometry.px(10.0)),
@geometry.point(@geometry.px(20.0), @geometry.px(25.0)),
]
let path = @scene.PaintedPath::new(
[triangle],
2.0,
mask,
@color.red().to_background(),
)
assert_eq(path.bounds, sb(20.0, 20.0, 40.0, 30.0))
assert_eq(path.content_mask.bounds, sb(0.0, 0.0, 200.0, 200.0))
assert_false(path.even_odd)
let scene = @scene.Scene::new()
scene.insert_primitive(Path(path))
assert_eq(labels(scene), ["paths (1)"])
}
///|
test "quad depth" {
assert_eq(@scene.quad_depth_scale(0), 1.0)
assert_eq(@scene.quad_depth_scale(3), 0.25)
assert_eq(@scene.quad_depth_scale(4), 0.125)
assert_eq(@scene.quad_depth(0, 0.25), 0.25)
assert_eq(@scene.quad_depth(10, 0.25), 1.0)
}