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
use sw_composite::*;

use crate::{IntPoint, Point, Transform};
use crate::draw_target::{ExtendMode, Source, FilterMode};

use euclid::vec2;
use std::marker::PhantomData;

pub trait Blitter {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, mask: &[u8]);
}

pub trait RasterBlitter {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32);
}

pub struct MaskSuperBlitter {
    pub x: i32,
    pub y: i32,
    width: i32,
    pub buf: Vec<u8>,
}

const SHIFT: i32 = crate::rasterizer::SAMPLE_SHIFT;
const SCALE: i32 = 1 << SHIFT;
const MASK: i32 = SCALE - 1;
const SUPER_MASK: i32 = (1 << SHIFT) - 1;

fn coverage_to_partial_alpha(mut aa: i32) -> u8 {
    aa <<= 8 - 2 * SHIFT;
    return aa as u8;
}

impl MaskSuperBlitter {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> MaskSuperBlitter {
        MaskSuperBlitter {
            x: x * SCALE, y: y * SCALE,
            width,
            // we can end up writing one byte past the end of the buffer so allocate that
            // padding to avoid needing to do an extra check
            buf: vec![0; (width * height) as usize + 1],
        }
    }
}

// Perform this tricky subtract, to avoid overflowing to 256. Our caller should
// only ever call us with at most enough to hit 256 (never larger), so it is
// enough to just subtract the high-bit. Actually clamping with a branch would
// be slower (e.g. if (tmp > 255) tmp = 255;)
fn saturated_add(a: u8, b: u8) -> u8 {
    let tmp = a as u32 + b as u32;
    let result = tmp - (tmp >> 8);
    result as u8
}

impl RasterBlitter for MaskSuperBlitter {
    fn blit_span(&mut self, mut y: i32, mut x1: i32, mut x2: i32) {
        y -= self.y;
        x1 -= self.x;
        x2 -= self.x;
        x2 = x2.min(self.width * SCALE);
        let max: u8 = ((1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT)) as u8;
        let start = (y / 4 * self.width) as usize;

        let mut fb = x1 & SUPER_MASK;
        let fe = x2 & SUPER_MASK;
        let b = &mut self.buf[start + (x1 >> SHIFT) as usize..start + (x2 >> SHIFT) as usize + 1];
        let len = b.len();

        // invert the alpha on the left side
        if len == 0 {
        } else if len == 1 {
            b[0] = saturated_add(b[0], coverage_to_partial_alpha(fe - fb));
        } else {
            fb = (1 << SHIFT) - fb;
            b[0] = saturated_add(b[0], coverage_to_partial_alpha(fb));

            // Rust seems to emit bounds checks here when it should be able to avoid them
            for i in &mut b[1..len-1] {
                *i += max;
            }
            b[len-1] = saturated_add(b[len-1], coverage_to_partial_alpha(fe));
        }
    }
}

pub struct MaskBlitter {
    pub x: i32,
    pub y: i32,
    width: i32,
    pub buf: Vec<u8>,
}

impl MaskBlitter {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> MaskBlitter {
        MaskBlitter {
            x: x * SCALE,
            y: y * SCALE,
            width,
            // we can end up writing one byte past the end of the buffer so allocate that
            // padding to avoid needing to do an extra check
            buf: vec![0; (width * height) as usize + 1],
        }
    }
}

impl RasterBlitter for MaskBlitter {
    fn blit_span(&mut self, mut y: i32, mut x1: i32, mut x2: i32) {
        y -= self.y;
        x1 -= self.x;
        x2 -= self.x;
        if y % SCALE != 0 {
            return;
        }

        x2 = x2.min(self.width * SCALE);

        x1 >>= SHIFT;
        x2 >>= SHIFT;

        for i in x1..x2 {
            self.buf[(y / 4 * self.width + i) as usize] = 0xff;
        }
    }
}

pub trait Shader {
    fn shade_span(&self, x: i32, y: i32, dest: &mut [u32], count: usize);
}

