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
// Copyright 2020 Yevhenii Reizner
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use alloc::vec::Vec;

use crate::{Path, LengthU32, FillRule};
use crate::{ALPHA_U8_OPAQUE, ALPHA_U8_TRANSPARENT};

use crate::alpha_runs::AlphaRun;
use crate::blitter::Blitter;
use crate::color::AlphaU8;
use crate::geom::ScreenIntRect;
use crate::math::LENGTH_U32_ONE;
use core::num::NonZeroU32;

#[derive(Clone, Debug)]
pub struct ClipMaskData {
    pub data: Vec<u8>,
    pub width: LengthU32,
    pub height: LengthU32,
}

impl ClipMaskData {
    pub(crate) fn clip_mask_ctx(&self) -> crate::pipeline::ClipMaskCtx {
        crate::pipeline::ClipMaskCtx {
            data: &self.data,
            stride: self.width,
        }
    }
}


/// A clipping mask.
///
/// Unlike Skia, we're using just a simple 8bit alpha mask.
/// It's way slower, but times easier to implement.
#[derive(Clone, Debug)]
pub struct ClipMask {
    pub(crate) mask: ClipMaskData,
}

impl Default for ClipMask {
    fn default() -> Self {
        ClipMask {
            mask: ClipMaskData {
                data: Vec::new(),
                width: LENGTH_U32_ONE,
                height: LENGTH_U32_ONE,
            }
        }
    }
}

impl ClipMask {
    /// Creates a new, empty mask.
    pub fn new() -> Self {
        ClipMask::default()
    }

    /// Checks that mask is empty.
    pub fn is_empty(&self) -> bool {
        self.mask.data.is_empty()
    }

    /// Sets the current clipping path.
    ///
    /// Not additive. Overwrites the previous data.
    ///
    /// Path must be transformed beforehand.
    pub fn set_path(
        &mut self,
        width: u32,
        height: u32,
        path: &Path,
        fill_rule: FillRule,
        anti_alias: bool,
    ) -> Option<()> {
        let width = NonZeroU32::new(width)?;
        let height = NonZeroU32::new(height)?;

        self.mask.width = width;
        self.mask.height = height;

        // Reuse the existing allocation.
        self.mask.data.clear();
        self.mask.data.resize((width.get() * height.get()) as usize, 0);

        let clip = ScreenIntRect::from_xywh_safe(0, 0, width, height);

        if anti_alias {
            let mut builder = ClipBuilderAA(&mut self.mask);
            crate::scan::path_aa::fill_path(path, fill_rule, &clip, &mut builder)
        } else {
            let mut builder = ClipBuilder(&mut self.mask);
            crate::scan::path::fill_path(path, fill_rule, &clip, &mut builder)
        }
    }

    /// Intersects the provided path with the current clipping path.
    ///
    /// Path must be transformed beforehand.
    pub fn intersect_path(
        &mut self,
        path: &Path,
        fill_rule: FillRule,
        anti_alias: bool,
    ) -> Option<()> {
        let mut submask = ClipMask::new();
        submask.set_path(self.mask.width.get(), self.mask.height.get(), path, fill_rule, anti_alias)?;

        for (a, b) in self.mask.data.iter_mut().zip(submask.mask.data.iter()) {
            *a = crate::color::premultiply_u8(*a, *b);
        }

        Some(())
    }

    /// Clears the mask.
    ///
    /// Internal memory buffer is not deallocated.
    pub fn clear(&mut self) {
        // Clear the mask, but keep the allocation.
        self.mask.data.clear();
    }
}


struct ClipBuilder<'a>(&'a mut ClipMaskData);

impl Blitter for ClipBuilder<'_> {
    fn blit_h(&mut self, x: u32, y: u32, width: LengthU32) {
        let offset = (y * self.0.width.get() + x) as usize;
        for i in 0..width.get() as usize {
            self.0.data[offset + i] = 255;
        }
    }
}


struct ClipBuilderAA<'a>(&'a mut ClipMaskData);

impl Blitter for ClipBuilderAA<'_> {
    fn blit_h(&mut self, x: u32, y: u32, width: LengthU32) {
        let offset = (y * self.0.width.get() + x) as usize;
        for i in 0..width.get() as usize {
            self.0.data[offset + i] = 255;
        }
    }

    fn blit_anti_h(&mut self, mut x: u32, y: u32, aa: &mut [AlphaU8], runs: &mut [AlphaRun]) {
        let mut aa_offset = 0;
        let mut run_offset = 0;
        let mut run_opt = runs[0];
        while let Some(run) = run_opt {
            let width = LengthU32::from(run);

            match aa[aa_offset] {
                ALPHA_U8_TRANSPARENT => {}
                ALPHA_U8_OPAQUE => {
                    self.blit_h(x, y, width);
                }
                alpha => {
                    let offset = (y * self.0.width.get() + x) as usize;
                    for i in 0..width.get() as usize {
                        self.0.data[offset + i] = alpha;
                    }
                }
            }

            x += width.get();
            run_offset += usize::from(run.get());
            aa_offset += usize::from(run.get());
            run_opt = runs[run_offset];
        }
    }
}