summaryrefslogtreecommitdiff
path: root/Userland/Applications/PixelPaint/Mask.cpp
blob: 51fbcf46645a04d6d4caedbd91a7579f8355477d (plain)
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
/*
 * Copyright (c) 2021, Davipb <daviparca@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Mask.h"

namespace PixelPaint {

Mask::Mask(Gfx::IntRect bounding_rect, u8 default_value)
    : m_bounding_rect(bounding_rect)
{
    auto data_size = bounding_rect.size().area();
    m_data.resize(data_size);

    for (auto& x : m_data) {
        x = default_value;
    }
}

size_t Mask::to_index(int x, int y) const
{
    VERIFY(m_bounding_rect.contains(x, y));

    int dx = x - m_bounding_rect.x();
    int dy = y - m_bounding_rect.y();
    return dy * m_bounding_rect.width() + dx;
}

u8 Mask::get(int x, int y) const
{
    if (is_null() || !m_bounding_rect.contains(x, y)) {
        return 0;
    }

    return m_data[to_index(x, y)];
}

void Mask::set(int x, int y, u8 value)
{
    VERIFY(!is_null());
    VERIFY(m_bounding_rect.contains(x, y));

    m_data[to_index(x, y)] = value;
}

Mask Mask::with_bounding_rect(Gfx::IntRect inner_rect) const
{
    auto result = Mask::empty(inner_rect);

    result.for_each_pixel([&](int x, int y) {
        result.set(x, y, get(x, y));
    });

    return result;
}

void Mask::shrink_to_fit()
{
    int topmost = NumericLimits<int>::max();
    int bottommost = NumericLimits<int>::min();
    int leftmost = NumericLimits<int>::max();
    int rightmost = NumericLimits<int>::min();

    bool empty = true;
    for_each_pixel([&](auto x, auto y) {
        if (get(x, y) == 0) {
            return;
        }

        empty = false;

        topmost = min(topmost, y);
        bottommost = max(bottommost, y);

        leftmost = min(leftmost, x);
        rightmost = max(rightmost, x);
    });

    if (empty) {
        m_bounding_rect = {};
        m_data.clear();
        return;
    }

    Gfx::IntRect new_bounding_rect(
        leftmost,
        topmost,
        rightmost - leftmost + 1,
        bottommost - topmost + 1);

    *this = with_bounding_rect(new_bounding_rect);
}

void Mask::invert()
{
    for_each_pixel([&](int x, int y) {
        set(x, y, 0xFF - get(x, y));
    });
}

void Mask::add(Mask const& other)
{
    combine(other, [](int a, int b) { return a + b; });
}

void Mask::subtract(Mask const& other)
{
    combine(other, [](int a, int b) { return a - b; });
}

void Mask::intersect(Mask const& other)
{
    combinef(other, [](float a, float b) { return a * b; });
}

}