pub struct SolidShader {
    pub color: u32,
}

impl Shader for SolidShader {
    fn shade_span(&self, _x: i32, _y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            dest[i] = self.color;
        }
    }
}

fn transform_to_fixed(transform: &Transform) -> MatrixFixedPoint {
    MatrixFixedPoint {
        xx: float_to_fixed(transform.m11),
        xy: float_to_fixed(transform.m21),
        yx: float_to_fixed(transform.m12),
        yy: float_to_fixed(transform.m22),
        x0: float_to_fixed(transform.m31),
        y0: float_to_fixed(transform.m32),
    }
}

pub struct TransformedImageShader<'a, 'b, Fetch: PixelFetch> {
    image: &'a Image<'b>,
    xfm: MatrixFixedPoint,
    fetch: PhantomData<Fetch>,
}

impl<'a, 'b, Fetch: PixelFetch> TransformedImageShader<'a, 'b, Fetch> {
    pub fn new(image: &'a Image<'b>, transform: &Transform) -> TransformedImageShader<'a, 'b, Fetch> {
        TransformedImageShader {
            image,
            xfm: transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5)).then_translate(vec2(-0.5, -0.5))),
            fetch: PhantomData,
        }
    }
}

impl<'a, 'b, Fetch: PixelFetch> Shader for TransformedImageShader<'a, 'b, Fetch> {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            let p = self.xfm.transform(x as u16, y as u16);
            dest[i] = fetch_bilinear::<Fetch>(self.image, p.x, p.y);
            x += 1;
        }
    }
}

pub struct TransformedImageAlphaShader<'a, 'b, Fetch: PixelFetch> {
    image: &'a Image<'b>,
    xfm: MatrixFixedPoint,
    alpha: u32,
    fetch: PhantomData<Fetch>,
}

impl<'a, 'b, Fetch: PixelFetch> TransformedImageAlphaShader<'a, 'b, Fetch> {
    pub fn new(image: &'a Image<'b>, transform: &Transform, alpha: u32) -> TransformedImageAlphaShader<'a, 'b, Fetch> {
        TransformedImageAlphaShader {
            image,
            xfm: transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5)).then_translate(vec2(-0.5, -0.5))),
            alpha: alpha_to_alpha256(alpha),
            fetch: PhantomData,
        }
    }
}

impl<'a, 'b, Fetch: PixelFetch> Shader for TransformedImageAlphaShader<'a, 'b, Fetch> {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            let p = self.xfm.transform(x as u16, y as u16);
            dest[i] = fetch_bilinear_alpha::<Fetch>(self.image, p.x, p.y, self.alpha);
            x += 1;
        }
    }
}

pub struct TransformedNearestImageShader<'a, 'b, Fetch: PixelFetch> {
    image: &'a Image<'b>,
    xfm: MatrixFixedPoint,
    fetch: PhantomData<Fetch>,
}

impl<'a, 'b, Fetch: PixelFetch> TransformedNearestImageShader<'a, 'b, Fetch> {
    pub fn new(image: &'a Image<'b>, transform: &Transform) -> TransformedNearestImageShader<'a, 'b, Fetch> {
        TransformedNearestImageShader {
            image,
            xfm: transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5)).then_translate(vec2(-0.5, -0.5))),
            fetch: PhantomData,
        }
    }
}

impl<'a, 'b, Fetch: PixelFetch> Shader for TransformedNearestImageShader<'a, 'b, Fetch> {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            let p = self.xfm.transform(x as u16, y as u16);
            dest[i] = fetch_nearest::<Fetch>(self.image, p.x, p.y);
            x += 1;
        }
    }
}

pub struct TransformedNearestImageAlphaShader<'a, 'b, Fetch: PixelFetch> {
    image: &'a Image<'b>,
    xfm: MatrixFixedPoint,
    alpha: u32,
    fetch: PhantomData<Fetch>,
}

