summaryrefslogtreecommitdiff
path: root/src/pixels.cpp
blob: fcdfac7048642907067879aea8c7633075de9620 (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
#include "pixels.h"

#include <execution>
#include <filesystem>
#include <fstream>
#include <iostream>

Pixels& Pixels::operator+=(
    const Pixels& other)
{
    std::transform(std::execution::par,
                   pixels.begin(),
                   pixels.end(),
                   other.pixels.begin(),
                   pixels.begin(),
                   // [](auto& toAdd) { return dst += src; });
                   std::plus<>());

    return *this;
}

Pixels& Pixels::operator/=(
    const float divider)
{
    std::for_each(std::execution::par_unseq,
                  pixels.begin(),
                  pixels.end(),
                  [divider](auto& pixel) { pixel /= divider; });

    return *this;
}

std::optional<Pixels> Pixels::load(
    const QString& filename)
{
    const std::filesystem::path filepath{filename.toStdString()};

    if (!std::filesystem::exists(filepath)) {
        std::cerr << "no such file: " << filepath << std::endl;

        return {};
    }

    std::ifstream ifs(filepath, std::ios::in | std::ios::binary);

    if (!ifs)
        return {};

    Pixels result;
    ifs.read(reinterpret_cast<char*>(&result), sizeof(Pixels));
    ifs.close();

    if (!ifs) {
        std::cerr << "cannot read " << filepath << std::endl;

        return {};
    }

    return result;
}

bool Pixels::save(
    const QString& filename)
{
    const std::filesystem::path filepath{filename.toStdString()};
    const auto parent_path = filepath.parent_path();

    if (!std::filesystem::exists(parent_path)
        && !std::filesystem::create_directories(parent_path)) {
        std::cerr << "cannot create parent directory for file " << filepath
                  << std::endl;

        return false;
    }

    std::ofstream ofs(filepath, std::ios::out | std::ios::binary);

    if (!ofs)
        return false;

    ofs.write(reinterpret_cast<const char*>(this), sizeof(Pixels));
    ofs.close();

    if (!ofs) {
        std::cerr << "cannot write " << filepath << std::endl;

        return false;
    }

    return true;
}

Pixels::operator bool() const
{
    bool result = std::find_if(pixels.cbegin(),
                               pixels.cend(),
                               [](const auto& p) {
                                   return !qFuzzyIsNull(p) && !std::isnan(p);
                               })
                  != pixels.cend();
    // std::cout << __func__ << ":\t" << (result ? "true" : "false") << std::endl;
    return result;
}