1// Nodes and their primitives encoded as the shader's instances: each 482// floats in draw.wgsl's `Instance` layout, in device space. A node keeps3// only its bounds, which a change damages; a frame encodes the nodes4// meeting its damaged rectangles as it gathers them.56import std::vector;7import std::option;8import std::math;9import pkg::alloy::gpu;10import pkg::alloy::text;11import pkg::alloy::window;1213import draw;14import frame;15import glyphs;1617pub const FLOATS: u64 = 48; // an instance's1819const FAR: f32 = 10000000.0;2021// What a primitive draws, in the order of draw.wgsl's kinds, with what22// only that kind needs.23pub type Kind = enum {24 Solid,25 Linear,26 Radial,27 Border,28 Shadow,29 Image: Sampled,30 Mask: Sampled,31 Clear,32 Colored: Sampled, // premultiplied RGBA, a color glyph's33 Text: GlyphRun, // glyphs, each encoded as a mask or a colored one34};3536// A texture's region and how it is sampled.37pub type Sampled = struct {38 pub texture: Texture,39 pub linear: bool,40};4142// A text's glyphs among its paint's.43pub type GlyphRun = struct {44 pub first: u32,45 pub count: u32,46};4748pub type Primitive = struct {49 pub kind: Kind,50 pub shape: Rect,51 pub radii: Radii,52 pub color: Color,53 pub params: [f32 : 3], // the instance's params after its kind54 pub extra: [f32 : 4],55};5657// A glyph to draw, from a layout.58pub type TextGlyph = struct {59 pub face: u32,60 pub glyph: u32,61 pub size: f32,62 pub x: f32, // its pen, on the baseline63 pub y: f32,64 pub color: Color,65};6667pub fn Primitive::of(kind: Kind, shape: Rect, radii: Radii) -> Primitive {68 return Primitive {69 .kind = kind,70 .shape = shape,71 .radii = radii,72 .color = Color::transparent(),73 .params = [0.0, 0.0, 0.0],74 .extra = [0.0, 0.0, 0.0, 0.0]75 };76}7778// The picture's region, in its texture's coordinates from 0 to 1.79pub fn texture_bounds(self picture: &Picture) -> [f32 : 4] {80 const w = picture.texture.width to f32;81 const h = picture.texture.height to f32;82 return [83 picture.region.x / w,84 picture.region.y / h,85 picture.region.right() / w,86 picture.region.bottom() / h87 ];88}8990// How far past its shape the primitive may draw, in its units.91fn margin(92 self p: &Primitive,93 aa: f3294) -> f32 => if (p.kind is ::Shadow) p.params[0] * 3.0 + aa else aa;9596// The innermost clip a node's primitives draw inside, in the clipping97// node's coordinates, and the device rectangle every clip above allows.98pub type ClipState = struct {99 pub area: Rect,100 pub radii: Radii,101 pub inverse: Transform, // device to the clip's coordinates102 pub aa: f32, // the clip's units a device pixel, 0 for no clip103 pub scissor: Rect,104};105106pub fn ClipState::none() -> ClipState {107 const everywhere = Rect::at(-FAR, -FAR, FAR * 2.0, FAR * 2.0);108 return ClipState {109 .area = everywhere,110 .radii = Radii::none(),111 .inverse = Transform::identity(),112 .aa = 0.0,113 .scissor = everywhere114 };115}116117pub type Node = struct {118 pub alive: bool,119 pub generation: u32,120 pub parent: Option<u32>, // none for the root121 pub children: Vector<u32>,122 pub transform: Transform,123 pub clip: Option<Clip>,124 pub paint: Paint,125 pub bounds: Rect, // what its instances may cover, in device pixels126 pub reach: Rect, // what it and the nodes below it may cover127 // changed since: its paint; its transform or clip, or it is new; a descendant128 pub dirty: bool,129 pub moved: bool,130 pub below: bool,131 pub hidden: bool, // drawn with none of its descendants, which keep their paint132 pub opacity: f32, // multiplying the alpha of all it and its descendants draw133 // where its gradients' stops went in the frame drawing it last134 pub stop_frame: u64,135 pub stop_base: f32,136};137138pub fn Node::create(parent: Option<u32>, generation: u32) -> Node {139 return Node {140 .alive = true,141 .generation = generation,142 .parent = parent,143 .children = Vector<u32>::empty(),144 .transform = Transform::identity(),145 .clip = ::None,146 .paint = Paint::empty(),147 .bounds = Rect::empty(),148 .reach = Rect::empty(),149 .dirty = true,150 .moved = true,151 .below = false,152 .hidden = false,153 .opacity = 1.0,154 .stop_frame = 0,155 .stop_base = 0.0156 };157}158159// The node's units a device pixel spans.160pub fn units_per_pixel(t: &Transform) -> f32 {161 const det = abs(t.a * t.d - t.b * t.c);162 return if (det == 0.0) 1.0 else 1.0 / sqrt(det);163}164165// The clip the node's children draw inside. A rectangle inside a166// rounded clip, both upright, keeps the rounded clip's corners: their167// intersection is tested per pixel when it is one rounded rectangle (each168// corner the rounded clip's own or clear of its curve), else the rounded169// clip is, the rectangle cutting by the scissor.170pub fn child_state(self n: &Node, world: &Transform, inner: &ClipState) -> ClipState {171 if (n.clip is ::Some |&clip|) {172 const scissor = inner.scissor.intersection(&world.map_rect(&clip.area));173 if (174 clip.radii == Radii::none()175 && inner.radii != Radii::none()176 && upright(&world)177 && upright(&inner.inverse)178 ) {179 const area = inner.inverse.map_rect(180 &world.map_rect(&clip.area)181 ).intersection(&inner.area);182 var cut = copy inner;183 cut.scissor = scissor;184 if (185 corners_within(&inner.area, &inner.radii, &area, inner.aa * 0.01) is ::Some |radii|186 ) {187 cut.area = area;188 cut.radii = radii;189 }190 return cut;191 }192 return ClipState {193 .area = clip.area,194 .radii = clip.radii,195 .inverse = world.inverse(),196 .aa = units_per_pixel(&world),197 .scissor = scissor198 };199 }200 return copy inner;201}202203// Whether the transform only moves and scales, keeping corners in place.204fn upright(t: &Transform) -> bool => t.b == 0.0 && t.c == 0.0 && t.a > 0.0 && t.d > 0.0;205206// The radii of the area within the rounded rectangle, when the two meet207// in one rounded rectangle: each of the area's corners the outer's own208// (within `near` of it), or clear of the outer's curve there.209fn corners_within(outer: &Rect, radii: &Radii, area: &Rect, near: f32) -> Option<Radii> {210 // how far in from the outer's sides the area's are211 const left = area.x - outer.x;212 const top = area.y - outer.y;213 const right = outer.right() - area.right();214 const bottom = outer.bottom() - area.bottom();215 const tl = corner(left <= near && top <= near, left, top, radii.top_left);216 const tr = corner(right <= near && top <= near, right, top, radii.top_right);217 const br = corner(right <= near && bottom <= near, right, bottom, radii.bottom_right);218 const bl = corner(left <= near && bottom <= near, left, bottom, radii.bottom_left);219 if (tl is ::Some |a| && tr is ::Some |b| && br is ::Some |c| && bl is ::Some |d|) {220 return ::Some(Radii { .top_left = a, .top_right = b, .bottom_right = c, .bottom_left = d });221 }222 return ::None;223}224225// A corner's radius: the outer's where the corners meet, none where the226// area's sides there are a radius in or more, else no one radius.227fn corner(meets: bool, across: f32, down: f32, radius: f32) -> Option<f32> {228 if (meets) {229 return ::Some(radius);230 }231 if (across >= radius || down >= radius) {232 return ::Some(0.0);233 }234 return ::None;235}236237// The device bounds of what the node's paint may cover, at its world238// transform and within its clips: a text's are its layout's box with239// room for glyphs reaching out of their lines.240pub fn measure(self n: &var Node, world: &Transform, inner: &ClipState) {241 n.bounds = Rect::empty();242 const aa = units_per_pixel(&world);243 for (n.paint.items.view()) |&p| {244 var margin = p.margin(aa);245 if (p.kind is ::Text |run|) {246 var size: f32 = 0.0;247 for (n.paint.glyphs.view()[run.first to u64..(run.first + run.count) to u64]) |&g| {248 size = max(size, g.size);249 }250 margin += size * 0.5 + aa;251 }252 const box = world.map_rect(&p.shape.inflated(margin)).intersection(&inner.scissor);253 if (!box.is_empty()) {254 n.bounds = n.bounds.union(&box);255 }256 }257}258259// An instance encoded: its texture's bind group, if it has a texture,260// and whether its gradient's stops are the node's, to place in the261// frame's.262pub type Encoded = struct {263 pub group: Option<u32>,264 pub gradient: bool,265};266267// The instances meeting the rectangle, encoded at the node's world268// transform and clip, into the resources' `scratch` and `encoded`.269pub fn encode(270 self n: &Node,271 world: &Transform,272 inner: &ClipState,273 rect: &Rect,274 gpu: &var Resources,275 device: &var Device,276 fonts: &Option<Fonts>,277 alpha: f32278) {279 const aa = units_per_pixel(&world);280 for (n.paint.items.view()) |&item| {281 if (item.kind is ::Text |run|) {282 if (fonts is ::Some |&f|) {283 n.encode_text(&world, &inner, run, &rect, &var gpu, &var device, &f, alpha);284 }285 continue;286 }287 var p = item;288 p.color.a = p.color.a * alpha;289 const margin = p.margin(aa);290 const box = world.map_rect(&p.shape.inflated(margin)).intersection(&inner.scissor);291 if (box.is_empty() || !box.intersects(&rect)) {292 continue;293 }294 gpu.scratch.append(&p.instance(&world, &inner, margin, aa));295 const group: Option<u32> = match (p.kind) {296 ::Image, ::Mask, ::Colored |s| ::Some(gpu.group_of(&var device, s.texture, s.linear));297 else ::None;298 };299 gpu.encoded.push(Encoded {300 .group = group,301 .gradient = p.kind is ::Linear || p.kind is ::Radial302 });303 }304}305306// Each glyph as a mask from the glyph cache, a color glyph as its colors:307// placed on whole pixels, an outline's at its quarter-pixel shift, where308// the node is only moved and scaled evenly, else its pixels at the node's309// scale, transformed.310fn encode_text(311 self n: &Node,312 w: &Transform,313 inner: &ClipState,314 run: GlyphRun,315 rect: &Rect,316 gpu: &var Resources,317 device: &var Device,318 fonts: &Fonts,319 alpha: f32320) {321 const scale = 1.0 / units_per_pixel(&w);322 const even = w.b == 0.0 && w.c == 0.0 && w.a > 0.0 && w.a == w.d;323 const area = inner.scissor.intersection(&rect);324 // the last glyph's cache page and its bind group: glyphs share a few325 var last_page = Option<Texture>::None;326 var group: u32 = 0;327 for (n.paint.glyphs.view()[run.first to u64..(run.first + run.count) to u64]) |&g| {328 // a glyph well clear of the clip is not rasterized: its outline329 // stays within a few ems of its pen330 const reach = Rect::at(g.x - g.size, g.y - 2.0 * g.size, 4.0 * g.size, 3.0 * g.size);331 if (!w.map_rect(&reach).intersects(&area)) {332 continue;333 }334 const pen = w.apply(Point { .x = g.x, .y = g.y });335 var quarter: u32 = 0;336 var x = pen.x;337 if (even) {338 x = floor(pen.x);339 quarter = floor((pen.x - x) * 4.0 + 0.5) to u32;340 if (quarter == 4) {341 x += 1.0;342 quarter = 0;343 }344 }345 const found = gpu.glyph_cache.glyph(346 &var device,347 &fonts,348 g.face,349 g.glyph,350 g.size * scale,351 quarter,352 &g.color,353 gpu.frames354 );355 const cached = if (found is ::Some |c|) c else {356 continue;357 };358 const page = gpu.glyph_cache.pages.get(cached.page to u64).texture;359 var shape = Rect::empty();360 var world = Transform::identity();361 var aa: f32 = 1.0;362 if (even) {363 if (cached.color) {364 x = floor(pen.x + 0.5); // drawn with no shift365 }366 const y = floor(pen.y + 0.5);367 shape = Rect::at(368 x + cached.left to f32,369 y + cached.top to f32,370 cached.region.width,371 cached.region.height372 );373 } else {374 shape = Rect::at(375 g.x + cached.left to f32 / scale,376 g.y + cached.top to f32 / scale,377 cached.region.width / scale,378 cached.region.height / scale379 );380 world = w;381 aa = units_per_pixel(&w);382 }383 const picture = Picture { .texture = page, .region = cached.region };384 const sampled = Sampled { .texture = page, .linear = true };385 var glyph = Primitive::of(386 if (cached.color) Kind::Colored(sampled) else Kind::Mask(sampled),387 shape,388 Radii::none()389 );390 // a color glyph in its own colors391 glyph.color = if (cached.color) Color::white() else g.color;392 glyph.color.a = glyph.color.a * alpha;393 glyph.extra = picture.texture_bounds();394 const box = world.map_rect(&shape.inflated(aa)).intersection(&inner.scissor);395 if (box.is_empty() || !box.intersects(&rect)) {396 continue;397 }398 gpu.scratch.append(&glyph.instance(&world, &inner, aa, aa));399 group = if (400 last_page is ::Some |t|401 && t == page402 ) group else gpu.group_of(&var device, page, true);403 last_page = ::Some(page);404 gpu.encoded.push(Encoded { .group = ::Some(group), .gradient = false });405 }406}407408// The primitive as the shader's instance.409pub fn instance(410 self p: &Primitive,411 world: &Transform,412 clip: &ClipState,413 margin: f32,414 aa: f32415) -> [f32 : FLOATS] {416 const shape = &p.shape;417 const r = &p.radii;418 const cr = &clip.radii;419 const inverse = &clip.inverse;420 const s = &clip.scissor;421 return [422 shape.x, shape.y, shape.right(), shape.bottom(),423 r.top_left, r.top_right, r.bottom_right, r.bottom_left,424 p.color.r, p.color.g, p.color.b, p.color.a,425 p.kind to u32 to f32, p.params[0], p.params[1], p.params[2],426 world.a, world.b, world.c, world.d,427 world.tx, world.ty, margin, aa,428 p.extra[0], p.extra[1], p.extra[2], p.extra[3],429 clip.area.x, clip.area.y, clip.area.right(), clip.area.bottom(),430 cr.top_left, cr.top_right, cr.bottom_right, cr.bottom_left,431 inverse.a, inverse.b, inverse.c, inverse.d,432 inverse.tx, inverse.ty, clip.aa, 0.0,433 s.x, s.y, s.right(), s.bottom()434 ];435}