impl<'a, 'b, Fetch: PixelFetch> TransformedNearestImageAlphaShader<'a, 'b, Fetch> {
    pub fn new(image: &'a Image<'b>, transform: &Transform, alpha: u32) -> TransformedNearestImageAlphaShader<'a, 'b, Fetch> {
        TransformedNearestImageAlphaShader {
            image,
            xfm: transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5)).then_translate(vec2(-0.5, -0.5))),
            alpha: alpha_to_alpha256(alpha),
            fetch: PhantomData,
        }
    }
}

impl<'a, 'b, Fetch: PixelFetch> Shader for TransformedNearestImageAlphaShader<'a, 'b, Fetch> {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            let p = self.xfm.transform(x as u16, y as u16);
            dest[i] = fetch_nearest_alpha::<Fetch>(self.image, p.x, p.y, self.alpha);
            x += 1;
        }
    }
}

pub struct ImagePadAlphaShader<'a, 'b> {
    image: &'a Image<'b>,
    offset_x: i32,
    offset_y: i32,
    alpha: u32,
}

impl<'a, 'b> ImagePadAlphaShader<'a, 'b> {
    pub fn new(image: &'a Image<'b>, x: i32, y: i32, alpha: u32) -> ImagePadAlphaShader<'a, 'b> {
        ImagePadAlphaShader {
            image,
            offset_x: x,
            offset_y: y,
            alpha: alpha_to_alpha256(alpha),
        }
    }
}

impl<'a, 'b> Shader for ImagePadAlphaShader<'a, 'b> {
    fn shade_span(&self, mut x: i32, mut y: i32, dest: &mut [u32], mut count: usize) {
        x += self.offset_x;
        y += self.offset_y;
        let mut dest_x = 0;

        if y < 0 {
            y = 0;
        } else if y >= self.image.height {
            y = self.image.height - 1;
        }

        while x < 0 && count > 0 {
            dest[dest_x] = alpha_mul(self.image.data[(self.image.width * y) as usize], self.alpha);
            x += 1;
            dest_x += 1;
            count -= 1;
        }
        if count > 0 && x < self.image.width {
            let len = count.min((self.image.width - x) as usize);
            let d = &mut dest[dest_x..dest_x + len];
            let src_start = (self.image.width * y + x) as usize;
            let s = &self.image.data[src_start..src_start + len];

            for (d, s) in d.iter_mut().zip(s) {
                *d = alpha_mul(*s, self.alpha);
            }

            dest_x += len;
            count -= len;
        }
        while count > 0 {
            dest[dest_x] = alpha_mul(self.image.data[(self.image.width * y + self.image.width - 1) as usize], self.alpha);
            dest_x += 1;
            count -= 1;
        }
    }
}

pub struct ImageRepeatAlphaShader<'a, 'b> {
    image: &'a Image<'b>,
    offset_x: i32,
    offset_y: i32,
    alpha: u32,
}

impl<'a, 'b> ImageRepeatAlphaShader<'a, 'b> {
    pub fn new(image: &'a Image<'b>, x: i32, y: i32, alpha: u32) -> ImageRepeatAlphaShader<'a, 'b> {
        ImageRepeatAlphaShader {
            image,
            offset_x: x,
            offset_y: y,
            alpha: alpha_to_alpha256(alpha),
        }
    }
}

impl<'a, 'b> Shader for ImageRepeatAlphaShader<'a, 'b> {
    fn shade_span(&self, mut x: i32, mut y: i32, dest: &mut [u32], mut count: usize) {
        x += self.offset_x;
        y += self.offset_y;
        let mut dest_x = 0;

        let y = y.rem_euclid(self.image.height);
        let mut x = x.rem_euclid(self.image.width);

        while count > 0 {
            let len = count.min((self.image.width - x) as usize);
            let d = &mut dest[dest_x..dest_x + len];
            let src_start = (self.image.width * y + x) as usize;
            let s = &self.image.data[src_start..src_start + len];

            for (d, s) in d.iter_mut().zip(s) {
                *d = alpha_mul(*s, self.alpha);
            }

            dest_x += len;
            count -= len;
            x = 0;
        }
    }
}

