1// A frame: nodes changed since the last encoded again, their old and new2// bounds damaged, then the instances touching each damaged rectangle3// gathered in painter's order, in runs of one texture, and drawn under4// its scissor into the kept texture, which is copied to the frame or,5// for a canvas over another's drawing, blended over it.67import std::vector;8import std::option;9import std::math;10import pkg::alloy::gpu;11import pkg::alloy::window;1213import draw;14import encoding;15import damage;16import atlas;17import glyphs;1819// What a canvas made on the device.20pub type Resources = struct {21 pub shader: Shader,22 pub draw: RenderPipeline, // premultiplied blending23 pub clear: RenderPipeline, // replacing, for a rectangle's background24 pub white: Texture,25 pub linear: Sampler,26 pub nearest: Sampler,27 pub uniform: Buffer,28 pub instances: Buffer,29 pub stops: Buffer,30 pub globals: BindGroup,31 pub groups: Vector<TextureGroup>, // the first the white texture's32 pub kept: Option<Texture>,33 pub pages: Vector<Page>,34 pub owned: Vector<Texture>,35 pub floats: Vector<f32>, // the frame's instances, the first `used`36 // a node's instances as it is gathered, and what each needs37 pub scratch: Vector<f32>,38 pub encoded: Vector<Encoded>,39 pub used: u64,40 pub stop_floats: Vector<f32>,41 pub frames: u64,42 pub glyph_cache: GlyphCache,43};4445pub type TextureGroup = struct {46 pub texture: Texture,47 pub linear: bool,48 pub group: BindGroup,49};5051// A draw of instances in a row, all using one texture's group, or none52// yet.53type Run = struct {54 rect: u64,55 first: u32,56 count: u32,57 group: Option<u32>,58 clear: bool,59};6061pub fn Resources::create(device: &var Device, shader: &[u8], format: TextureFormat) -> Resources {62 const module = device.shader(&shader);63 var descriptor = RenderPipelineDescriptor::simple(module, format);64 descriptor.blend = Blend::Premultiplied;65 const draw = device.render_pipeline(&descriptor);66 descriptor.blend = Blend::Replace;67 const clear = device.render_pipeline(&descriptor);68 const white = device.texture(&TextureDescriptor {69 .width = 1,70 .height = 1,71 .format = TextureFormat::Rgba8Unorm,72 .usage = TEXTURE_SAMPLED | TEXTURE_COPY_DESTINATION73 });74 device.write_texture(white, &[255, 255, 255, 255]);75 const usage = BUFFER_STORAGE | BUFFER_COPY_DESTINATION;76 const uniform = device.buffer(16, BUFFER_UNIFORM | BUFFER_COPY_DESTINATION);77 const instances = device.buffer(256 * FLOATS * 4, usage);78 const stops = device.buffer(1024, usage);79 var g = Resources {80 .shader = module,81 .draw = draw,82 .clear = clear,83 .white = white,84 .linear = device.sampler(&SamplerDescriptor { .linear = true, .repeat = false }),85 .nearest = device.sampler(&SamplerDescriptor { .linear = false, .repeat = false }),86 .uniform = uniform,87 .instances = instances,88 .stops = stops,89 .globals = globals(&var device, draw, uniform, instances, stops),90 .groups = Vector<TextureGroup>::empty(),91 .kept = ::None,92 .pages = Vector<Page>::empty(),93 .owned = Vector<Texture>::empty(),94 .floats = Vector<f32>::empty(),95 .scratch = Vector<f32>::empty(),96 .encoded = Vector<Encoded>::empty(),97 .used = 0,98 .stop_floats = Vector<f32>::empty(),99 .frames = 0,100 .glyph_cache = GlyphCache::create()101 };102 g.group_of(&var device, white, true);103 return move g;104}105106fn globals(107 device: &var Device,108 pipeline: RenderPipeline,109 uniform: Buffer,110 instances: Buffer,111 stops: Buffer112) -> BindGroup {113 const bindings: [Binding : 3] = [114 Binding { .binding = 0, .resource = BindingResource::Buffer(uniform) },115 Binding { .binding = 1, .resource = BindingResource::Buffer(instances) },116 Binding { .binding = 2, .resource = BindingResource::Buffer(stops) }117 ];118 return device.bind_group(pipeline, 0, &bindings);119}120121// The index of the texture's bind group, made the first time.122pub fn group_of(123 self g: &var Resources,124 device: &var Device,125 texture: Texture,126 linear: bool127) -> u32 {128 for (g.groups.view(), [..g.groups.length()]) |&t, k| {129 if (t.texture == texture && t.linear == linear) {130 return k to u32;131 }132 }133 const bindings: [Binding : 2] = [134 Binding { .binding = 0, .resource = BindingResource::Texture(texture) },135 Binding {136 .binding = 1,137 .resource = BindingResource::Sampler(if (linear) g.linear else g.nearest)138 }139 ];140 g.groups.push(TextureGroup {141 .texture = texture,142 .linear = linear,143 .group = device.bind_group(g.draw, 1, &bindings)144 });145 return g.groups.length() to u32 - 1;146}147148// Releases the texture's bind groups, whose indices last only a frame.149pub fn forget(self g: &var Resources, device: &var Device, texture: Texture) {150 var k: u64 = 0;151 while (k < g.groups.length()) {152 if (g.groups.get(k).texture == texture) {153 device.release(g.groups.get(k).group);154 g.groups.swap_remove(k);155 } else {156 k += 1;157 }158 }159}160161// Releases the pictures' pages holding none, but a format's last.162fn release_empty_pages(self g: &var Resources, device: &var Device) {163 var k: u64 = 0;164 while (k < g.pages.length()) {165 const page = &g.pages.get(k);166 var others: u32 = 0;167 for (g.pages.view()) |&p| {168 if (p.texture.format == page.texture.format) {169 others += 1;170 }171 }172 if (page.held == 0 && others > 1) {173 const texture = page.texture;174 g.forget(&var device, texture);175 device.release(texture);176 g.pages.swap_remove(k);177 } else {178 k += 1;179 }180 }181}182183pub fn release(self g: &var Resources, device: &var Device) {184 for (g.groups.view()) |&t| {185 device.release(t.group);186 }187 g.groups.clear();188 device.release(g.globals);189 for (g.pages.view()) |&p| {190 device.release(p.texture);191 }192 g.pages.clear();193 for (g.owned.view()) |t| {194 device.release(t);195 }196 g.owned.clear();197 g.glyph_cache.release(&var device);198 if (g.kept is ::Some |k|) {199 device.release(k);200 }201 g.kept = ::None;202 device.release(g.white);203 device.release(g.linear);204 device.release(g.nearest);205 device.release(g.uniform);206 device.release(g.instances);207 device.release(g.stops);208 device.release(g.draw);209 device.release(g.clear);210 device.release(g.shader);211}212213pub fn draw_frame(214 self c: &var Canvas,215 device: &var Device,216 encoder: &var Encoder,217 frame: Texture,218 over: bool219) {220 if (frame.format != c.format) {221 panic "pkg::alloy::draw: a frame of another format than the canvas's";222 }223 const size = Size { .width = frame.width, .height = frame.height };224 if (c.gpu.kept is ::None || c.size.width != size.width || c.size.height != size.height) {225 if (c.gpu.kept is ::Some |k|) {226 c.gpu.forget(&var device, k); // the group blending it over227 device.release(k);228 }229 c.gpu.kept = ::Some(device.texture(&TextureDescriptor {230 .width = size.width,231 .height = size.height,232 .format = c.format,233 .usage = TEXTURE_RENDER_TARGET | TEXTURE_COPY_SOURCE | TEXTURE_SAMPLED234 }));235 c.size = size;236 c.everything = true;237 }238 var full = c.everything;239 const kept = if (c.gpu.kept is ::Some |k|) k else {240 return;241 };242 // glyphs' plots cleared and pages released: what drew from them is in243 // the kept texture, and frames to come find their glyphs again244 const released = c.gpu.glyph_cache.evict(&var device, c.gpu.frames);245 for (released.view()) |t| {246 c.gpu.forget(&var device, t);247 }248 c.gpu.release_empty_pages(&var device);249 c.update(&var device, 0, &Transform::identity(), &ClipState::none(), false);250 c.gpu.frames += 1;251 const whole = Rect::sized(size.width to f32, size.height to f32);252 var rects = merged(&c.damage.view(), size);253 c.damage.clear();254 c.everything = false;255 c.pending = false;256 var area: f32 = 0.0;257 for (rects.view()) |&r| {258 area += r.area();259 }260 if (area * 10.0 >= whole.area() * 6.0) {261 full = true;262 }263 if (full) {264 rects.clear();265 rects.push(whole);266 }267268 // the instances, in runs269 c.gpu.used = 0;270 c.gpu.stop_floats.clear();271 var runs = Vector<Run>::empty();272 for (rects.view(), [..rects.length()]) |&r, k| {273 if (!full) {274 var p = Primitive::of(Kind::Clear, r, Radii::none());275 p.color = c.background;276 runs.push(Run {277 .rect = k,278 .first = (c.gpu.used / FLOATS) to u32,279 .count = 1,280 .group = ::None,281 .clear = true282 });283 c.gpu.append(&p.instance(&Transform::identity(), &ClipState::none(), 0.0, 1.0));284 }285 runs.push(Run {286 .rect = k,287 .first = (c.gpu.used / FLOATS) to u32,288 .count = 0,289 .group = ::None,290 .clear = false291 });292 c.gather(&var device, 0, &Transform::identity(), &ClipState::none(), &r, 1.0, &var runs);293 }294 if (c.gpu.stop_floats.length() == 0) {295 // a buffer to bind, with no stop in it296 c.gpu.stop_floats.append(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);297 }298 // over another's drawing, the kept texture is one image over the frame299 const blended = (c.gpu.used / FLOATS) to u32;300 if (over) {301 var p = Primitive::of(302 Kind::Image(Sampled { .texture = kept, .linear = false }),303 whole,304 Radii::none()305 );306 p.color = Color::white();307 p.extra = [0.0, 0.0, 1.0, 1.0];308 c.gpu.append(&p.instance(&Transform::identity(), &ClipState::none(), 0.0, 1.0));309 }310 c.gpu.upload(&var device, size);311312 // the drawing, when anything changed313 var drawing = full;314 for (runs.view()) |&run| {315 drawing = drawing || run.count != 0;316 }317 var draws: u32 = 0;318 if (drawing) {319 c.draw_runs(&var encoder, kept, full, &runs.view(), &rects.view(), &var draws);320 }321 if (over) {322 const group = c.gpu.group_of(&var device, kept, false);323 encoder.begin_render_pass(frame, Option<Color>::None);324 encoder.set_scissor(0, 0, size.width, size.height);325 encoder.set_pipeline(c.gpu.draw);326 encoder.set_bind_group(c.gpu.globals);327 encoder.set_bind_group(c.gpu.groups.get(group to u64).group);328 encoder.draw_from(6, 1, 0, blended);329 encoder.end_render_pass();330 draws += 1;331 } else {332 encoder.copy_texture(kept, frame);333 }334 c.stats.rects = move rects;335 c.stats.full = full;336 c.stats.instances = (c.gpu.used / FLOATS) to u32;337 c.stats.draws = draws;338}339340// Draws the runs into the kept texture, each under its rectangle's341// scissor, clearing it first when the whole frame is drawn.342fn draw_runs(343 self c: &var Canvas,344 encoder: &var Encoder,345 kept: Texture,346 full: bool,347 runs: &[Run],348 rects: &[Rect],349 draws: &var u32350) {351 const background = c.background;352 encoder.begin_render_pass(kept, if (full) ::Some(Color::rgba(353 background.r * background.a,354 background.g * background.a,355 background.b * background.a,356 background.a357 )) else Option<Color>::None);358 // what is set only when it changes: the scissor, the pipeline, by359 // whether it clears, and the texture's group360 var scissor: Option<u64> = ::None;361 var clearing: Option<bool> = ::None;362 var bound: Option<u32> = ::None;363 for (runs) |&run| {364 if (run.count == 0) {365 continue;366 }367 if (scissor != ::Some(run.rect)) {368 scissor = ::Some(run.rect);369 const s = rects[run.rect];370 encoder.set_scissor(s.x to u32, s.y to u32, s.width to u32, s.height to u32);371 }372 if (clearing != ::Some(run.clear)) {373 clearing = ::Some(run.clear);374 encoder.set_pipeline(if (run.clear) c.gpu.clear else c.gpu.draw);375 encoder.set_bind_group(c.gpu.globals);376 bound = ::None;377 }378 // the white texture's group for a run drawing none379 const group = run.group.unwrap_or(0);380 if (bound != ::Some(group)) {381 bound = ::Some(group);382 encoder.set_bind_group(c.gpu.groups.get(group to u64).group);383 }384 encoder.draw_from(6, run.count, 0, run.first);385 draws += 1;386 }387 encoder.end_render_pass();388}389390// Measures again what changed under the node, damaging where it was and391// where it is.392fn update(393 self c: &var Canvas,394 device: &var Device,395 index: u32,396 parent_world: &Transform,397 inherited: &ClipState,398 forced: bool399) {400 const n = &var c.nodes.get_var(index to u64);401 // a hidden node covers nothing; it is measured again once shown,402 // `set_hidden` marking it moved403 if (n.hidden) {404 n.moved = true;405 n.reach = Rect::empty();406 return;407 }408 const moved = forced || n.moved;409 const world = n.transform.then(&parent_world);410 if (moved || n.dirty) {411 const old = n.bounds;412 n.measure(&world, &inherited);413 c.add_damage(old);414 c.add_damage(c.nodes.get(index to u64).bounds);415 }416 const node = &var c.nodes.get_var(index to u64);417 node.dirty = false;418 node.moved = false;419 if (moved || node.below) {420 node.below = false;421 const state = node.child_state(&world, &inherited);422 const count = node.children.length();423 for ([..count]) |k| {424 const child = c.nodes.get(index to u64).children.get(k);425 c.update(&var device, child, &world, &state, moved);426 }427 }428 // what the subtree may cover, which gathering skips it outside429 var reach = c.nodes.get(index to u64).bounds;430 for (c.nodes.get(index to u64).children.view()) |child| {431 reach = reach.union(&c.nodes.get(child to u64).reach);432 }433 c.nodes.get_var(index to u64).reach = reach;434}435436// Adds the node's instances touching the rectangle, then its437// children's, their alpha multiplied by the opacities above them.438fn gather(439 self c: &var Canvas,440 device: &var Device,441 index: u32,442 parent_world: &Transform,443 inherited: &ClipState,444 rect: &Rect,445 parent_alpha: f32,446 runs: &var Vector<Run>447) {448 const alpha = parent_alpha * c.nodes.get(index to u64).opacity;449 if (alpha <= 0.0 || !c.nodes.get(index to u64).reach.intersects(&rect)) {450 return;451 }452 const world = c.nodes.get(index to u64).transform.then(&parent_world);453 if (c.nodes.get(index to u64).bounds.intersects(&rect)) {454 c.gpu.scratch.clear();455 c.gpu.encoded.clear();456 c.nodes.get(index to u64).encode(457 &world,458 &inherited,459 &rect,460 &var c.gpu,461 &var device,462 &c.fonts,463 alpha464 );465 for ([..c.gpu.encoded.length()]) |k| {466 const at = c.gpu.used;467 c.gpu.append(&c.gpu.scratch.view()[k * FLOATS..(k + 1) * FLOATS]);468 const encoded = c.gpu.encoded.get(k);469 if (encoded.gradient) {470 const base = c.stops_of(index, alpha);471 c.gpu.floats.get_var(at + 13) += base;472 }473 const last = &var runs.get_var(runs.length() - 1);474 if (475 encoded.group is ::Some |group|476 && last.group is ::Some |current|477 && current != group478 ) {479 runs.push(Run {480 .rect = last.rect,481 .first = (at / FLOATS) to u32,482 .count = 1,483 .group = encoded.group,484 .clear = false485 });486 } else {487 if (encoded.group is ::Some) {488 last.group = encoded.group;489 }490 last.count += 1;491 }492 }493 }494 const state = c.nodes.get(index to u64).child_state(&world, &inherited);495 const count = c.nodes.get(index to u64).children.length();496 for ([..count]) |k| {497 c.gather(498 &var device,499 c.nodes.get(index to u64).children.get(k),500 &world,501 &state,502 &rect,503 alpha,504 &var runs505 );506 }507}508509// Where the node's gradient stops start in the frame's, in 4 floats,510// put there the first time the frame asks, their alpha multiplied.511fn stops_of(self c: &var Canvas, index: u32, alpha: f32) -> f32 {512 var n = &var c.nodes.get_var(index to u64);513 if (n.stop_frame != c.gpu.frames) {514 n.stop_frame = c.gpu.frames;515 const start = c.gpu.stop_floats.length();516 n.stop_base = (start / 4) to f32;517 c.gpu.stop_floats.append(&n.paint.stops.view());518 if (alpha < 1.0) {519 // a stop is its color, then its offset, 4 floats each520 var k = start + 3;521 while (k < c.gpu.stop_floats.length()) {522 c.gpu.stop_floats.get_var(k) *= alpha;523 k += 8;524 }525 }526 }527 return n.stop_base;528}529530// Puts the floats after the frame's first `used`, over what an earlier531// frame left there.532fn append(self g: &var Resources, floats: &[f32]) {533 const end = g.used + floats.length();534 const fits = min(end, g.floats.length());535 if (fits > g.used) {536 g.floats.items()[g.used..fits] = floats[..fits - g.used];537 }538 if (end > fits) {539 g.floats.append(&floats[fits - g.used..]);540 }541 g.used = end;542}543544// Writes the frame's size, instances and stops into the buffers, larger545// ones first when they have outgrown them.546fn upload(self g: &var Resources, device: &var Device, size: Size) {547 const instance_bytes = g.used * 4;548 const stop_bytes = g.stop_floats.length() * 4;549 if (instance_bytes > g.instances.size || stop_bytes > g.stops.size) {550 const usage = BUFFER_STORAGE | BUFFER_COPY_DESTINATION;551 if (instance_bytes > g.instances.size) {552 device.release(g.instances);553 g.instances = device.buffer(grown(g.instances.size, instance_bytes), usage);554 }555 if (stop_bytes > g.stops.size) {556 device.release(g.stops);557 g.stops = device.buffer(grown(g.stops.size, stop_bytes), usage);558 }559 device.release(g.globals);560 g.globals = globals(&var device, g.draw, g.uniform, g.instances, g.stops);561 }562 const frame: [f32 : 4] = [size.width to f32, size.height to f32, 0.0, 0.0];563 device.write_buffer(g.uniform, 0, &frame[..] as &[u8]);564 if (g.used > 0) {565 device.write_buffer(g.instances, 0, &g.floats.view()[..g.used] as &[u8]);566 }567 device.write_buffer(g.stops, 0, &g.stop_floats.view() as &[u8]);568}569570fn grown(size: u64, needed: u64) -> u64 {571 var out = size;572 while (out < needed) {573 out *= 2;574 }575 return out;576}