/
paint_context.rs
2015 lines (1839 loc) · 94.5 KB
/
paint_context.rs
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Painting of display lists using Moz2D/Azure.
use azure::azure::AzIntSize;
use azure::azure_hl::{AntialiasMode, Color, ColorPattern, CompositionOp};
use azure::azure_hl::{DrawOptions, DrawSurfaceOptions, DrawTarget, ExtendMode, FilterType};
use azure::azure_hl::{GaussianBlurAttribute, StrokeOptions, SurfaceFormat};
use azure::azure_hl::{GaussianBlurInput, GradientStop, Filter, FilterNode, LinearGradientPattern};
use azure::azure_hl::{JoinStyle, CapStyle};
use azure::azure_hl::{Pattern, PatternRef, Path, PathBuilder, SurfacePattern};
use azure::scaled_font::ScaledFont;
use azure::{AzFloat, struct__AzDrawOptions, struct__AzGlyph};
use azure::{struct__AzGlyphBuffer, struct__AzPoint, AzDrawTargetFillGlyphs};
use display_list::TextOrientation::{SidewaysLeft, SidewaysRight, Upright};
use display_list::{BLUR_INFLATION_FACTOR, BorderRadii, BoxShadowClipMode, ClippingRegion};
use display_list::{TextDisplayItem};
use euclid::matrix2d::Matrix2D;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::side_offsets::SideOffsets2D;
use euclid::size::Size2D;
use filters;
use font_context::FontContext;
use gfx_traits::color;
use libc::types::common::c99::uint32_t;
use msg::compositor_msg::LayerKind;
use net_traits::image::base::{Image, PixelFormat};
use std::default::Default;
use std::f32;
use std::mem;
use std::ptr;
use std::sync::Arc;
use style::computed_values::{border_style, filter, image_rendering, mix_blend_mode};
use text::TextRun;
use text::glyph::CharIndex;
use util::geometry::{self, Au, MAX_RECT, ZERO_RECT};
use util::opts;
use util::range::Range;
pub struct PaintContext<'a> {
pub draw_target: DrawTarget,
pub font_context: &'a mut Box<FontContext>,
/// The rectangle that this context encompasses in page coordinates.
pub page_rect: Rect<f32>,
/// The rectangle that this context encompasses in screen coordinates (pixels).
pub screen_rect: Rect<usize>,
/// The clipping rect for the stacking context as a whole.
pub clip_rect: Option<Rect<Au>>,
/// The current transient clipping region, if any. A "transient clipping region" is the
/// clipping region used by the last display item. We cache the last value so that we avoid
/// pushing and popping clipping regions unnecessarily.
pub transient_clip: Option<ClippingRegion>,
/// A temporary hack to disable clipping optimizations on 3d layers.
pub layer_kind: LayerKind,
}
#[derive(Copy, Clone)]
enum Direction {
Top,
Left,
Right,
Bottom
}
#[derive(Copy, Clone)]
enum BorderCorner {
TL, // top left
TR, // top right
BR, // bottom right
BL, // bottom left
}
#[derive(Copy, Clone)]
enum DashSize {
DottedBorder = 1,
DashedBorder = 3
}
#[derive(Copy, Clone, Debug)]
struct Ellipse {
origin: Point2D<f32>,
width: f32,
height: f32,
}
/// When `Line::new` creates a new `Line` it ensures `start.x <= end.x` for that line.
#[derive(Copy, Clone, Debug)]
struct Line {
start: Point2D<f32>,
end: Point2D<f32>,
}
impl Line {
/// Guarantees that `start.x <= end.x` for the returned `Line`.
fn new(start: Point2D<f32>, end: Point2D<f32>) -> Line {
let line = if start.x <= end.x {
Line { start: start, end: end }
} else {
Line { start: end, end: start }
};
debug_assert!(line.length_squared() > f32::EPSILON);
line
}
fn length_squared(&self) -> f32 {
let width = (self.end.x - self.start.x).abs();
let height = (self.end.y - self.start.y).abs();
width * width + height * height
}
}
struct CornerOrigin {
top_left: Point2D<f32>,
top_right: Point2D<f32>,
bottom_right: Point2D<f32>,
bottom_left: Point2D<f32>,
}
impl<'a> PaintContext<'a> {
pub fn screen_pixels_per_px(&self) -> f32 {
self.screen_rect.size.width as f32 / self.page_rect.size.width
}
pub fn draw_target(&self) -> &DrawTarget {
&self.draw_target
}
pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
self.draw_target.make_current();
self.draw_target.fill_rect(&bounds.to_nearest_azure_rect(self.screen_pixels_per_px()),
PatternRef::Color(&ColorPattern::new(color)),
None);
}
pub fn draw_border(&self,
bounds: &Rect<Au>,
border: &SideOffsets2D<Au>,
radius: &BorderRadii<Au>,
color: &SideOffsets2D<Color>,
style: &SideOffsets2D<border_style::T>) {
let scale = self.screen_pixels_per_px();
let border = border.to_float_pixels(scale);
let radius = radius.to_radii_pixels(scale);
self.draw_border_segment(Direction::Top, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Right, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Bottom, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Left, bounds, &border, &radius, color, style);
}
pub fn draw_line(&self, bounds: &Rect<Au>, color: Color, style: border_style::T) {
self.draw_target.make_current();
self.draw_line_segment(bounds, &Default::default(), color, style);
}
pub fn draw_push_clip(&self, bounds: &Rect<Au>) {
let rect = bounds.to_nearest_azure_rect(self.screen_pixels_per_px());
let path_builder = self.draw_target.create_path_builder();
let left_top = Point2D::new(rect.origin.x, rect.origin.y);
let right_top = Point2D::new(rect.origin.x + rect.size.width, rect.origin.y);
let left_bottom = Point2D::new(rect.origin.x, rect.origin.y + rect.size.height);
let right_bottom = Point2D::new(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height);
path_builder.move_to(left_top);
path_builder.line_to(right_top);
path_builder.line_to(right_bottom);
path_builder.line_to(left_bottom);
let path = path_builder.finish();
self.draw_target.push_clip(&path);
}
pub fn draw_pop_clip(&self) {
self.draw_target.pop_clip();
}
pub fn draw_image(&self,
bounds: &Rect<Au>,
stretch_size: &Size2D<Au>,
image: Arc<Image>,
image_rendering: image_rendering::T) {
let size = Size2D::new(image.width as i32, image.height as i32);
let (pixel_width, source_format) = match image.format {
PixelFormat::RGBA8 => (4, SurfaceFormat::B8G8R8A8),
PixelFormat::K8 => (1, SurfaceFormat::A8),
PixelFormat::RGB8 => panic!("RGB8 color type not supported"),
PixelFormat::KA8 => panic!("KA8 color type not supported"),
};
let stride = image.width * pixel_width;
let scale = self.screen_pixels_per_px();
self.draw_target.make_current();
let draw_target_ref = &self.draw_target;
let azure_surface = draw_target_ref.create_source_surface_from_data(&image.bytes,
size,
stride as i32,
source_format);
let source_rect = Rect::new(Point2D::new(0.0, 0.0),
Size2D::new(image.width as AzFloat, image.height as AzFloat));
let dest_rect = bounds.to_nearest_azure_rect(scale);
// TODO(pcwalton): According to CSS-IMAGES-3 § 5.3, nearest-neighbor interpolation is a
// conforming implementation of `crisp-edges`, but it is not the best we could do.
// Something like Scale2x would be ideal.
let draw_surface_filter = match image_rendering {
image_rendering::T::Auto => Filter::Linear,
image_rendering::T::CrispEdges | image_rendering::T::Pixelated => Filter::Point,
};
let draw_surface_options = DrawSurfaceOptions::new(draw_surface_filter, true);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
// Fast path: No need to create a pattern.
if bounds.size == *stretch_size {
draw_target_ref.draw_surface(azure_surface,
dest_rect,
source_rect,
draw_surface_options,
draw_options);
return
}
// Slightly slower path: No need to stretch.
//
// Annoyingly, surface patterns in Azure/Skia are relative to the top left of the *canvas*,
// not the rectangle we're drawing to. So we need to translate it explicitly.
let matrix = Matrix2D::identity().translate(dest_rect.origin.x, dest_rect.origin.y);
let stretch_size = stretch_size.to_nearest_azure_size(scale);
if source_rect.size == stretch_size {
let pattern = SurfacePattern::new(azure_surface.azure_source_surface,
true,
true,
&matrix);
draw_target_ref.fill_rect(&dest_rect,
PatternRef::Surface(&pattern),
Some(&draw_options));
return
}
// Slow path: Both stretch and a pattern are needed.
let draw_surface_options = DrawSurfaceOptions::new(draw_surface_filter, true);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
let temporary_draw_target =
self.draw_target.create_similar_draw_target(&stretch_size.to_azure_int_size(),
self.draw_target.get_format());
let temporary_dest_rect = Rect::new(Point2D::new(0.0, 0.0), stretch_size);
temporary_draw_target.draw_surface(azure_surface,
temporary_dest_rect,
source_rect,
draw_surface_options,
draw_options);
let temporary_surface = temporary_draw_target.snapshot();
let pattern = SurfacePattern::new(temporary_surface.azure_source_surface,
true,
true,
&matrix);
draw_target_ref.fill_rect(&dest_rect, PatternRef::Surface(&pattern), None);
}
pub fn clear(&self) {
let pattern = ColorPattern::new(color::transparent());
let rect = Rect::new(Point2D::new(self.page_rect.origin.x as AzFloat,
self.page_rect.origin.y as AzFloat),
Size2D::new(self.screen_rect.size.width as AzFloat,
self.screen_rect.size.height as AzFloat));
let mut draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
draw_options.set_composition_op(CompositionOp::Source);
self.draw_target.make_current();
self.draw_target.fill_rect(&rect, PatternRef::Color(&pattern), Some(&draw_options));
}
fn draw_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: &SideOffsets2D<Color>,
style: &SideOffsets2D<border_style::T>) {
let (style_select, color_select) = match direction {
Direction::Top => (style.top, color.top),
Direction::Left => (style.left, color.left),
Direction::Right => (style.right, color.right),
Direction::Bottom => (style.bottom, color.bottom)
};
match style_select {
border_style::T::none | border_style::T::hidden => {}
border_style::T::dotted => {
// FIXME(sammykim): This doesn't work well with dash_pattern and cap_style.
self.draw_dashed_border_segment(direction,
bounds,
border,
radius,
color_select,
DashSize::DottedBorder);
}
border_style::T::dashed => {
self.draw_dashed_border_segment(direction,
bounds,
border,
radius,
color_select,
DashSize::DashedBorder);
}
border_style::T::solid => {
self.draw_solid_border_segment(direction, bounds, border, radius, color_select);
}
border_style::T::double => {
self.draw_double_border_segment(direction, bounds, border, radius, color_select);
}
border_style::T::groove | border_style::T::ridge => {
self.draw_groove_ridge_border_segment(direction,
bounds,
border,
radius,
color_select,
style_select);
}
border_style::T::inset | border_style::T::outset => {
self.draw_inset_outset_border_segment(direction,
bounds,
border,
radius,
color_select,
style_select);
}
}
}
fn draw_line_segment(&self,
bounds: &Rect<Au>,
radius: &BorderRadii<AzFloat>,
color: Color,
style: border_style::T) {
let scale = self.screen_pixels_per_px();
let border = SideOffsets2D::new_all_same(bounds.size.width).to_float_pixels(scale);
match style {
border_style::T::none | border_style::T::hidden => {}
border_style::T::dotted => {
self.draw_dashed_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
DashSize::DottedBorder);
}
border_style::T::dashed => {
self.draw_dashed_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
DashSize::DashedBorder);
}
border_style::T::solid => {
self.draw_solid_border_segment(Direction::Right, bounds, &border, radius, color)
}
border_style::T::double => {
self.draw_double_border_segment(Direction::Right, bounds, &border, radius, color)
}
border_style::T::groove | border_style::T::ridge => {
self.draw_groove_ridge_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
style);
}
border_style::T::inset | border_style::T::outset => {
self.draw_inset_outset_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
style);
}
}
}
fn draw_border_path(&self,
bounds: &Rect<f32>,
direction: Direction,
border: &SideOffsets2D<f32>,
radii: &BorderRadii<AzFloat>,
color: Color) {
let mut path_builder = self.draw_target.create_path_builder();
self.create_border_path_segment(&mut path_builder,
bounds,
direction,
border,
radii,
BorderPathDrawingMode::EntireBorder);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
self.draw_target.fill(&path_builder.finish(),
Pattern::Color(ColorPattern::new(color)).to_pattern_ref(),
&draw_options);
}
fn push_rounded_rect_clip(&self, bounds: &Rect<f32>, radii: &BorderRadii<AzFloat>) {
let mut path_builder = self.draw_target.create_path_builder();
self.create_rounded_rect_path(&mut path_builder, bounds, radii);
self.draw_target.push_clip(&path_builder.finish());
}
fn solve_quadratic(a: f32, b: f32, c: f32) -> (Option<f32>, Option<f32>) {
let discriminant = b * b - 4. * a * c;
if discriminant < 0. {
return (None, None);
}
let x1 = (-b + discriminant.sqrt())/(2. * a);
let x2 = (-b - discriminant.sqrt())/(2. * a);
if discriminant == 0. {
return (Some(x1), None);
}
(Some(x1), Some(x2))
}
fn intersect_ellipse_line(mut e: Ellipse, mut line: Line) -> (Option<Point2D<f32>>,
Option<Point2D<f32>>) {
let mut rotated_axes = false;
fn rotate_axes(point: Point2D<f32>, clockwise: bool) -> Point2D<f32> {
if clockwise {
// rotate clockwise by 90 degrees
Point2D::new(point.y, -point.x)
} else {
// rotate counter clockwise by 90 degrees
Point2D::new(-point.y, point.x)
}
}
// if line height is greater than its width then rotate the axes by 90 degrees,
// i.e. (x, y) -> (y, -x).
if (line.end.x - line.start.x).abs() < (line.end.y - line.start.y).abs() {
rotated_axes = true;
line = Line::new(rotate_axes(line.start, true), rotate_axes(line.end, true));
e = Ellipse { origin: rotate_axes(e.origin, true),
width: e.height, height: e.width };
}
debug_assert!(line.end.x - line.start.x > f32::EPSILON,
"Error line segment end.x ({}) <= start.x ({})!", line.end.x, line.start.x);
// shift the origin to center of the ellipse.
line = Line::new(line.start - e.origin, line.end - e.origin);
let a = (line.end.y - line.start.y)/(line.end.x - line.start.x);
let b = line.start.y - (a * line.start.x);
// given the equation of a line,
// y = a * x + b,
// and the equation of an ellipse,
// x^2/w^2 + y^2/h^2 = 1,
// substitute y = a * x + b, giving
// x^2/w^2 + (a^2x^2 + 2abx + b^2)/h^2 = 1
// then simplify to
// (h^2 + w^2a^2)x^2 + 2abw^2x + (b^2w^2 - w^2h^2) = 0
// finally solve for w using the quadratic equation.
let w = e.width;
let h = e.height;
let quad_a = h * h + w * w * a * a;
let quad_b = 2. * a * b * w * w;
let quad_c = b * b * w * w - w * w * h * h;
let intersections = PaintContext::solve_quadratic(quad_a, quad_b, quad_c);
match intersections {
(Some(x0), Some(x1)) => {
let mut p0 = Point2D::new(x0, a * x0 + b) + e.origin;
let mut p1 = Point2D::new(x1, a * x1 + b) + e.origin;
if x0 > x1 {
mem::swap(&mut p0, &mut p1);
}
if rotated_axes {
p0 = rotate_axes(p0, false);
p1 = rotate_axes(p1, false);
}
(Some(p0), Some(p1))
},
(Some(x0), None) => {
let mut p = Point2D::new(x0, a * x0 + b) + e.origin;
if rotated_axes {
p = rotate_axes(p, false);
}
(Some(p), None)
},
(None, Some(x1)) => {
let mut p = Point2D::new(x1, a * x1 + b) + e.origin;
if rotated_axes {
p = rotate_axes(p, false);
}
(Some(p), None)
},
(None, None) => (None, None),
}
}
// Given an ellipse and line segment, the line segment may intersect the
// ellipse at 0, 1, or 2 points. We compute those intersection points.
// For each intersection point the angle of the point on the ellipse relative to
// the top|bottom of the ellipse is computed.
// Examples:
// - intersection at ellipse.center + (0, ellipse.height), the angle is 0 rad.
// - intersection at ellipse.center + (0, -ellipse.height), the angle is 0 rad.
// - intersection at ellipse.center + (+-ellipse.width, 0), the angle is pi/2.
fn ellipse_line_intersection_angles(e: Ellipse, l: Line)
-> (Option<(Point2D<f32>, f32)>, Option<(Point2D<f32>, f32)>) {
fn point_angle(e: Ellipse, intersect_point: Point2D<f32>) -> f32 {
((intersect_point.y - e.origin.y).abs() / e.height).asin()
}
let intersection = PaintContext::intersect_ellipse_line(e, l);
match intersection {
(Some(p0), Some(p1)) => (Some((p0, point_angle(e, p0))), Some((p1, point_angle(e, p1)))),
(Some(p0), None) => (Some((p0, point_angle(e, p0))), None),
(None, Some(p1)) => (None, Some((p1, point_angle(e, p1)))),
(None, None) => (None, None),
}
}
fn ellipse_rightmost_intersection(e: Ellipse, l: Line) -> Option<f32> {
match PaintContext::ellipse_line_intersection_angles(e, l) {
(Some((p0, angle0)), Some((p1, _))) if p0.x > p1.x => Some(angle0),
(_, Some((_, angle1))) => Some(angle1),
(Some((_, angle0)), None) => Some(angle0),
(None, None) => None,
}
}
fn ellipse_leftmost_intersection(e: Ellipse, l: Line) -> Option<f32> {
match PaintContext::ellipse_line_intersection_angles(e, l) {
(Some((p0, angle0)), Some((p1, _))) if p0.x < p1.x => Some(angle0),
(_, Some((_, angle1))) => Some(angle1),
(Some((_, angle0)), None) => Some(angle0),
(None, None) => None,
}
}
fn is_zero_radius(radius: &Size2D<AzFloat>) -> bool {
radius.width <= 0. || radius.height <= 0.
}
// The following comment is wonderful, and stolen from
// gecko:gfx/thebes/gfxContext.cpp:RoundedRectangle for reference.
// ---------------------------------------------------------------
//
// For CW drawing, this looks like:
//
// ...******0** 1 C
// ****
// *** 2
// **
// *
// *
// 3
// *
// *
//
// Where 0, 1, 2, 3 are the control points of the Bezier curve for
// the corner, and C is the actual corner point.
//
// At the start of the loop, the current point is assumed to be
// the point adjacent to the top left corner on the top
// horizontal. Note that corner indices start at the top left and
// continue clockwise, whereas in our loop i = 0 refers to the top
// right corner.
//
// When going CCW, the control points are swapped, and the first
// corner that's drawn is the top left (along with the top segment).
//
// There is considerable latitude in how one chooses the four
// control points for a Bezier curve approximation to an ellipse.
// For the overall path to be continuous and show no corner at the
// endpoints of the arc, points 0 and 3 must be at the ends of the
// straight segments of the rectangle; points 0, 1, and C must be
// collinear; and points 3, 2, and C must also be collinear. This
// leaves only two free parameters: the ratio of the line segments
// 01 and 0C, and the ratio of the line segments 32 and 3C. See
// the following papers for extensive discussion of how to choose
// these ratios:
//
// Dokken, Tor, et al. "Good approximation of circles by
// curvature-continuous Bezier curves." Computer-Aided
// Geometric Design 7(1990) 33--41.
// Goldapp, Michael. "Approximation of circular arcs by cubic
// polynomials." Computer-Aided Geometric Design 8(1991) 227--238.
// Maisonobe, Luc. "Drawing an elliptical arc using polylines,
// quadratic, or cubic Bezier curves."
// http://www.spaceroots.org/documents/ellipse/elliptical-arc.pdf
//
// We follow the approach in section 2 of Goldapp (least-error,
// Hermite-type approximation) and make both ratios equal to
//
// 2 2 + n - sqrt(2n + 28)
// alpha = - * ---------------------
// 3 n - 4
//
// where n = 3( cbrt(sqrt(2)+1) - cbrt(sqrt(2)-1) ).
//
// This is the result of Goldapp's equation (10b) when the angle
// swept out by the arc is pi/2, and the parameter "a-bar" is the
// expression given immediately below equation (21).
//
// Using this value, the maximum radial error for a circle, as a
// fraction of the radius, is on the order of 0.2 x 10^-3.
// Neither Dokken nor Goldapp discusses error for a general
// ellipse; Maisonobe does, but his choice of control points
// follows different constraints, and Goldapp's expression for
// 'alpha' gives much smaller radial error, even for very flat
// ellipses, than Maisonobe's equivalent.
//
// For the various corners and for each axis, the sign of this
// constant changes, or it might be 0 -- it's multiplied by the
// appropriate multiplier from the list before using.
// ---------------------------------------------------------------
//
// Code adapted from gecko:gfx/2d/PathHelpers.h:EllipseToBezier
fn ellipse_to_bezier(path_builder: &mut PathBuilder,
origin: Point2D<AzFloat>,
radius: Size2D<AzFloat>,
start_angle: f32,
end_angle: f32) {
if PaintContext::is_zero_radius(&radius) {
return;
}
// Calculate kappa constant for partial curve. The sign of angle in the
// tangent will actually ensure this is negative for a counter clockwise
// sweep, so changing signs later isn't needed.
let kappa_factor: f32 = (4.0f32 / 3.0f32) * ((end_angle - start_angle) / 4.).tan();
let kappa_x: f32 = kappa_factor * radius.width;
let kappa_y: f32 = kappa_factor * radius.height;
// We guarantee here the current point is the start point of the next
// curve segment.
let start_point = Point2D::new(origin.x + start_angle.cos() * radius.width,
origin.y + start_angle.sin() * radius.height);
path_builder.line_to(start_point);
let end_point = Point2D::new(origin.x + end_angle.cos() * radius.width,
origin.y + end_angle.sin() * radius.height);
let tangent_start = Point2D::new(-start_angle.sin(), start_angle.cos());
let cp1 = Point2D::new(start_point.x + tangent_start.x * kappa_x,
start_point.y + tangent_start.y * kappa_y);
let rev_tangent_end = Point2D::new(end_angle.sin(), -end_angle.cos());
let cp2 = Point2D::new(end_point.x + rev_tangent_end.x * kappa_x,
end_point.y + rev_tangent_end.y * kappa_y);
path_builder.bezier_curve_to(&cp1, &cp2, &end_point);
}
#[allow(non_snake_case)]
fn inner_border_bounds(bounds: &Rect<f32>, border: &SideOffsets2D<f32>) -> Rect<f32> {
// T = top, B = bottom, L = left, R = right
let inner_TL = bounds.origin + Point2D::new(border.left, border.top);
let inner_BR = bounds.bottom_right() + Point2D::new(-border.right, -border.bottom);
Rect::new(inner_TL, Size2D::new(inner_BR.x - inner_TL.x, inner_BR.y - inner_TL.y))
}
#[allow(non_snake_case)]
fn corner_bounds(bounds: &Rect<f32>,
border: &SideOffsets2D<f32>,
radii: &BorderRadii<AzFloat>) -> (CornerOrigin, SideOffsets2D<Size2D<f32>>) {
fn distance_to_elbow(radius: &Size2D<AzFloat>,
corner_width: f32,
corner_height: f32) -> Size2D<f32> {
if corner_width >= radius.width || corner_height >= radius.height {
Size2D::zero()
} else {
Size2D::new(radius.width - corner_width, radius.height - corner_height)
}
}
// T = top, B = bottom, L = left, R = right
let origin_TL = bounds.origin + Point2D::new(radii.top_left.width, radii.top_left.height);
let origin_TR = bounds.top_right() + Point2D::new(-radii.top_right.width,
radii.top_right.height);
let origin_BR = bounds.bottom_right() + Point2D::new(-radii.bottom_right.width,
-radii.bottom_right.height);
let origin_BL = bounds.bottom_left() + Point2D::new(radii.bottom_left.width,
-radii.bottom_left.height);
let elbow_TL = distance_to_elbow(&radii.top_left, border.left, border.top);
let elbow_TR = distance_to_elbow(&radii.top_right, border.right, border.top);
let elbow_BR = distance_to_elbow(&radii.bottom_right, border.right, border.bottom);
let elbow_BL = distance_to_elbow(&radii.bottom_left, border.left, border.bottom);
(CornerOrigin { top_left: origin_TL,
top_right: origin_TR,
bottom_right: origin_BR,
bottom_left: origin_BL },
SideOffsets2D::new(elbow_TL, elbow_TR, elbow_BR, elbow_BL))
}
/// `origin` is the origin point when drawing the corner e.g. it's the circle center
/// when drawing radial borders.
///
/// `corner` indicates which corner to draw e.g. top left or top right etc.
///
/// `radius` is the border-radius width and height. If `radius.width == radius.height` then
/// an arc from a circle is drawn instead of an arc from an ellipse.
///
/// `inner_border` & `outer_border` are the inner and outer points on the border corner
/// respectively. ASCII diagram:
/// ---------------* =====> ("*" is the `outer_border` point)
/// |
/// |
/// |
/// --------* ============> ("*" is the `inner_border` point)
/// | |
/// | |
///
///
/// `dist_elbow` is the distance from `origin` to the inner part of the border corner.
/// `clockwise` indicates direction to draw the border curve.
#[allow(non_snake_case)]
fn draw_corner(path_builder: &mut PathBuilder,
corner: BorderCorner,
origin: &Point2D<AzFloat>,
radius: &Size2D<AzFloat>,
inner_border: &Point2D<AzFloat>,
outer_border: &Point2D<AzFloat>,
dist_elbow: &Size2D<AzFloat>,
clockwise: bool) {
let rad_R: AzFloat = 0.;
let rad_BR = rad_R + f32::consts::FRAC_PI_4;
let rad_B = rad_BR + f32::consts::FRAC_PI_4;
let rad_BL = rad_B + f32::consts::FRAC_PI_4;
let rad_L = rad_BL + f32::consts::FRAC_PI_4;
let rad_TL = rad_L + f32::consts::FRAC_PI_4;
let rad_T = rad_TL + f32::consts::FRAC_PI_4;
// Returns true if the angular size for this border corner
// is PI/4.
fn simple_border_corner(border_corner_radius: &Size2D<f32>,
border1_width: f32,
border2_width: f32) -> bool {
(border_corner_radius.width - border_corner_radius.height).abs() <= f32::EPSILON &&
(border1_width - border2_width).abs() <= f32::EPSILON
}
if PaintContext::is_zero_radius(radius) {
return;
}
let ellipse = Ellipse { origin: *origin, width: radius.width, height: radius.height };
let simple_border = simple_border_corner(&radius,
(outer_border.x - inner_border.x).abs(),
(outer_border.y - inner_border.y).abs());
let corner_angle = if simple_border {
f32::consts::FRAC_PI_4
} else {
let corner_line = Line::new(*inner_border, *outer_border);
match corner {
BorderCorner::TL | BorderCorner::BL =>
PaintContext::ellipse_leftmost_intersection(ellipse, corner_line).unwrap(),
BorderCorner::TR | BorderCorner::BR =>
PaintContext::ellipse_rightmost_intersection(ellipse, corner_line).unwrap(),
}
};
let (start_angle, end_angle) = match corner {
// TR corner - top border & right border
BorderCorner::TR =>
if clockwise { (-rad_B, rad_R - corner_angle) } else { (rad_R - corner_angle, rad_R) },
// BR corner - right border & bottom border
BorderCorner::BR =>
if clockwise { (rad_R, rad_R + corner_angle) } else { (rad_R + corner_angle, rad_B) },
// TL corner - left border & top border
BorderCorner::TL =>
if clockwise { (rad_L, rad_L + corner_angle) } else { (rad_L + corner_angle, rad_T) },
// BL corner - bottom border & left border
BorderCorner::BL =>
if clockwise { (rad_B, rad_L - corner_angle) } else { (rad_L - corner_angle, rad_L) },
};
if clockwise {
PaintContext::ellipse_to_bezier(path_builder, *origin, *radius, start_angle, end_angle);
PaintContext::ellipse_to_bezier(path_builder, *origin, *dist_elbow, end_angle, start_angle);
} else {
PaintContext::ellipse_to_bezier(path_builder, *origin, *dist_elbow, end_angle, start_angle);
PaintContext::ellipse_to_bezier(path_builder, *origin, *radius, start_angle, end_angle);
}
}
#[allow(non_snake_case)]
fn create_border_path_segment(&self,
path_builder: &mut PathBuilder,
bounds: &Rect<f32>,
direction: Direction,
border: &SideOffsets2D<f32>,
radii: &BorderRadii<AzFloat>,
mode: BorderPathDrawingMode) {
// T = top, B = bottom, L = left, R = right
let inner = PaintContext::inner_border_bounds(bounds, &border);
let (box_TL, inner_TL,
box_TR, inner_TR,
box_BR, inner_BR,
box_BL, inner_BL) = (bounds.origin, inner.origin,
bounds.top_right(), inner.top_right(),
bounds.bottom_right(), inner.bottom_right(),
bounds.bottom_left(), inner.bottom_left());
fn dx(x: AzFloat) -> Point2D<AzFloat> {
Point2D::new(x, 0.)
}
fn dy(y: AzFloat) -> Point2D<AzFloat> {
Point2D::new(0., y)
}
fn dx_if(cond: bool, dx: AzFloat) -> Point2D<AzFloat> {
Point2D::new(if cond { dx } else { 0. }, 0.)
}
fn dy_if(cond: bool, dy: AzFloat) -> Point2D<AzFloat> {
Point2D::new(0., if cond { dy } else { 0. })
}
let (corner_origin, elbow) =
PaintContext::corner_bounds(bounds, border, radii);
let (elbow_TL, elbow_TR, elbow_BR, elbow_BL) =
(elbow.top, elbow.right, elbow.bottom, elbow.left);
match direction {
Direction::Top => {
let edge_TL = box_TL + dx(radii.top_left.width.max(border.left));
let edge_TR = box_TR + dx(-radii.top_right.width.max(border.right));
let edge_BR = box_TR + dx(-border.right - elbow_TR.width) + dy(border.top);
let edge_BL = box_TL + dx(border.left + elbow_TL.width) + dy(border.top);
let corner_TL = edge_TL + dx_if(PaintContext::is_zero_radius(&radii.top_left),
-border.left);
let corner_TR = edge_TR + dx_if(PaintContext::is_zero_radius(&radii.top_right),
border.right);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(corner_TL);
path_builder.line_to(corner_TR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TR),
}
PaintContext::draw_corner(path_builder,
BorderCorner::TR,
&corner_origin.top_right,
&radii.top_right,
&inner_TR,
&box_TR,
&elbow_TR,
true);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(edge_BR);
path_builder.line_to(edge_BL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BL),
}
PaintContext::draw_corner(path_builder,
BorderCorner::TL,
&corner_origin.top_left,
&radii.top_left,
&inner_TL,
&box_TL,
&elbow_TL,
false);
}
Direction::Left => {
let edge_TL = box_TL + dy(radii.top_left.height.max(border.top));
let edge_BL = box_BL + dy(-radii.bottom_left.height.max(border.bottom));
let edge_TR = box_TL + dx(border.left) + dy(border.top + elbow_TL.height);
let edge_BR = box_BL + dx(border.left) + dy(-border.bottom -
elbow_BL.height);
let corner_TL = edge_TL + dy_if(PaintContext::is_zero_radius(&radii.top_left),
-border.top);
let corner_BL = edge_BL + dy_if(PaintContext::is_zero_radius(&radii.bottom_left),
border.bottom);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(corner_BL);
path_builder.line_to(corner_TL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TL),
}
PaintContext::draw_corner(path_builder,
BorderCorner::TL,
&corner_origin.top_left,
&radii.top_left,
&inner_TL,
&box_TL,
&elbow_TL,
true);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(edge_TR);
path_builder.line_to(edge_BR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BR),
}
PaintContext::draw_corner(path_builder,
BorderCorner::BL,
&corner_origin.bottom_left,
&radii.bottom_left,
&inner_BL,
&box_BL,
&elbow_BL,
false);
}
Direction::Right => {
let edge_TR = box_TR + dy(radii.top_right.height.max(border.top));
let edge_BR = box_BR + dy(-radii.bottom_right.height.max(border.bottom));
let edge_TL = box_TR + dx(-border.right) + dy(border.top + elbow_TR.height);
let edge_BL = box_BR + dx(-border.right) + dy(-border.bottom -
elbow_BR.height);
let corner_TR = edge_TR + dy_if(PaintContext::is_zero_radius(&radii.top_right),
-border.top);
let corner_BR = edge_BR + dy_if(PaintContext::is_zero_radius(&radii.bottom_right),
border.bottom);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(edge_BL);
path_builder.line_to(edge_TL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TL),
}
PaintContext::draw_corner(path_builder,
BorderCorner::TR,
&corner_origin.top_right,
&radii.top_right,
&inner_TR,
&box_TR,
&elbow_TR,
false);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(corner_TR);
path_builder.line_to(corner_BR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BR),
}
PaintContext::draw_corner(path_builder,
BorderCorner::BR,
&corner_origin.bottom_right,
&radii.bottom_right,
&inner_BR,
&box_BR,
&elbow_BR,
true);
}
Direction::Bottom => {
let edge_BL = box_BL + dx(radii.bottom_left.width.max(border.left));
let edge_BR = box_BR + dx(-radii.bottom_right.width.max(border.right));
let edge_TL = box_BL + dy(-border.bottom) + dx(border.left +
elbow_BL.width);
let edge_TR = box_BR + dy(-border.bottom) + dx(-border.right -
elbow_BR.width);
let corner_BR = edge_BR + dx_if(PaintContext::is_zero_radius(&radii.bottom_right),
border.right);
let corner_BL = edge_BL + dx_if(PaintContext::is_zero_radius(&radii.bottom_left),
-border.left);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(edge_TL);
path_builder.line_to(edge_TR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TR),
}
PaintContext::draw_corner(path_builder,
BorderCorner::BR,
&corner_origin.bottom_right,
&radii.bottom_right,
&inner_BR,
&box_BR,
&elbow_BR,
false);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(corner_BR);
path_builder.line_to(corner_BL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BL),
}
PaintContext::draw_corner(path_builder,
BorderCorner::BL,
&corner_origin.bottom_left,
&radii.bottom_left,
&inner_BL,
&box_BL,
&elbow_BL,
true);
}