pub struct RadialGradientShader {
    gradient: Box<GradientSource>,
    spread: Spread,
}

impl RadialGradientShader {
    pub fn new(gradient: &Gradient, transform: &Transform, spread: Spread, alpha: u32) -> RadialGradientShader {
        RadialGradientShader {
            gradient: gradient.make_source(&transform_to_fixed(
                &transform.pre_translate(vec2(0.5, 0.5))),
                alpha
            ),
            spread,
        }
    }
}

impl Shader for RadialGradientShader {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            dest[i] = self.gradient.radial_gradient_eval(x as u16, y as u16, self.spread);
            x += 1;
        }
    }
}

pub struct TwoCircleRadialGradientShader {
    gradient: Box<TwoCircleRadialGradientSource>,
    spread: Spread,
}

impl TwoCircleRadialGradientShader {
    pub fn new(gradient: &Gradient,
               transform: &Transform,
               c1: Point,
               r1: f32,
               c2: Point,
               r2: f32,
               spread: Spread,
               alpha: u32) -> TwoCircleRadialGradientShader {
        TwoCircleRadialGradientShader {
            gradient: gradient.make_two_circle_source(
                c1.x, c1.y,
                r1,
                c2.x, c2.y,
                r2,
                &transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5))), alpha
            ),
            spread,
        }
    }
}

impl Shader for TwoCircleRadialGradientShader {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            dest[i] = self.gradient.eval(x as u16, y as u16, self.spread);
            x += 1;
        }
    }
}

pub struct SweepGradientShader {
    gradient: Box<SweepGradientSource>,
    spread: Spread,
}

impl SweepGradientShader {
    pub fn new(gradient: &Gradient,
               transform: &Transform,
               start_angle: f32,
               end_angle: f32,
               spread: Spread,
               alpha: u32) -> SweepGradientShader {
        SweepGradientShader {
            gradient: gradient.make_sweep_source(
                start_angle,
                end_angle,
                &transform_to_fixed(&transform.pre_translate(vec2(0.5, 0.5))), alpha
            ),
            spread,
        }
    }
}

impl Shader for SweepGradientShader {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            dest[i] = self.gradient.eval(x as u16, y as u16, self.spread);
            x += 1;
        }
    }
}

pub struct LinearGradientShader {
    gradient: Box<GradientSource>,
    spread: Spread,
}

impl LinearGradientShader {
    pub fn new(gradient: &Gradient, transform: &Transform, spread: Spread, alpha: u32) -> LinearGradientShader {
        LinearGradientShader {
            gradient: gradient.make_source(&transform_to_fixed(
                &transform.pre_translate(vec2(0.5, 0.5))),
                alpha
            ),
            spread,
        }
    }
}

impl Shader for LinearGradientShader {
    fn shade_span(&self, mut x: i32, y: i32, dest: &mut [u32], count: usize) {
        for i in 0..count {
            dest[i] = self.gradient.linear_gradient_eval(x as u16, y as u16, self.spread);
            x += 1;
        }
    }
}

pub struct ShaderMaskBlitter<'a> {
    pub x: i32,
    pub y: i32,
    pub shader: &'a dyn Shader,
    pub tmp: Vec<u32>,
    pub dest: &'a mut [u32],
    pub dest_stride: i32,
}

impl<'a> Blitter for ShaderMaskBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, mask: &[u8]) {
        let dest_row = (y - self.y) * self.dest_stride;
        let count = (x2 - x1) as usize;
        self.shader.shade_span(x1, y, &mut self.tmp[..], count);
        for i in 0..count {
            let mask = mask[i] as u32;
            if mask != 0 {
                self.dest[(dest_row + x1 - self.x) as usize + i] = over_in(
                    self.tmp[i],
                    self.dest[(dest_row + x1 - self.x) as usize + i],
                    mask,
                );
            }
        }
    }
}

