1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// What a window target drew of each record of its scene, and the damage the
// scene's changes since make to it. Each frame reads the scene's journal and
// puts the areas the changed records were drawn in into the frame's damage;
// after the collect, which records how it drew each record, it adds the
// areas they are drawn in now.
use cranpose_core::{RecordId, RecordRef, collections::growth_slack::GrowthSlack};
use cranpose_render_common::{
scene_store::{
BLUR_PIXEL_SLACK, JournalEntry, JournalRead, Reach, RecordEvent, RecordEvents, SceneStore,
SceneVersion,
},
space::scene_of,
};
use cranpose_ui_graphics::{Point, Rect};
use crate::{
collect::{LayerScene, ShownArea},
frame::{Capture, Damage, DamageRects, DeviceRect, OwnSake, collect_captures, widen},
};
// The pixels a record's area takes in a target, whole pixels from the
// first to past the last.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PixelBox {
x0: u16,
y0: u16,
x1: u16,
y1: u16,
}
// The pixels of a target that logical rects take: `scale` pixels a unit, a
// `margin` of pixels past a rect all around, in a window `width` by `height`
// pixels, clamped to 65,535.
#[derive(Clone, Copy)]
struct PixelGrid {
scale: f32,
margin: f32,
width: f32,
height: f32,
}
impl PixelGrid {
// The grid of `setting`: a pixel past a rect for filtering and
// snapping, and under a scale of one the blur pixels a reach leaves out.
fn of(setting: TargetSetting) -> Self {
let scale = setting.root_scale;
let (width, height) = setting.viewport;
let most = |pixels: u32| pixels.min(u32::from(u16::MAX)) as f32;
Self {
scale,
margin: 2.0 + BLUR_PIXEL_SLACK * (1.0 - scale).max(0.0),
width: most(width),
height: most(height),
}
}
}
impl PixelBox {
// The pixels of `grid` that `rect`, in logical units, may touch; `None`
// when it touches none.
fn of(rect: Rect, grid: PixelGrid) -> Option<Self> {
let PixelGrid {
scale,
margin,
width,
height,
} = grid;
let x0 = pixel((rect.x * scale - margin).floor(), width);
let y0 = pixel((rect.y * scale - margin).floor(), height);
let x1 = pixel(((rect.x + rect.width) * scale + margin).ceil(), width);
let y1 = pixel(((rect.y + rect.height) * scale + margin).ceil(), height);
(x0 < x1 && y0 < y1).then_some(Self { x0, y0, x1, y1 })
}
fn intersect(self, other: Self) -> Option<Self> {
let x0 = self.x0.max(other.x0);
let y0 = self.y0.max(other.y0);
let x1 = self.x1.min(other.x1);
let y1 = self.y1.min(other.y1);
(x0 < x1 && y0 < y1).then_some(Self { x0, y0, x1, y1 })
}
fn rect(self) -> DeviceRect {
DeviceRect {
x: f32::from(self.x0),
y: f32::from(self.y0),
width: f32::from(self.x1 - self.x0),
height: f32::from(self.y1 - self.y0),
}
}
}
// The pixel `value` lies at in a window `most` pixels long, clamped to it.
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the value is clamped to 0..=most, and most is at most 65,535"
)]
fn pixel(value: f32, most: f32) -> u16 {
value.clamp(0.0, most) as u16
}
// How the target drew a record's subtree.
#[derive(Clone, Copy, Debug, Default)]
enum Area {
// In place, within bounds the walk did not know.
#[default]
Unknown,
Hidden,
Drawn(PixelBox),
// Through the record's own surface, with no areas of what lies beneath
// it: a change there changes all of it.
Composite(PixelBox),
}
impl Area {
fn of(shown: ShownArea, grid: PixelGrid) -> Self {
let pixels = |rect| PixelBox::of(rect, grid);
match shown {
ShownArea::Drawn(rect) => pixels(rect).map_or(Self::Hidden, Self::Drawn),
ShownArea::Composite(rect) => pixels(rect).map_or(Self::Hidden, Self::Composite),
ShownArea::Hidden => Self::Hidden,
ShownArea::Unknown => Self::Unknown,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Shown {
generation: u32,
area: Area,
// Where the record drew its own draws, beside its children.
own: Area,
// Where the origin of the record's space lay, when the target drew the
// record in place and only moved its space there.
origin: Option<Point>,
}
impl Shown {
// The part of the record's own area that `within`, in the record's
// space, covers.
fn own_part(self, within: Reach, setting: TargetSetting) -> Area {
let (Reach::Finite(rect), Some(origin)) = (within, self.origin) else {
return if within == Reach::Empty {
Area::Hidden
} else {
self.own
};
};
let part = PixelBox::of(rect.translate(origin.x, origin.y), PixelGrid::of(setting));
match (self.own, part) {
(_, None) | (Area::Hidden, _) => Area::Hidden,
(Area::Drawn(own), Some(part)) => part.intersect(own).map_or(Area::Hidden, Area::Drawn),
(Area::Unknown, Some(part)) => Area::Drawn(part),
(own @ Area::Composite(_), Some(_)) => own,
}
}
}
// How a culled walk takes a record.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Visit {
// It leaves the record out: it lies outside the region, as it did.
Skip,
// It walks the record, culling beneath it.
Walk,
// It walks all the record's subtree: the subtree moved or is new.
WalkAll,
}
// What a window's walk leaves out: the records that did not change and lie
// outside a region, as the target last drew them.
pub(crate) struct Cull<'a> {
region: &'a DamageRects,
shown: &'a [Shown],
marks: &'a [(u32, Visit)],
stamp: u32,
}
impl Cull<'_> {
// How the walk takes `record`.
pub(crate) fn visit(&self, record: RecordRef) -> Visit {
let row = record.id.index();
if let Some(&(stamp, visit)) = self.marks.get(row)
&& stamp == self.stamp
{
return visit;
}
let Some(shown) = self
.shown
.get(row)
.filter(|shown| shown.generation == record.generation)
else {
return Visit::Walk;
};
match shown.area {
Area::Drawn(pixels) | Area::Composite(pixels) if !self.region.meets(pixels.rect()) => {
Visit::Skip
}
Area::Hidden => Visit::Skip,
Area::Drawn(_) | Area::Composite(_) | Area::Unknown => Visit::Walk,
}
}
}
// What of a record a change reaches.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Scope {
// All the record's subtree draws.
Subtree,
// All the record's subtree draws, placed anew: the record moved or is
// new.
Placed,
// What the record draws of its own, within the reach in its space.
Own(Reach),
}
impl Scope {
fn of(event: RecordEvent) -> Self {
match event {
RecordEvent::Redrawn(within) => Self::Own(within),
RecordEvent::Moved | RecordEvent::Inserted => Self::Placed,
_ => Self::Subtree,
}
}
}
/// What draws every pixel of a frame beside its records: a frame of another
/// setting than the frame before draws whole.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TargetSetting {
pub(crate) viewport: (u32, u32),
pub(crate) root_scale: f32,
pub(crate) clear: wgpu::Color,
// The generation of the debug toggles, which any thread may flip.
pub(crate) debug_toggles: u64,
}
/// The most frames in a row a target whose frames keep changing most of
/// the window skips working out their damage: about four seconds at 60 Hz.
const MAX_SKIPPED: u32 = 256;
/// The frames to skip at or past which a target lets its areas go until it
/// records them again: after four frames in a row changed most of the
/// window.
const RELEASE_SKIPS: u32 = 64;
/// How a frame went into a target that keeps its frames.
#[derive(Clone, Copy, Debug)]
pub(crate) struct TargetDrawn {
/// What the frame changed in the target.
pub(crate) damage: Damage,
/// Whether the packet was one to skip working out its damage.
pub(crate) skipped: bool,
/// Whether the packet knew the frame before it.
pub(crate) knew_before: bool,
// Why the frame drew whole for the target's sake.
pub(crate) own_sake: Option<OwnSake>,
}
#[derive(Default)]
pub(crate) struct TargetState {
// The version of the records read last.
read: Option<SceneVersion>,
// By record row, how the target last drew the record.
shown: Vec<Shown>,
setting: Option<TargetSetting>,
damage: DamageRects,
// Whether the frame changes the whole window: an area it changes is not
// known.
whole: bool,
// Whether the frame before is not known: the frame draws whole, and that
// says nothing of how much of the window it changes.
unknown_before: bool,
// The records the frame's changes leave and what of each they reach,
// whose new areas the frame adds after its collect.
changed: Vec<(RecordRef, Scope)>,
// The damage of the old areas, and whether one is not known, which each
// end of the frame starts from.
begun: (DamageRects, bool),
// By row, the frame that marked the record and how a culled walk of
// that frame takes it.
marks: Vec<(u32, Visit)>,
stamp: u32,
path: Vec<RecordId>,
captures: Vec<Capture>,
// While frames keep changing most of the window, the frames left to
// skip: 1, 4, 16, 64 and then [`MAX_SKIPPED`] after each such frame.
skipped: u32,
// The frames in a row that changed most of the window.
full_frames: u32,
// Whether the areas describe a frame before skipped ones, so the next
// frame that records them draws whole.
stale: bool,
// Whether the frame in progress records its areas and works out its
// damage.
recording: bool,
// Whether the frame in progress, skipped, changes nothing at all.
still: bool,
// The root the frame before drew.
last_root: Option<RecordRef>,
// When the records' changes since the frame before are lost, the area
// the frame before drew the root in.
lost_root: Option<Area>,
}
impl TargetState {
/// Ends a run of frames that changed most of the window: the app held
/// still since the frame before.
pub(crate) fn held_still(&mut self) {
self.skipped = 0;
self.full_frames = 0;
}
/// Starts a frame of `setting` of the records of `source`: reads their
/// changes since the frame before, and puts the areas the frame before
/// drew the changed records in into the frame's damage.
pub(crate) fn begin(&mut self, store: &SceneStore, setting: TargetSetting) {
self.damage.clear();
self.changed.clear();
let read = self.read.replace(store.version());
self.recording = self.skipped == 0;
if !self.recording {
// A frame that changes nothing says so, skipped or not.
let same = self.setting == Some(setting);
self.still = same && !store.changed_since(read);
return;
}
self.whole = false;
self.lost_root = None;
self.unknown_before = std::mem::take(&mut self.stale) || self.setting != Some(setting);
self.setting = Some(setting);
match store.changes_since(read) {
// The records went or were replaced: all the root drew before
// and draws now changes.
JournalRead::Lost => {
self.lost_root = Some(
self.last_root
.and_then(|root| self.shown(root))
.map_or(Area::Hidden, |shown| shown.area),
);
}
JournalRead::Changes(entries) => {
for entry in entries {
if self.whole || self.unknown_before {
break;
}
self.note(store, entry);
}
}
}
self.begun.0.assign(&self.damage);
self.begun.1 = self.whole;
}
// The changes the records keep for the target from the next update on:
// a frame that skips working out its damage needs only whether
// anything changed, which the store tells without entries.
pub(crate) fn followed(&self) -> RecordEvents {
if self.recording {
RecordEvents::ALL
} else {
RecordEvents::NONE
}
}
// The damage of the areas the frame before drew the changed records in;
// `None` when the frame works out no damage or one of them is not
// known.
pub(crate) fn begun(&self) -> Option<&DamageRects> {
let known = self.recording && !self.unknown_before && self.lost_root.is_none();
(known && !self.begun.1).then_some(&self.begun.0)
}
// Writes into `damage` the damage the frame takes when each moved and
// new record takes the area the frame before tells for it: its reach,
// placed at the origin the frame before drew its parent's space at. The
// whole window when a moved record's reach is not known: the walk finds
// that record's area unknown too. `false` when the frame works out no
// damage, an old area is not known, or a moved record casts an
// elevation shadow or lies under a parent the frame before drew through
// a surface or under a turn: the walk then works the areas out.
pub(crate) fn predict_damage(&self, store: &SceneStore, damage: &mut Damage) -> bool {
let (Some(setting), Some(begun)) = (self.setting, self.begun()) else {
return false;
};
damage.assign_part(begun);
for &(record, scope) in &self.changed {
let (Scope::Placed, Some(id)) = (scope, store.resolve(record)) else {
continue;
};
let extent = store.layer(id).extent();
let rect = match (extent.reach, extent.caster) {
(Reach::Unknown, _) => {
*damage = Damage::Full;
return true;
}
(Reach::Finite(rect), None) => rect,
(Reach::Empty, None) => continue,
(_, Some(_)) => return false,
};
let Some(origin) = store
.parent(id)
.and_then(|parent| self.shown(store.record_ref(parent)))
.and_then(|shown| shown.origin)
else {
return false;
};
let placed = rect.translate(origin.x, origin.y);
if let (Some(pixels), Damage::Part(rects)) =
(PixelBox::of(placed, PixelGrid::of(setting)), &mut *damage)
{
rects.add(pixels.rect());
}
}
damage.settle(setting.viewport);
true
}
// What a walk of the frame leaves out of `region` of the records of
// `store`: it walks every changed record and its ancestors, and all of
// a moved or new record's subtree.
pub(crate) fn cull<'a>(&'a mut self, store: &SceneStore, region: &'a DamageRects) -> Cull<'a> {
self.stamp = self.stamp.wrapping_add(1).max(1);
for at in 0..self.changed.len() {
let (record, scope) = self.changed[at];
let Some(id) = store.resolve(record) else {
continue;
};
let visit = match scope {
Scope::Subtree | Scope::Placed => Visit::WalkAll,
Scope::Own(_) => Visit::Walk,
};
let mut next = self.mark(id.index(), visit).then_some(id);
while let Some(parent) = next.and_then(|id| store.parent(id)) {
next = self.mark(parent.index(), Visit::Walk).then_some(parent);
}
}
Cull {
region,
shown: &self.shown,
marks: &self.marks,
stamp: self.stamp,
}
}
// Marks the record at `row` for the frame's walk to take as `visit` at
// least; returns whether the frame marked it first now.
fn mark(&mut self, row: usize, visit: Visit) -> bool {
if row >= self.marks.len() {
self.marks.resize(row + 1, (0, Visit::Skip));
}
let mark = &mut self.marks[row];
let first = mark.0 != self.stamp;
*mark = (self.stamp, if first { visit } else { mark.1.max(visit) });
first
}
// Puts the area the frame before drew the record of `entry` in into the
// damage, and keeps the record to add its area after the collect.
fn note(&mut self, store: &SceneStore, entry: &JournalEntry) {
let scope = Scope::of(entry.event);
if !matches!(entry.event, RecordEvent::Inserted | RecordEvent::Claimed) {
let area = self.area_of(store, (entry.record, scope), entry.parent);
self.add(area);
}
if entry.event != RecordEvent::Removed {
self.changed.push((entry.record, scope));
}
}
/// Whether the frame records how it draws each record: a frame skipped
/// while frames keep changing most of the window does not.
pub(crate) fn records(&self) -> bool {
self.recording
}
/// Ends the frame whose collect drew `root`: keeps how it drew each
/// record, adds the areas the changed records are drawn in now, and
/// writes the frame's damage into `damage`.
pub(crate) fn end(
&mut self,
store: &SceneStore,
root: Option<&LayerScene>,
damage: &mut Damage,
) {
if !self.recording {
if self.still {
damage.assign_part(&DamageRects::default());
} else {
*damage = Damage::Skipped;
}
return;
}
self.ended(store, root, damage);
self.last_root = store.root().map(|root| store.record_ref(root));
}
/// Whether the frame in progress knew the frame before it: one that did
/// not draws whole, as the frame later frames compare with.
pub(crate) fn knew_before(&self) -> bool {
!self.recording || !self.unknown_before
}
/// Follows how the renderer drew a frame into a target that keeps its
/// frames. A frame skipped counts towards the frames to skip. After a
/// frame that changed the whole target, though its packet knew the frame
/// before, frames skip working out their damage: 1, 4, 16, 64 and then
/// [`MAX_SKIPPED`] frames, each such frame in a row quadrupling them;
/// past [`RELEASE_SKIPS`], the areas go until a frame records them
/// again.
pub(crate) fn drawn(&mut self, drawn: &TargetDrawn) {
if drawn.skipped {
self.skipped = self.skipped.saturating_sub(1);
return;
}
match (&drawn.damage, drawn.own_sake) {
// Stand-ins go once their pipelines land: a frame drawn whole
// over them says nothing of what the page changes.
(Damage::Full, Some(OwnSake::StandIns)) => return,
(Damage::Full, _) if drawn.knew_before => {}
(Damage::Full | Damage::Skipped, _) => return,
(Damage::Part(_), _) => {
self.full_frames = 0;
return;
}
}
self.full_frames = self.full_frames.saturating_add(1);
// A target that held no frame took this one whole for its own sake:
// the skips start with the second such frame in a row.
let run = self.full_frames - u32::from(drawn.own_sake == Some(OwnSake::NoFrame));
if run == 0 {
return;
}
let doublings = 2 * (run - 1);
self.skipped = 1u32 << doublings.min(MAX_SKIPPED.trailing_zeros());
self.stale = true;
if self.skipped >= RELEASE_SKIPS {
self.shown = Vec::new();
self.changed = Vec::new();
self.path = Vec::new();
self.captures = Vec::new();
}
}
fn ended(&mut self, store: &SceneStore, root: Option<&LayerScene>, damage: &mut Damage) {
let Some(setting) = self.setting else {
*damage = Damage::Full;
return;
};
self.damage.assign(&self.begun.0);
self.whole = self.begun.1;
let shown = root.map_or(&[][..], |root| &root.shown);
let grid = PixelGrid::of(setting);
for shown in shown {
let row = shown.record.id.index();
if row >= self.shown.len() {
self.shown.resize(row + 1, Shown::default());
}
let area = Area::of(shown.area, grid);
// Most records draw all they draw themselves: a leaf, and a
// record drawn through its own surface.
let own = if shown.own == shown.area {
area
} else {
Area::of(shown.own, grid)
};
self.shown[row] = Shown {
generation: shown.record.generation,
area,
own,
origin: shown.origin,
};
}
// By row arrays doubled to take a record; the room past a quarter
// of their rows goes back.
self.shown.trim_growth_slack();
self.marks.trim_growth_slack();
if self.unknown_before {
*damage = Damage::Full;
return;
}
if let Some(before) = self.lost_root {
let now = store
.root()
.and_then(|root| self.shown(store.record_ref(root)))
.map_or(Area::Hidden, |shown| shown.area);
self.add(before);
self.add(now);
}
for at in 0..self.changed.len() {
if self.whole {
break;
}
let (record, scope) = self.changed[at];
if store.resolve(record).is_some() {
let area = self.area_of(store, (record, scope), None);
self.add(area);
}
}
if self.whole {
*damage = Damage::Full;
return;
}
if let Some(root) = root.filter(|root| !self.damage.is_empty() && root.contains_backdrop())
{
self.captures.clear();
let place = (setting.root_scale, setting.viewport);
if !collect_captures(root, place, &mut self.captures) {
*damage = Damage::Full;
return;
}
widen(&self.captures, &mut self.damage);
}
damage.assign_part(&self.damage);
damage.settle(setting.viewport);
}
// The area the target drew `record` in, as the target's areas say: that
// of its topmost ancestor drawn hidden or through a surface, or that
// shows a scene, else its own. The walk keeps no area of a record in a
// scene's space, and a change there changes all the scene draws. A
// record gone from the store is found under `parent`; one whose parent
// went too lies in the area of that parent.
fn area_of(
&mut self,
store: &SceneStore,
(record, scope): (RecordRef, Scope),
parent: Option<RecordRef>,
) -> Area {
let mut current = match store.resolve(record) {
Some(id) => store.parent(id),
None => match parent {
Some(parent) => match store.resolve(parent) {
Some(id) => Some(id),
None => return Area::Hidden,
},
None => None,
},
};
self.path.clear();
while let Some(id) = current {
self.path.push(id);
current = store.parent(id);
}
for &ancestor in self.path.iter().rev() {
let area = self
.shown(store.record_ref(ancestor))
.map(|shown| shown.area);
if scene_of(store.layer(ancestor)).is_some() {
return match area {
Some(Area::Drawn(pixels)) => Area::Composite(pixels),
Some(area) => area,
None => Area::Hidden,
};
}
match area {
Some(Area::Drawn(_) | Area::Unknown) => {}
Some(area) => return area,
// An ancestor new since the frame: the record moved under
// it, and its old parent's change holds where it was.
None => return Area::Hidden,
}
}
let Some(setting) = self.setting else {
return Area::Unknown;
};
self.shown(record)
.map_or(Area::Hidden, |shown| match scope {
Scope::Subtree | Scope::Placed => shown.area,
Scope::Own(within) => shown.own_part(within, setting),
})
}
fn shown(&self, record: RecordRef) -> Option<Shown> {
self.shown
.get(record.id.index())
.filter(|shown| shown.generation == record.generation)
.copied()
}
fn add(&mut self, area: Area) {
match area {
Area::Drawn(pixels) | Area::Composite(pixels) => self.damage.add(pixels.rect()),
Area::Hidden => {}
Area::Unknown => self.whole = true,
}
}
}