Repository navigation
Expand file tree
/
Copy pathpainting.dart
More file actions
1228 lines (1049 loc) · 34.1 KB
/
Copy pathpainting.dart
File metadata and controls
1228 lines (1049 loc) · 34.1 KB
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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For documentation see https://github.com/flutter/flutter/blob/main/engine/src/flutter/lib/ui/painting.dart
part of ui;
void _validateColorStops(List<Color> colors, List<double>? colorStops) {
if (colorStops == null) {
if (colors.length != 2) {
throw ArgumentError('"colors" must have length 2 if "colorStops" is omitted.');
}
} else {
if (colors.length != colorStops.length) {
throw ArgumentError('"colors" and "colorStops" arguments must have equal length.');
}
}
}
Color _scaleAlpha(Color x, double factor) {
return x.withValues(alpha: (x.a * factor).clamp(0, 1));
}
ColorSpace _widerColorSpace(ColorSpace a, ColorSpace b) {
return a == ColorSpace.displayP3 || b == ColorSpace.displayP3 ? ColorSpace.displayP3 : a;
}
class Color {
const Color(int value)
: this._fromARGBC(value >> 24, value >> 16, value >> 8, value, ColorSpace.sRGB);
const Color.from({
required double alpha,
required double red,
required double green,
required double blue,
this.colorSpace = ColorSpace.sRGB,
}) : a = alpha,
r = red,
g = green,
b = blue;
const Color.fromARGB(int a, int r, int g, int b) : this._fromARGBC(a, r, g, b, ColorSpace.sRGB);
const Color._fromARGBC(int alpha, int red, int green, int blue, ColorSpace colorSpace)
: this._fromRGBOC(red, green, blue, (alpha & 0xff) / 255, colorSpace);
const Color.fromRGBO(int r, int g, int b, double opacity)
: this._fromRGBOC(r, g, b, opacity, ColorSpace.sRGB);
const Color._fromRGBOC(int r, int g, int b, double opacity, this.colorSpace)
: a = opacity,
r = (r & 0xff) / 255,
g = (g & 0xff) / 255,
b = (b & 0xff) / 255;
final double a;
final double r;
final double g;
final double b;
final ColorSpace colorSpace;
static int _floatToInt8(double x) {
return (x * 255.0).round() & 0xff;
}
int get value => toARGB32();
int toARGB32() {
return _floatToInt8(a) << 24 |
_floatToInt8(r) << 16 |
_floatToInt8(g) << 8 |
_floatToInt8(b) << 0;
}
int get alpha => (0xff000000 & value) >> 24;
double get opacity => alpha / 0xFF;
int get red => (0x00ff0000 & value) >> 16;
int get green => (0x0000ff00 & value) >> 8;
int get blue => (0x000000ff & value) >> 0;
Color withValues({
double? alpha,
double? red,
double? green,
double? blue,
ColorSpace? colorSpace,
}) {
Color? updatedComponents;
if (alpha != null || red != null || green != null || blue != null) {
updatedComponents = Color.from(
alpha: alpha ?? a,
red: red ?? r,
green: green ?? g,
blue: blue ?? b,
colorSpace: this.colorSpace,
);
}
if (colorSpace != null && colorSpace != this.colorSpace) {
final _ColorTransform transform = _getColorTransform(this.colorSpace, colorSpace);
return transform.transform(updatedComponents ?? this, colorSpace);
} else {
return updatedComponents ?? this;
}
}
Color withAlpha(int a) {
return Color.fromARGB(a, red, green, blue);
}
Color withOpacity(double opacity) {
assert(opacity >= 0.0 && opacity <= 1.0);
return withAlpha((255.0 * opacity).round());
}
Color withRed(int r) {
return Color.fromARGB(alpha, r, green, blue);
}
Color withGreen(int g) {
return Color.fromARGB(alpha, red, g, blue);
}
Color withBlue(int b) {
return Color.fromARGB(alpha, red, green, b);
}
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
static double _linearizeColorComponent(double component) {
if (component <= 0.03928) {
return component / 12.92;
}
return math.pow((component + 0.055) / 1.055, 2.4) as double;
}
double computeLuminance() {
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
final double R = _linearizeColorComponent(r);
final double G = _linearizeColorComponent(g);
final double B = _linearizeColorComponent(b);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
static Color? lerp(Color? x, Color? y, double t) {
assert(x?.colorSpace != ColorSpace.extendedSRGB);
assert(y?.colorSpace != ColorSpace.extendedSRGB);
if (y == null) {
if (x == null) {
return null;
} else {
return _scaleAlpha(x, 1.0 - t);
}
} else {
if (x == null) {
return _scaleAlpha(y, t);
} else {
final Color a;
final Color b;
final ColorSpace resultColorSpace;
if (x.colorSpace == y.colorSpace) {
a = x;
b = y;
resultColorSpace = x.colorSpace;
} else {
resultColorSpace = _widerColorSpace(x.colorSpace, y.colorSpace);
a = x.withValues(colorSpace: resultColorSpace);
b = y.withValues(colorSpace: resultColorSpace);
}
return Color.from(
alpha: _lerpDouble(a.a, b.a, t).clamp(0, 1),
red: _lerpDouble(a.r, b.r, t).clamp(0, 1),
green: _lerpDouble(a.g, b.g, t).clamp(0, 1),
blue: _lerpDouble(a.b, b.b, t).clamp(0, 1),
colorSpace: resultColorSpace,
);
}
}
}
static Color alphaBlend(Color foreground, Color background) {
assert(foreground.colorSpace == background.colorSpace);
assert(foreground.colorSpace != ColorSpace.extendedSRGB);
final double alpha = foreground.a;
if (alpha == 0) {
// Foreground completely transparent.
return background;
}
final double invAlpha = 1 - alpha;
double backAlpha = background.a;
if (backAlpha == 1) {
// Opaque background case
return Color.from(
alpha: 1,
red: alpha * foreground.r + invAlpha * background.r,
green: alpha * foreground.g + invAlpha * background.g,
blue: alpha * foreground.b + invAlpha * background.b,
colorSpace: foreground.colorSpace,
);
} else {
// General case
backAlpha = backAlpha * invAlpha;
final double outAlpha = alpha + backAlpha;
assert(outAlpha != 0);
return Color.from(
alpha: outAlpha,
red: (foreground.r * alpha + background.r * backAlpha) / outAlpha,
green: (foreground.g * alpha + background.g * backAlpha) / outAlpha,
blue: (foreground.b * alpha + background.b * backAlpha) / outAlpha,
colorSpace: foreground.colorSpace,
);
}
}
static int getAlphaFromOpacity(double opacity) {
return (clampDouble(opacity, 0.0, 1.0) * 255).round();
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Color &&
other.a == a &&
other.r == r &&
other.g == g &&
other.b == b &&
other.colorSpace == colorSpace;
}
@override
int get hashCode => Object.hash(a, r, g, b, colorSpace);
@override
String toString() =>
'Color(alpha: ${a.toStringAsFixed(4)}, red: ${r.toStringAsFixed(4)}, green: ${g.toStringAsFixed(4)}, blue: ${b.toStringAsFixed(4)}, colorSpace: $colorSpace)';
}
enum StrokeCap { butt, round, square }
// These enum values must be kept in sync with SkPaint::Join.
enum StrokeJoin { miter, round, bevel }
enum PaintingStyle { fill, stroke }
enum BlendMode {
// This list comes from Skia's SkXfermode.h and the values (order) should be
// kept in sync.
// See: https://skia.org/user/api/skpaint#SkXfermode
clear,
src,
dst,
srcOver,
dstOver,
srcIn,
dstIn,
srcOut,
dstOut,
srcATop,
dstATop,
xor,
plus,
modulate,
// Following blend modes are defined in the CSS Compositing standard.
screen, // The last coeff mode.
overlay,
darken,
lighten,
colorDodge,
colorBurn,
hardLight,
softLight,
difference,
exclusion,
multiply, // The last separable mode.
hue,
saturation,
color,
luminosity,
}
enum Clip { none, hardEdge, antiAlias, antiAliasWithSaveLayer }
abstract class Paint {
factory Paint() => engine.EnginePaint();
factory Paint.from(Paint other) {
final paint = Paint();
paint
..blendMode = other.blendMode
..color = other.color
..colorFilter = other.colorFilter
..filterQuality = other.filterQuality
..imageFilter = other.imageFilter
..invertColors = other.invertColors
..isAntiAlias = other.isAntiAlias
..maskFilter = other.maskFilter
..shader = other.shader
..strokeCap = other.strokeCap
..strokeJoin = other.strokeJoin
..strokeMiterLimit = other.strokeMiterLimit
..strokeWidth = other.strokeWidth
..style = other.style;
return paint;
}
BlendMode get blendMode;
set blendMode(BlendMode value);
PaintingStyle get style;
set style(PaintingStyle value);
double get strokeWidth;
set strokeWidth(double value);
StrokeCap get strokeCap;
set strokeCap(StrokeCap value);
StrokeJoin get strokeJoin;
set strokeJoin(StrokeJoin value);
bool get isAntiAlias;
set isAntiAlias(bool value);
Color get color;
set color(Color value);
bool get invertColors;
set invertColors(bool value);
Shader? get shader;
set shader(Shader? value);
MaskFilter? get maskFilter;
set maskFilter(MaskFilter? value);
// TODO(ianh): verify that the image drawing methods actually respect this
FilterQuality get filterQuality;
set filterQuality(FilterQuality value);
ColorFilter? get colorFilter;
set colorFilter(ColorFilter? value);
double get strokeMiterLimit;
set strokeMiterLimit(double value);
ImageFilter? get imageFilter;
set imageFilter(ImageFilter? value);
}
abstract class Shader {
Shader._();
void dispose();
bool get debugDisposed;
}
abstract class Gradient implements Shader {
factory Gradient.linear(
Offset from,
Offset to,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
Float64List? matrix4,
]) {
_validateColorStops(colors, colorStops);
return engine.EngineGradient.linear(
from,
to,
colors,
colorStops,
tileMode,
matrix4 != null ? engine.toMatrix32(matrix4) : null,
);
}
factory Gradient.radial(
Offset center,
double radius,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
Float64List? matrix4,
Offset? focal,
double focalRadius = 0.0,
]) {
_validateColorStops(colors, colorStops);
return engine.EngineGradient.radial(
center,
radius,
colors,
colorStops,
tileMode,
matrix4 != null ? engine.toMatrix32(matrix4) : null,
focal,
focalRadius,
);
}
factory Gradient.sweep(
Offset center,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
double startAngle = 0.0,
double endAngle = math.pi * 2,
Float64List? matrix4,
]) {
_validateColorStops(colors, colorStops);
return engine.EngineGradient.sweep(
center,
colors,
colorStops,
tileMode,
startAngle,
endAngle,
matrix4 != null ? engine.toMatrix32(matrix4) : null,
);
}
}
typedef ImageEventCallback = void Function(Image image);
abstract class Image {
static ImageEventCallback? onCreate;
static ImageEventCallback? onDispose;
int get width;
int get height;
Future<ByteData?> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba});
void dispose();
bool get debugDisposed;
Image clone() => this;
bool isCloneOf(Image other) => other == this;
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
ColorSpace get colorSpace => ColorSpace.sRGB;
@override
String toString() => '[$width\u00D7$height]';
}
class ColorFilter implements ImageFilter {
const factory ColorFilter.mode(Color color, BlendMode blendMode) = engine.EngineColorFilter.mode;
const factory ColorFilter.matrix(List<double> matrix) = engine.EngineColorFilter.matrix;
const factory ColorFilter.linearToSrgbGamma() = engine.EngineColorFilter.linearToSrgbGamma;
const factory ColorFilter.srgbToLinearGamma() = engine.EngineColorFilter.srgbToLinearGamma;
factory ColorFilter.saturation(double saturation) = engine.EngineColorFilter.saturation;
@override
String get debugShortDescription => toString();
}
// These enum values must be kept in sync with SkBlurStyle.
enum BlurStyle {
// These mirror SkBlurStyle and must be kept in sync.
normal,
solid,
outer,
inner,
}
abstract class MaskFilter {
// ignore: no_leading_underscores_for_local_identifiers
const factory MaskFilter.blur(BlurStyle _style, double _sigma) = engine.EngineMaskFilter.blur;
double get webOnlySigma;
BlurStyle get webOnlyBlurStyle;
}
abstract class _ColorTransform {
Color transform(Color color, ColorSpace resultColorSpace);
}
class _IdentityColorTransform implements _ColorTransform {
const _IdentityColorTransform();
@override
Color transform(Color color, ColorSpace resultColorSpace) => color;
}
class _ClampTransform implements _ColorTransform {
const _ClampTransform(this.child);
final _ColorTransform child;
@override
Color transform(Color color, ColorSpace resultColorSpace) {
return Color.from(
alpha: clampDouble(color.a, 0, 1),
red: clampDouble(color.r, 0, 1),
green: clampDouble(color.g, 0, 1),
blue: clampDouble(color.b, 0, 1),
colorSpace: resultColorSpace,
);
}
}
// sRGB standard constants for transfer functions.
// See https://en.wikipedia.org/wiki/SRGB.
const double _kSrgbGamma = 2.4;
const double _kSrgbLinearThreshold = 0.04045;
const double _kSrgbLinearSlope = 12.92;
const double _kSrgbEncodedOffset = 0.055;
const double _kSrgbEncodedDivisor = 1.055;
const double _kSrgbLinearToEncodedThreshold = 0.0031308;
/// sRGB electro-optical transfer function (gamma decode to linear).
double _srgbEOTF(double v) {
if (v <= _kSrgbLinearThreshold) {
return v / _kSrgbLinearSlope;
}
return math.pow((v + _kSrgbEncodedOffset) / _kSrgbEncodedDivisor, _kSrgbGamma).toDouble();
}
/// sRGB opto-electronic transfer function (linear to gamma encode).
double _srgbOETF(double v) {
if (v <= _kSrgbLinearToEncodedThreshold) {
return v * _kSrgbLinearSlope;
}
return _kSrgbEncodedDivisor * math.pow(v, 1.0 / _kSrgbGamma).toDouble() - _kSrgbEncodedOffset;
}
/// Extended versions that handle negative values by mirroring.
double _srgbEOTFExtended(double v) {
return v < 0.0 ? -_srgbEOTF(-v) : _srgbEOTF(v);
}
double _srgbOETFExtended(double v) {
return v < 0.0 ? -_srgbOETF(-v) : _srgbOETF(v);
}
/// Display P3 to sRGB 3x3 matrix in linear space.
/// M = sRGB_XYZ_to_RGB * P3_RGB_to_XYZ
const List<double> _kP3ToSrgbLinear = <double>[
1.2249401,
-0.2249402,
0.0,
-0.0420569,
1.0420571,
0.0,
-0.0196376,
-0.0786507,
1.0982884,
];
/// sRGB to Display P3 3x3 matrix in linear space (inverse of [_kP3ToSrgbLinear]).
const List<double> _kSrgbToP3Linear = <double>[
0.8224622,
0.1775380,
0.0,
0.0331942,
0.9668058,
0.0,
0.0170806,
0.0723974,
0.9105220,
];
/// Converts Display P3 (gamma-encoded) to extended sRGB (gamma-encoded).
/// Pipeline: EOTF(decode) -> 3x3 matrix -> OETF(encode).
class _P3ToSrgbTransform implements _ColorTransform {
const _P3ToSrgbTransform();
@override
Color transform(Color color, ColorSpace resultColorSpace) {
final double rLin = _srgbEOTFExtended(color.r);
final double gLin = _srgbEOTFExtended(color.g);
final double bLin = _srgbEOTFExtended(color.b);
final double rOut =
_kP3ToSrgbLinear[0] * rLin + _kP3ToSrgbLinear[1] * gLin + _kP3ToSrgbLinear[2] * bLin;
final double gOut =
_kP3ToSrgbLinear[3] * rLin + _kP3ToSrgbLinear[4] * gLin + _kP3ToSrgbLinear[5] * bLin;
final double bOut =
_kP3ToSrgbLinear[6] * rLin + _kP3ToSrgbLinear[7] * gLin + _kP3ToSrgbLinear[8] * bLin;
return Color.from(
alpha: color.a,
red: _srgbOETFExtended(rOut),
green: _srgbOETFExtended(gOut),
blue: _srgbOETFExtended(bOut),
colorSpace: resultColorSpace,
);
}
}
// Converts sRGB (gamma-encoded) to Display P3 (gamma-encoded).
// Pipeline: EOTF(decode) -> 3x3 matrix -> OETF(encode).
class _SrgbToP3Transform implements _ColorTransform {
const _SrgbToP3Transform();
@override
Color transform(Color color, ColorSpace resultColorSpace) {
final double rLin = _srgbEOTFExtended(color.r);
final double gLin = _srgbEOTFExtended(color.g);
final double bLin = _srgbEOTFExtended(color.b);
final double rOut =
_kSrgbToP3Linear[0] * rLin + _kSrgbToP3Linear[1] * gLin + _kSrgbToP3Linear[2] * bLin;
final double gOut =
_kSrgbToP3Linear[3] * rLin + _kSrgbToP3Linear[4] * gLin + _kSrgbToP3Linear[5] * bLin;
final double bOut =
_kSrgbToP3Linear[6] * rLin + _kSrgbToP3Linear[7] * gLin + _kSrgbToP3Linear[8] * bLin;
return Color.from(
alpha: color.a,
red: _srgbOETFExtended(rOut),
green: _srgbOETFExtended(gOut),
blue: _srgbOETFExtended(bOut),
colorSpace: resultColorSpace,
);
}
}
_ColorTransform _getColorTransform(ColorSpace source, ColorSpace destination) {
return switch (source) {
ColorSpace.sRGB => switch (destination) {
ColorSpace.sRGB => const _IdentityColorTransform(),
ColorSpace.extendedSRGB => const _IdentityColorTransform(),
ColorSpace.displayP3 => const _SrgbToP3Transform(),
},
ColorSpace.extendedSRGB => switch (destination) {
ColorSpace.sRGB => const _ClampTransform(_IdentityColorTransform()),
ColorSpace.extendedSRGB => const _IdentityColorTransform(),
ColorSpace.displayP3 => const _ClampTransform(_SrgbToP3Transform()),
},
ColorSpace.displayP3 => switch (destination) {
ColorSpace.sRGB => const _ClampTransform(_P3ToSrgbTransform()),
ColorSpace.extendedSRGB => const _P3ToSrgbTransform(),
ColorSpace.displayP3 => const _IdentityColorTransform(),
},
};
}
// This needs to be kept in sync with the "_FilterQuality" enum in skwasm's canvas.cpp
enum FilterQuality { none, low, medium, high }
class ImageFilter {
factory ImageFilter.blur({
double sigmaX = 0.0,
double sigmaY = 0.0,
TileMode? tileMode,
Rect? bounds,
}) => engine.EngineImageFilter.blur(
sigmaX: sigmaX,
sigmaY: sigmaY,
tileMode: tileMode,
bounds: bounds,
);
factory ImageFilter.dilate({double radiusX = 0.0, double radiusY = 0.0}) =>
engine.EngineImageFilter.dilate(radiusX: radiusX, radiusY: radiusY);
factory ImageFilter.erode({double radiusX = 0.0, double radiusY = 0.0}) =>
engine.EngineImageFilter.erode(radiusX: radiusX, radiusY: radiusY);
factory ImageFilter.matrix(
Float64List matrix4, {
FilterQuality filterQuality = FilterQuality.medium,
}) {
if (matrix4.length != 16) {
throw ArgumentError('"matrix4" must have 16 entries.');
}
return engine.EngineImageFilter.matrix(matrix: matrix4, filterQuality: filterQuality);
}
factory ImageFilter.compose({required ImageFilter outer, required ImageFilter inner}) {
engine.EngineImageFilter convert(ImageFilter filter) {
if (filter is engine.EngineColorFilter) {
return engine.EngineColorFilterImageFilter(colorFilter: filter);
}
return filter as engine.EngineImageFilter;
}
return engine.EngineImageFilter.compose(outer: convert(outer), inner: convert(inner));
}
factory ImageFilter.shader(
// ignore: avoid_unused_constructor_parameters
FragmentShader shader, {
// ignore: avoid_unused_constructor_parameters
FilterQuality filterQuality = FilterQuality.none,
}) {
throw UnsupportedError('ImageFilter.shader only supported with Impeller rendering engine.');
}
static bool get isShaderFilterSupported => false;
String get debugShortDescription => toString();
}
enum ColorSpace { sRGB, extendedSRGB, displayP3 }
// This must be kept in sync with the `ImageByteFormat` enum in Skwasm's surface.cpp.
enum ImageByteFormat { rawRgba, rawStraightRgba, rawUnmodified, png }
// This must be kept in sync with the `PixelFormat` enum in Skwasm's image.cpp.
enum PixelFormat { rgba8888, bgra8888, rgbaFloat32 }
enum TargetPixelFormat { dontCare, rgbaFloat32 }
typedef ImageDecoderCallback = void Function(Image result);
abstract class FrameInfo {
Duration get duration;
Image get image;
}
abstract class Codec {
int get frameCount;
int get repetitionCount;
Future<FrameInfo> getNextFrame();
void dispose() {}
}
Future<Codec> instantiateImageCodec(
Uint8List list, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) => engine.engineInstantiateImageCodec(
list,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling,
);
Future<Codec> instantiateImageCodecFromBuffer(
ImmutableBuffer buffer, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) async {
try {
return await engine.engineInstantiateImageCodec(
buffer._list!,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling,
);
} finally {
buffer.dispose();
}
}
Future<Codec> instantiateImageCodecWithSize(
ImmutableBuffer buffer, {
TargetImageSizeCallback? getTargetSize,
}) async {
Codec? codec;
FrameInfo? info;
try {
if (getTargetSize == null) {
return await engine.engineInstantiateImageCodec(buffer._list!);
} else {
codec = await engine.engineInstantiateImageCodec(buffer._list!);
info = await codec.getNextFrame();
final int width = info.image.width;
final int height = info.image.height;
final TargetImageSize targetSize = getTargetSize(width, height);
return await engine.engineInstantiateImageCodec(
buffer._list!,
targetWidth: targetSize.width,
targetHeight: targetSize.height,
);
}
} finally {
info?.image.dispose();
codec?.dispose();
buffer.dispose();
}
}
typedef TargetImageSizeCallback = TargetImageSize Function(int intrinsicWidth, int intrinsicHeight);
class TargetImageSize {
const TargetImageSize({this.width, this.height})
: assert(width == null || width > 0),
assert(height == null || height > 0);
final int? width;
final int? height;
}
void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) {
_decodeImageFromListAsync(list, callback);
}
Future<void> _decodeImageFromListAsync(Uint8List list, ImageDecoderCallback callback) async {
final Codec codec = await instantiateImageCodec(list);
final FrameInfo frameInfo;
try {
frameInfo = await codec.getNextFrame();
} finally {
codec.dispose();
}
callback(frameInfo.image);
}
// Encodes the input pixels into a BMP file that supports transparency.
//
// The `pixels` should be the scanlined raw pixels, 4 bytes per pixel, from left
// to right, then from top to down. The order of the 4 bytes of pixels is
// decided by `format`.
Future<Codec> createBmp(Uint8List pixels, int width, int height, int rowBytes, PixelFormat format) {
final bool swapRedBlue = switch (format) {
PixelFormat.bgra8888 => true,
PixelFormat.rgba8888 => false,
PixelFormat.rgbaFloat32 => throw UnimplementedError(
'RGB conversion from rgbaFloat32 data is not implemented',
),
};
// See https://en.wikipedia.org/wiki/BMP_file_format for format examples.
// The header is in the 108-byte BITMAPV4HEADER format, or as called by
// Chromium, WindowsV4. Do not use the 56-byte or 52-byte Adobe formats, since
// they're not supported.
const dibSize = 0x6C /* 108: BITMAPV4HEADER */;
const int headerSize = dibSize + 0x0E;
final int bufferSize = headerSize + (width * height * 4);
final bmpData = ByteData(bufferSize);
// 'BM' header
bmpData.setUint16(0x00, 0x424D);
// Size of data
bmpData.setUint32(0x02, bufferSize, Endian.little);
// Offset where pixel array begins
bmpData.setUint32(0x0A, headerSize, Endian.little);
// Bytes in DIB header
bmpData.setUint32(0x0E, dibSize, Endian.little);
// Width
bmpData.setUint32(0x12, width, Endian.little);
// Height
bmpData.setUint32(0x16, height, Endian.little);
// Color panes (always 1)
bmpData.setUint16(0x1A, 0x01, Endian.little);
// bpp: 32
bmpData.setUint16(0x1C, 32, Endian.little);
// Compression method is BITFIELDS to enable bit fields
bmpData.setUint32(0x1E, 3, Endian.little);
// Raw bitmap data size
bmpData.setUint32(0x22, width * height, Endian.little);
// Print DPI width
bmpData.setUint32(0x26, width, Endian.little);
// Print DPI height
bmpData.setUint32(0x2A, height, Endian.little);
// Colors in the palette
bmpData.setUint32(0x2E, 0x00, Endian.little);
// Important colors
bmpData.setUint32(0x32, 0x00, Endian.little);
// Bitmask R
bmpData.setUint32(0x36, swapRedBlue ? 0x00FF0000 : 0x000000FF, Endian.little);
// Bitmask G
bmpData.setUint32(0x3A, 0x0000FF00, Endian.little);
// Bitmask B
bmpData.setUint32(0x3E, swapRedBlue ? 0x000000FF : 0x00FF0000, Endian.little);
// Bitmask A
bmpData.setUint32(0x42, 0xFF000000, Endian.little);
var destinationByte = headerSize;
final combinedPixels = Uint32List.sublistView(pixels);
// BMP is scanlined from bottom to top. Rearrange here.
for (int rowCount = height - 1; rowCount >= 0; rowCount -= 1) {
int sourcePixel = rowCount * rowBytes;
for (var colCount = 0; colCount < width; colCount += 1) {
bmpData.setUint32(destinationByte, combinedPixels[sourcePixel], Endian.little);
destinationByte += 4;
sourcePixel += 1;
}
}
return instantiateImageCodec(bmpData.buffer.asUint8List());
}
void decodeImageFromPixels(
Uint8List pixels,
int width,
int height,
PixelFormat format,
ImageDecoderCallback callback, {
int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
TargetPixelFormat targetFormat = TargetPixelFormat.dontCare,
}) => engine.renderer.decodeImageFromPixels(
pixels,
width,
height,
format,
callback,
rowBytes: rowBytes,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling,
);
Image decodeImageFromPixelsSync(Uint8List pixels, int width, int height, PixelFormat format) =>
throw UnimplementedError('`decodeImageFromPixelsSync` is not implemented for web targets.');
class Shadow {
const Shadow({
this.color = const Color(_kColorDefault),
this.offset = Offset.zero,
this.blurRadius = 0.0,
}) : assert(blurRadius >= 0.0, 'Text shadow blur radius should be non-negative.');
static const int _kColorDefault = 0xFF000000;
final Color color;
final Offset offset;
final double blurRadius;
// See SkBlurMask::ConvertRadiusToSigma().
// <https://github.com/google/skia/blob/bb5b77db51d2e149ee66db284903572a5aac09be/src/effects/SkBlurMask.cpp#L23>
static double convertRadiusToSigma(double radius) {
return radius > 0 ? radius * 0.57735 + 0.5 : 0;
}
double get blurSigma => convertRadiusToSigma(blurRadius);
Paint toPaint() {
return Paint()
..color = color
..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma);
}
Shadow scale(double factor) {
return Shadow(color: color, offset: offset * factor, blurRadius: blurRadius * factor);
}
static Shadow? lerp(Shadow? a, Shadow? b, double t) {
if (b == null) {
if (a == null) {
return null;
} else {
return a.scale(1.0 - t);
}
} else {
if (a == null) {
return b.scale(t);
} else {
return Shadow(
color: Color.lerp(a.color, b.color, t)!,
offset: Offset.lerp(a.offset, b.offset, t)!,
blurRadius: _lerpDouble(a.blurRadius, b.blurRadius, t),
);
}
}
}
static List<Shadow>? lerpList(List<Shadow>? a, List<Shadow>? b, double t) {
if (a == null && b == null) {
return null;
}
a ??= <Shadow>[];
b ??= <Shadow>[];
final result = <Shadow>[];
final int commonLength = math.min(a.length, b.length);
for (var i = 0; i < commonLength; i += 1) {
result.add(Shadow.lerp(a[i], b[i], t)!);
}
for (var i = commonLength; i < a.length; i += 1) {
result.add(a[i].scale(1.0 - t));
}
for (var i = commonLength; i < b.length; i += 1) {
result.add(b[i].scale(t));
}
return result;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is Shadow &&
other.color == color &&
other.offset == offset &&
other.blurRadius == blurRadius;
}
@override
int get hashCode => Object.hash(color, offset, blurRadius);
@override
String toString() => 'TextShadow($color, $offset, $blurRadius)';
}
abstract class ImageShader implements Shader {
factory ImageShader(
Image image,
TileMode tmx,
TileMode tmy,
Float64List matrix4, {
FilterQuality? filterQuality,
}) => engine.EngineImageShader(image, tmx, tmy, matrix4, filterQuality: filterQuality);
@override