pub struct ShaderClipMaskBlitter<'a> {
    pub x: i32,
    pub y: i32,
    pub shader: &'a dyn Shader,
    pub tmp: Vec<u32>,
    pub dest: &'a mut [u32],
    pub dest_stride: i32,
    pub clip: &'a [u8],
    pub clip_stride: i32,
}

impl<'a> Blitter for ShaderClipMaskBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, mask: &[u8]) {
        let dest_row = (y - self.y) * self.dest_stride;
        let clip_row = y * self.clip_stride;
        let count = (x2 - x1) as usize;
        self.shader.shade_span(x1, y, &mut self.tmp[..], count);
        for i in 0..count {
            let mask = mask[i] as u32;
            let clip = self.clip[(clip_row + x1) as usize + i] as u32;
            if mask != 0 && clip != 0 {
                self.dest[(dest_row + x1 - self.x) as usize + i] = over_in_in(
                    self.tmp[i],
                    self.dest[(dest_row + x1 - self.x) as usize + i],
                    mask,
                    clip,
                );
            }
        }
    }
}

pub struct ShaderClipBlendMaskBlitter<'a> {
    pub x: i32,
    pub y: i32,
    pub shader: &'a dyn Shader,
    pub tmp: Vec<u32>,
    pub dest: &'a mut [u32],
    pub dest_stride: i32,
    pub clip: &'a [u8],
    pub clip_stride: i32,
    pub blend_fn: fn (&[u32], &[u8], &[u8], &mut [u32]),
}

impl<'a> Blitter for ShaderClipBlendMaskBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, mask: &[u8]) {
        let dest_row = (y - self.y) * self.dest_stride;
        let clip_row = y * self.clip_stride;
        let count = (x2 - x1) as usize;
        self.shader.shade_span(x1, y, &mut self.tmp[..], count);
        (self.blend_fn)(&self.tmp[..],
                      mask,
                      &self.clip[(clip_row + x1) as usize..],
                      &mut self.dest[(dest_row + x1 - self.x) as usize..])
    }
}

pub struct ShaderBlendMaskBlitter<'a> {
    pub x: i32,
    pub y: i32,
    pub shader: &'a dyn Shader,
    pub tmp: Vec<u32>,
    pub dest: &'a mut [u32],
    pub dest_stride: i32,
    pub blend_fn: fn (&[u32], &[u8], &mut [u32]),
}

impl<'a> Blitter for ShaderBlendMaskBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, mask: &[u8]) {
        let dest_row = (y - self.y) * self.dest_stride;
        let count = (x2 - x1) as usize;
        self.shader.shade_span(x1, y, &mut self.tmp[..], count);
        (self.blend_fn)(&self.tmp[..],
                        mask,
                        &mut self.dest[(dest_row + x1 - self.x) as usize..])
    }
}

pub struct ShaderBlendBlitter<'a> {
    pub x: i32,
    pub y: i32,
    pub shader: &'a dyn Shader,
    pub tmp: Vec<u32>,
    pub dest: &'a mut [u32],
    pub dest_stride: i32,
    pub blend_fn: fn (&[u32], &mut [u32]),
}

impl<'a> Blitter for ShaderBlendBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32, _: &[u8]) {
        let dest_row = (y - self.y) * self.dest_stride;
        let count = (x2 - x1) as usize;
        self.shader.shade_span(x1, y, &mut self.tmp[..], count);
        (self.blend_fn)(&self.tmp[..],
                        &mut self.dest[(dest_row + x1 - self.x) as usize..])
    }
}


fn is_integer_transform(trans: &Transform) -> Option<IntPoint> {
    if trans.m11 == 1. &&
        trans.m12 == 0. &&
        trans.m21 == 0. &&
        trans.m22 == 1. {
        let x = trans.m31 as i32;
        let y = trans.m32 as i32;
        if x as f32 == trans.m31 &&
            y as f32 == trans.m32 {
            return Some(IntPoint::new(x, y))
        }
    }
    None
}

