1use crate::DrawBeginClip;
5
6use super::{
7 DrawBlurRoundedRect, DrawColor, DrawImage, DrawLinearGradient, DrawRadialGradient,
8 DrawSweepGradient, DrawTag, Glyph, GlyphRun, NormalizedCoord, Patch, PathEncoder, PathTag,
9 Style, Transform,
10};
11
12use peniko::color::{DynamicColor, palette};
13use peniko::kurbo::{Shape, Stroke};
14use peniko::{
15 BrushRef, ColorStop, Extend, Fill, GradientKind, ImageBrushRef, ImageSampler,
16 LinearGradientPosition, RadialGradientPosition, SweepGradientPosition,
17};
18
19#[derive(Clone, Default)]
26pub struct Encoding {
27 pub path_tags: Vec<PathTag>,
29 pub path_data: Vec<u32>,
33 pub draw_tags: Vec<DrawTag>,
35 pub draw_data: Vec<u32>,
37 pub transforms: Vec<Transform>,
39 pub styles: Vec<Style>,
41 pub resources: Resources,
43 pub n_paths: u32,
45 pub n_path_segments: u32,
47 pub n_clips: u32,
49 pub n_open_clips: u32,
51 pub flags: u32,
53}
54
55impl Encoding {
56 pub const FORCE_NEXT_TRANSFORM: u32 = 1;
59
60 pub const FORCE_NEXT_STYLE: u32 = 2;
63
64 pub fn new() -> Self {
66 Self::default()
67 }
68
69 pub fn is_empty(&self) -> bool {
71 self.path_tags.is_empty()
72 }
73
74 #[doc(alias = "clear")]
75 pub fn reset(&mut self) {
79 self.transforms.clear();
80 self.path_tags.clear();
81 self.path_data.clear();
82 self.styles.clear();
83 self.draw_data.clear();
84 self.draw_tags.clear();
85 self.n_paths = 0;
86 self.n_path_segments = 0;
87 self.n_clips = 0;
88 self.n_open_clips = 0;
89 self.flags = 0;
90 self.resources.reset();
91 }
92
93 pub fn append(&mut self, other: &Self, transform: &Option<Transform>) {
95 let glyph_runs_base = {
96 let offsets = self.stream_offsets();
97 let stops_base = self.resources.color_stops.len();
98 let glyph_runs_base = self.resources.glyph_runs.len();
99 let glyphs_base = self.resources.glyphs.len();
100 let coords_base = self.resources.normalized_coords.len();
101 self.resources
102 .glyphs
103 .extend_from_slice(&other.resources.glyphs);
104 self.resources
105 .normalized_coords
106 .extend_from_slice(&other.resources.normalized_coords);
107 self.resources
108 .glyph_runs
109 .extend(other.resources.glyph_runs.iter().cloned().map(|mut run| {
110 run.glyphs.start += glyphs_base;
111 run.glyphs.end += glyphs_base;
112 run.normalized_coords.start += coords_base;
113 run.normalized_coords.end += coords_base;
114 run.stream_offsets.path_tags += offsets.path_tags;
115 run.stream_offsets.path_data += offsets.path_data;
116 run.stream_offsets.draw_tags += offsets.draw_tags;
117 run.stream_offsets.draw_data += offsets.draw_data;
118 run.stream_offsets.transforms += offsets.transforms;
119 run.stream_offsets.styles += offsets.styles;
120 run
121 }));
122 self.resources
123 .patches
124 .extend(other.resources.patches.iter().map(|patch| match patch {
125 Patch::Ramp {
126 draw_data_offset: offset,
127 stops,
128 extend,
129 } => {
130 let stops = stops.start + stops_base..stops.end + stops_base;
131 Patch::Ramp {
132 draw_data_offset: offset + offsets.draw_data,
133 stops,
134 extend: *extend,
135 }
136 }
137 Patch::GlyphRun { index } => Patch::GlyphRun {
138 index: index + glyph_runs_base,
139 },
140 Patch::Image {
141 image,
142 draw_data_offset,
143 } => Patch::Image {
144 image: image.clone(),
145 draw_data_offset: *draw_data_offset + offsets.draw_data,
146 },
147 }));
148 self.resources
149 .color_stops
150 .extend_from_slice(&other.resources.color_stops);
151 self.resources
152 .marks
153 .extend(other.resources.marks.iter().map(|mark| {
154 let kind = match (mark.kind, transform) {
155 (MarkKind::Begin { key, origin }, Some(transform)) => MarkKind::Begin {
156 key,
157 origin: *transform * origin,
158 },
159 (kind, _) => kind,
160 };
161 Mark {
162 draw_tags: mark.draw_tags + offsets.draw_tags,
163 glyph_runs: mark.glyph_runs + glyph_runs_base,
164 kind,
165 }
166 }));
167 glyph_runs_base
168 };
169 self.path_tags.extend_from_slice(&other.path_tags);
170 self.path_data.extend_from_slice(&other.path_data);
171 self.draw_tags.extend_from_slice(&other.draw_tags);
172 self.draw_data.extend_from_slice(&other.draw_data);
173 self.n_paths += other.n_paths;
174 self.n_path_segments += other.n_path_segments;
175 self.n_clips += other.n_clips;
176 self.n_open_clips += other.n_open_clips;
177 let mut flags = other.flags;
183 if other.transforms.is_empty() {
184 flags |= self.flags & Self::FORCE_NEXT_TRANSFORM;
185 }
186 if other.styles.is_empty() {
187 flags |= self.flags & Self::FORCE_NEXT_STYLE;
188 }
189 self.flags = flags;
190 if let Some(transform) = *transform {
191 self.transforms
192 .extend(other.transforms.iter().map(|x| transform * *x));
193 for run in &mut self.resources.glyph_runs[glyph_runs_base..] {
194 run.transform = transform * run.transform;
195 }
196 } else {
197 self.transforms.extend_from_slice(&other.transforms);
198 }
199 self.styles.extend_from_slice(&other.styles);
200 }
201
202 pub fn encode_mark(&mut self, kind: MarkKind) {
204 self.resources.marks.push(Mark {
205 draw_tags: self.draw_tags.len(),
206 glyph_runs: self.resources.glyph_runs.len(),
207 kind,
208 });
209 }
210
211 pub fn stream_offsets(&self) -> StreamOffsets {
213 StreamOffsets {
214 path_tags: self.path_tags.len(),
215 path_data: self.path_data.len(),
216 draw_tags: self.draw_tags.len(),
217 draw_data: self.draw_data.len(),
218 transforms: self.transforms.len(),
219 styles: self.styles.len(),
220 }
221 }
222
223 pub fn encode_fill_style(&mut self, fill: Fill) {
225 self.encode_style(Style::from_fill(fill));
226 }
227
228 #[must_use]
232 pub fn encode_stroke_style(&mut self, stroke: &Stroke) -> bool {
233 let style = Style::from_stroke(stroke);
234 if let Some(style) = style {
235 self.encode_style(style);
236 true
237 } else {
238 false
239 }
240 }
241
242 fn encode_style(&mut self, style: Style) {
243 if self.flags & Self::FORCE_NEXT_STYLE != 0 || self.styles.last() != Some(&style) {
244 self.path_tags.push(PathTag::STYLE);
245 self.styles.push(style);
246 self.flags &= !Self::FORCE_NEXT_STYLE;
247 }
248 }
249
250 pub fn encode_transform(&mut self, transform: Transform) -> bool {
255 if self.flags & Self::FORCE_NEXT_TRANSFORM != 0
256 || self.transforms.last() != Some(&transform)
257 {
258 self.path_tags.push(PathTag::TRANSFORM);
259 self.transforms.push(transform);
260 self.flags &= !Self::FORCE_NEXT_TRANSFORM;
261 true
262 } else {
263 false
264 }
265 }
266
267 pub fn encode_path(&mut self, is_fill: bool) -> PathEncoder<'_> {
270 PathEncoder::new(
271 &mut self.path_tags,
272 &mut self.path_data,
273 &mut self.n_path_segments,
274 &mut self.n_paths,
275 is_fill,
276 )
277 }
278
279 pub fn encode_shape(&mut self, shape: &impl Shape, is_fill: bool) -> bool {
282 let mut encoder = self.encode_path(is_fill);
283 encoder.shape(shape);
284 encoder.finish(true) != 0
285 }
286
287 pub fn encode_empty_shape(&mut self) {
293 let mut encoder = self.encode_path(true);
294 encoder.empty_path();
295 encoder.finish(true);
296 }
297
298 pub fn encode_path_elements(
301 &mut self,
302 path: impl Iterator<Item = peniko::kurbo::PathEl>,
303 is_fill: bool,
304 ) -> bool {
305 let mut encoder = self.encode_path(is_fill);
306 encoder.path_elements(path);
307 encoder.finish(true) != 0
308 }
309
310 #[allow(
312 single_use_lifetimes,
313 reason = "False positive through Rust 1.96; fixed by rust-lang/rust#129255"
314 )]
315 pub fn encode_brush<'b>(&mut self, brush: impl Into<BrushRef<'b>>, alpha: f32) {
316 use super::math::point_to_f32;
317 match brush.into() {
318 BrushRef::Solid(color) => {
319 let color = if alpha != 1.0 {
320 color.multiply_alpha(alpha)
321 } else {
322 color
323 };
324 self.encode_color(color);
325 }
326 BrushRef::Gradient(gradient) => match gradient.kind {
327 GradientKind::Linear(LinearGradientPosition { start, end }) => {
328 self.encode_linear_gradient(
329 DrawLinearGradient {
330 index: 0,
331 p0: point_to_f32(start),
332 p1: point_to_f32(end),
333 },
334 gradient.stops.iter().copied(),
335 alpha,
336 gradient.extend,
337 );
338 }
339 GradientKind::Radial(RadialGradientPosition {
340 start_center,
341 start_radius,
342 end_center,
343 end_radius,
344 }) => {
345 self.encode_radial_gradient(
346 DrawRadialGradient {
347 index: 0,
348 p0: point_to_f32(start_center),
349 p1: point_to_f32(end_center),
350 r0: start_radius,
351 r1: end_radius,
352 },
353 gradient.stops.iter().copied(),
354 alpha,
355 gradient.extend,
356 );
357 }
358 GradientKind::Sweep(SweepGradientPosition {
359 center,
360 start_angle,
361 end_angle,
362 }) => {
363 use core::f32::consts::TAU;
364 self.encode_sweep_gradient(
365 DrawSweepGradient {
366 index: 0,
367 p0: point_to_f32(center),
368 t0: start_angle / TAU,
369 t1: end_angle / TAU,
370 },
371 gradient.stops.iter().copied(),
372 alpha,
373 gradient.extend,
374 );
375 }
376 },
377 BrushRef::Image(image) => {
378 self.encode_image(image, alpha);
379 }
380 }
381 }
382
383 pub fn encode_color(&mut self, color: impl Into<DrawColor>) {
385 let color = color.into();
386 self.draw_tags.push(DrawTag::COLOR);
387 let DrawColor { rgba } = color;
388 self.draw_data.push(rgba);
389 }
390
391 pub fn encode_linear_gradient(
393 &mut self,
394 gradient: DrawLinearGradient,
395 color_stops: impl Iterator<Item = ColorStop>,
396 alpha: f32,
397 extend: Extend,
398 ) {
399 match self.add_ramp(color_stops, alpha, extend) {
400 RampStops::Empty => self.encode_color(palette::css::TRANSPARENT),
401 RampStops::One(color) => {
402 self.encode_color(color);
403 }
404 RampStops::Many => {
405 self.draw_tags.push(DrawTag::LINEAR_GRADIENT);
406 self.draw_data
407 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(&gradient)));
408 }
409 }
410 }
411
412 pub fn encode_radial_gradient(
414 &mut self,
415 gradient: DrawRadialGradient,
416 color_stops: impl Iterator<Item = ColorStop>,
417 alpha: f32,
418 extend: Extend,
419 ) {
420 const SKIA_EPSILON: f32 = 1.0 / (1 << 12) as f32;
422 if gradient.p0 == gradient.p1 && (gradient.r0 - gradient.r1).abs() < SKIA_EPSILON {
423 self.encode_color(palette::css::TRANSPARENT);
424 return;
425 }
426 match self.add_ramp(color_stops, alpha, extend) {
427 RampStops::Empty => self.encode_color(palette::css::TRANSPARENT),
428 RampStops::One(color) => self.encode_color(color),
429 RampStops::Many => {
430 self.draw_tags.push(DrawTag::RADIAL_GRADIENT);
431 self.draw_data
432 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(&gradient)));
433 }
434 }
435 }
436
437 pub fn encode_sweep_gradient(
439 &mut self,
440 gradient: DrawSweepGradient,
441 color_stops: impl Iterator<Item = ColorStop>,
442 alpha: f32,
443 extend: Extend,
444 ) {
445 const SKIA_DEGENERATE_THRESHOLD: f32 = 1.0 / (1 << 15) as f32;
446 if (gradient.t0 - gradient.t1).abs() < SKIA_DEGENERATE_THRESHOLD {
447 self.encode_color(palette::css::TRANSPARENT);
448 return;
449 }
450 match self.add_ramp(color_stops, alpha, extend) {
451 RampStops::Empty => self.encode_color(palette::css::TRANSPARENT),
452 RampStops::One(color) => self.encode_color(color),
453 RampStops::Many => {
454 self.draw_tags.push(DrawTag::SWEEP_GRADIENT);
455 self.draw_data
456 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(&gradient)));
457 }
458 }
459 }
460
461 pub fn encode_image<'b>(&mut self, brush: impl Into<ImageBrushRef<'b>>, alpha: f32) {
463 let brush: ImageBrushRef<'b> = brush.into();
464 let ImageSampler {
465 x_extend,
466 y_extend,
467 quality,
468 alpha: global_alpha,
469 } = brush.sampler;
470 let alpha = (global_alpha * alpha * 255.0).round() as u8;
471 self.resources.patches.push(Patch::Image {
475 image: brush.image.clone(),
476 draw_data_offset: self.draw_data.len(),
477 });
478 self.draw_tags.push(DrawTag::IMAGE);
479 self.draw_data
480 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(&DrawImage {
481 xy: 0,
482 width_height: (brush.image.width << 16) | (brush.image.height & 0xFFFF),
483 sample_alpha: ((brush.image.format as u32) << 15
484 | (brush.image.alpha_type as u32) << 14
485 | (quality as u32) << 12
486 | ((x_extend as u32) << 10)
487 | ((y_extend as u32) << 8)
488 | alpha as u32),
489 })));
490 }
491
492 pub fn encode_blurred_rounded_rect(
494 &mut self,
495 color: impl Into<DrawColor>,
496 width: f32,
497 height: f32,
498 radius: f32,
499 std_dev: f32,
500 ) {
501 self.draw_tags.push(DrawTag::BLUR_RECT);
502 self.draw_data
503 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(
504 &DrawBlurRoundedRect {
505 color: color.into(),
506 width,
507 height,
508 radius,
509 std_dev,
510 },
511 )));
512 }
513
514 pub fn encode_begin_clip(&mut self, parameters: DrawBeginClip) {
516 self.draw_tags.push(DrawTag::BEGIN_CLIP);
517 self.draw_data
518 .extend_from_slice(bytemuck::cast_slice(bytemuck::bytes_of(¶meters)));
519 self.n_clips += 1;
520 self.n_open_clips += 1;
521 }
522
523 pub fn encode_end_clip(&mut self) {
525 if self.n_open_clips > 0 {
526 self.draw_tags.push(DrawTag::END_CLIP);
527 self.path_tags.push(PathTag::PATH);
529 self.n_paths += 1;
530 self.n_clips += 1;
531 self.n_open_clips -= 1;
532 }
533 }
534
535 pub fn force_next_transform_and_style(&mut self) {
538 self.flags |= Self::FORCE_NEXT_TRANSFORM | Self::FORCE_NEXT_STYLE;
539 }
540
541 pub fn swap_last_path_tags(&mut self) {
544 let len = self.path_tags.len();
545 self.path_tags.swap(len - 1, len - 2);
546 }
547
548 fn add_ramp(
549 &mut self,
550 color_stops: impl Iterator<Item = ColorStop>,
551 alpha: f32,
552 extend: Extend,
553 ) -> RampStops {
554 let offset = self.draw_data.len();
555 let stops_start = self.resources.color_stops.len();
556 if alpha != 1.0 {
557 self.resources
558 .color_stops
559 .extend(color_stops.map(|stop| stop.multiply_alpha(alpha)));
560 } else {
561 self.resources.color_stops.extend(color_stops);
562 }
563 let stops_end = self.resources.color_stops.len();
564 match stops_end - stops_start {
565 0 => RampStops::Empty,
566 1 => RampStops::One(self.resources.color_stops.pop().unwrap().color),
567 _ => {
568 self.resources.patches.push(Patch::Ramp {
569 draw_data_offset: offset,
570 stops: stops_start..stops_end,
571 extend,
572 });
573 RampStops::Many
574 }
575 }
576 }
577}
578
579enum RampStops {
581 Empty,
583 One(DynamicColor),
585 Many,
587}
588
589#[derive(Clone, Default)]
591pub struct Resources {
592 pub patches: Vec<Patch>,
594 pub color_stops: Vec<ColorStop>,
596 pub glyphs: Vec<Glyph>,
598 pub glyph_runs: Vec<GlyphRun>,
600 pub normalized_coords: Vec<NormalizedCoord>,
602 pub marks: Vec<Mark>,
605}
606
607#[derive(Clone, Debug)]
612pub struct Mark {
613 pub draw_tags: usize,
615 pub glyph_runs: usize,
618 pub kind: MarkKind,
620}
621
622#[derive(Clone, Copy, Debug)]
624pub enum MarkKind {
625 Begin {
628 key: u64,
630 origin: Transform,
632 },
633 End,
635}
636
637impl Resources {
638 #[doc(alias = "clear")]
639 fn reset(&mut self) {
642 self.patches.clear();
643 self.color_stops.clear();
644 self.glyphs.clear();
645 self.glyph_runs.clear();
646 self.normalized_coords.clear();
647 self.marks.clear();
648 }
649}
650
651#[derive(Copy, Clone, Default, Debug)]
653pub struct StreamOffsets {
654 pub path_tags: usize,
656 pub path_data: usize,
658 pub draw_tags: usize,
660 pub draw_data: usize,
662 pub transforms: usize,
664 pub styles: usize,
666}
667
668impl StreamOffsets {
669 pub(crate) fn add(&mut self, other: &Self) {
670 self.path_tags += other.path_tags;
671 self.path_data += other.path_data;
672 self.draw_tags += other.draw_tags;
673 self.draw_data += other.draw_data;
674 self.transforms += other.transforms;
675 self.styles += other.styles;
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use peniko::{Extend, ImageQuality};
682
683 use super::{Encoding, Transform};
684
685 #[test]
686 fn appending_an_encoding_without_transforms_keeps_a_forced_transform() {
687 let mut encoding = Encoding::new();
688 assert!(encoding.encode_transform(Transform::IDENTITY));
689 encoding.force_next_transform_and_style();
690 encoding.append(&Encoding::new(), &None);
691 assert!(
692 encoding.encode_transform(Transform::IDENTITY),
693 "the forced transform must still be encoded after an empty append"
694 );
695 }
696
697 #[test]
698 fn ensure_image_quality_values() {
699 assert_eq!(ImageQuality::Low as u32, 0);
700 assert_eq!(ImageQuality::Medium as u32, 1);
701 assert_eq!(ImageQuality::High as u32, 2);
702 match ImageQuality::Low {
704 ImageQuality::Low | ImageQuality::Medium | ImageQuality::High => {}
705 }
706 }
707
708 #[test]
709 fn ensure_extend_values() {
710 assert_eq!(Extend::Pad as u32, 0);
711 assert_eq!(Extend::Repeat as u32, 1);
712 assert_eq!(Extend::Reflect as u32, 2);
713 match Extend::Pad {
715 Extend::Pad | Extend::Repeat | Extend::Reflect => {}
716 }
717 }
718}