pub enum ShaderStorage<'a, 'b> {
    None,
    Solid(SolidShader),
    ImagePadAlpha(ImagePadAlphaShader<'a, 'b>),
    ImageRepeatAlpha(ImageRepeatAlphaShader<'a, 'b>),
    TransformedNearestPadImageAlpha(TransformedNearestImageAlphaShader<'a, 'b, PadFetch>),
    TransformedNearestRepeatImageAlpha(TransformedNearestImageAlphaShader<'a, 'b, RepeatFetch>),
    TransformedPadImageAlpha(TransformedImageAlphaShader<'a, 'b, PadFetch>),
    TransformedRepeatImageAlpha(TransformedImageAlphaShader<'a, 'b, RepeatFetch>),
    TransformedPadImage(TransformedImageShader<'a, 'b, PadFetch>),
    TransformedRepeatImage(TransformedImageShader<'a, 'b, RepeatFetch>),
    TransformedNearestPadImage(TransformedNearestImageShader<'a, 'b, PadFetch>),
    TransformedNearestRepeatImage(TransformedNearestImageShader<'a, 'b, RepeatFetch>),
    RadialGradient(RadialGradientShader),
    TwoCircleRadialGradient(TwoCircleRadialGradientShader),
    LinearGradient(LinearGradientShader),
    SweepGradient(SweepGradientShader),
}

// The idea here is to store a shader in shader_storage and then return
// a reference to it. The goal is to avoid a heap allocation but the end
// result is pretty ugly.
pub fn choose_shader<'a, 'b, 'c>(ti: &Transform, src: &'b Source<'c>, alpha: f32, shader_storage: &'a mut ShaderStorage<'b, 'c>) -> &'a dyn Shader {
    // XXX: clamp alpha
    let alpha = (alpha * 255. + 0.5) as u32;

    *shader_storage = match src {
        Source::Solid(c) => {
            let color = alpha_mul(c.to_u32(), alpha_to_alpha256(alpha));
            let s = SolidShader { color };
            ShaderStorage::Solid(s)
        }
        Source::Image(ref image, ExtendMode::Pad, filter, transform) => {
            if let Some(offset) = is_integer_transform(&ti.then(&transform)) {
                ShaderStorage::ImagePadAlpha(ImagePadAlphaShader::new(image, offset.x, offset.y, alpha))
            } else {
                if alpha != 255 {
                    if *filter == FilterMode::Bilinear {
                        let s = TransformedImageAlphaShader::<PadFetch>::new(image, &ti.then(&transform), alpha);
                        ShaderStorage::TransformedPadImageAlpha(s)
                    } else {
                        let s = TransformedNearestImageAlphaShader::<PadFetch>::new(image, &ti.then(&transform), alpha);
                        ShaderStorage::TransformedNearestPadImageAlpha(s)
                    }
                } else {
                    if *filter == FilterMode::Bilinear {
                        let s = TransformedImageShader::<PadFetch>::new(image, &ti.then(&transform));
                        ShaderStorage::TransformedPadImage(s)
                    } else {
                        let s = TransformedNearestImageShader::<PadFetch>::new(image, &ti.then(&transform));
                        ShaderStorage::TransformedNearestPadImage(s)
                    }
                }
            }
        }
        Source::Image(ref image, ExtendMode::Repeat, filter, transform) => {
            if let Some(offset) = is_integer_transform(&ti.then(&transform)) {
                ShaderStorage::ImageRepeatAlpha(ImageRepeatAlphaShader::new(image, offset.x, offset.y, alpha))
            } else {
                if *filter == FilterMode::Bilinear {
                    if alpha != 255 {
                        let s = TransformedImageAlphaShader::<RepeatFetch>::new(image, &ti.then(&transform), alpha);
                        ShaderStorage::TransformedRepeatImageAlpha(s)
                    } else {
                        let s = TransformedImageShader::<RepeatFetch>::new(image, &ti.then(&transform));
                        ShaderStorage::TransformedRepeatImage(s)
                    }
                } else {
                    if alpha != 255 {
                        let s = TransformedNearestImageAlphaShader::<RepeatFetch>::new(image, &ti.then(&transform), alpha);
                        ShaderStorage::TransformedNearestRepeatImageAlpha(s)
                    } else {
                        let s = TransformedNearestImageShader::<RepeatFetch>::new(image, &ti.then(&transform));
                        ShaderStorage::TransformedNearestRepeatImage(s)
                    }
                }
            }
        }
        Source::RadialGradient(ref gradient, spread, transform) => {
            let s = RadialGradientShader::new(gradient, &ti.then(&transform), *spread, alpha);
            ShaderStorage::RadialGradient(s)
        }
        Source::TwoCircleRadialGradient(ref gradient, spread, c1, r1, c2, r2, transform) => {
            let s = TwoCircleRadialGradientShader::new(gradient, &ti.then(&transform), *c1, *r1, *c2, *r2, *spread, alpha);
            ShaderStorage::TwoCircleRadialGradient(s)
        }
        Source::SweepGradient(ref gradient, spread, start_angle, end_angle, transform) => {
            let s = SweepGradientShader::new(gradient, &ti.then(&transform), *start_angle, *end_angle, *spread, alpha);
            ShaderStorage::SweepGradient(s)
        }
        Source::LinearGradient(ref gradient, spread, transform) => {
            let s = LinearGradientShader::new(gradient, &ti.then(&transform), *spread, alpha);
            ShaderStorage::LinearGradient(s)
        }
    };

    match shader_storage {
        ShaderStorage::None => unreachable!(),
        ShaderStorage::Solid(s) => s,
        ShaderStorage::ImagePadAlpha(s) => s,
        ShaderStorage::ImageRepeatAlpha(s) => s,
        ShaderStorage::TransformedNearestPadImageAlpha(s) => s,
        ShaderStorage::TransformedNearestRepeatImageAlpha(s) => s,
        ShaderStorage::TransformedPadImageAlpha(s) => s,
        ShaderStorage::TransformedRepeatImageAlpha(s) => s,
        ShaderStorage::TransformedPadImage(s) => s,
        ShaderStorage::TransformedRepeatImage(s) => s,
        ShaderStorage::TransformedNearestPadImage(s) => s,
        ShaderStorage::TransformedNearestRepeatImage(s) => s,
        ShaderStorage::RadialGradient(s) => s,
        ShaderStorage::TwoCircleRadialGradient(s) => s,
        ShaderStorage::SweepGradient(s) => s,
        ShaderStorage::LinearGradient(s) => s,
    }
}

pub enum ShaderBlitterStorage<'a> {
    None,
    ShaderBlendMaskBlitter(ShaderBlendMaskBlitter<'a>),
    ShaderClipBlendMaskBlitter(ShaderClipBlendMaskBlitter<'a>),
    ShaderMaskBlitter(ShaderMaskBlitter<'a>),
    ShaderClipMaskBlitter(ShaderClipMaskBlitter<'a>),
    ShaderBlendBlitter(ShaderBlendBlitter<'a>),
}

/*
pub struct SolidBlitter<'a> {
    color: u32,
    mask: &'a [u8],
    dest: &'a mut [u32],
    dest_stride: i32,
    mask_stride: i32,
}

impl<'a> Blitter for SolidBlitter<'a> {
    fn blit_span(&mut self, y: i32, x1: i32, x2: i32) {
        let dest_row = y * self.dest_stride;
        let mask_row = y * self.mask_stride;
        for i in x1..x2 {
            self.dest[(dest_row + i) as usize] = over_in(
                self.color,
                self.dest[(dest_row + i) as usize],
                self.mask[(mask_row + i) as usize] as u32,
            );
        }
    }
}
*/