summaryrefslogtreecommitdiffhomepage
path: root/crop-tool/crop-tool.cpp
blob: 0e92946b54cb9581e21256de96bc5bc4fe88f5dd (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
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
#include "../defs.hpp"
#include "serialize.hpp"
#include <Corrade/Utility/Arguments.h>
#include <Corrade/Utility/Debug.h>
#include <Corrade/Utility/DebugStl.h>
#include <opencv2/core/mat.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <optional>
#include <tuple>
#include <filesystem>
#include <algorithm>
#include <utility>
#include <cstring>
#include <cmath>

#undef MIN
#undef MAX

#ifdef _WIN32
#   define EX_OK        0   /* successful termination */
#   define EX_USAGE     64  /* command line usage error */
#   define EX_DATAERR   65  /* data format error */
#   define EX_SOFTWARE  70  /* internal software error */
#   define EX_CANTCREAT 73  /* can't create (user) output file */
#   define EX_IOERR     74  /* input/output error */
#else
#   include <sysexits.h>
#endif

struct file
{
    cv::Mat4b mat;
    Magnum::Vector2i ground_offset;
};

using Corrade::Utility::Error;
using Corrade::Utility::Debug;

static struct options_ {
    std::optional<unsigned> width, height;
    std::optional<double> scale;
} options;

using std::filesystem::path;

static
std::tuple<cv::Vec2i, cv::Vec2i, bool>
find_image_bounds(const path& path, const cv::Mat4b& mat)
{
    cv::Vec2i start{mat.cols, mat.rows}, end{0, 0};
    for (int y = 0; y < mat.rows; y++)
    {
        const auto* ptr = mat.ptr<cv::Vec4b>(y);
        for (int x = 0; x < mat.cols; x++)
        {
            enum {R, G, B, A};
            cv::Vec4b px = ptr[x];
            if (px[A] != 0)
            {
                start[0] = std::min(x, start[0]);
                start[1] = std::min(y, start[1]);
                end[0] = std::max(x+1, end[0]);
                end[1] = std::max(y+1, end[1]);
            }
        }
    }
    if (start[0] >= end[0] || start[1] >= end[1])
    {
        Error{} << "image" << path << "contains only fully transparent pixels!";
        return {{}, {}, false};
    }

    return {start, end, true};
}

static bool load_file(anim_group& group, const path& filename, const path& output_filename)
{
    auto mat = progn(
        cv::Mat mat_ = cv::imread(filename.string(), cv::IMREAD_UNCHANGED);
        if (mat_.empty() || mat_.type() != CV_8UC4)
        {
            Error{} << "failed to load" << filename << "as RGBA32 image";
            return cv::Mat4b{};
        }
        return cv::Mat4b(std::move(mat_));
    );

    if (mat.empty())
        return false;

    auto [start, end, bounds_ok] = find_image_bounds(filename, mat);

    if (!bounds_ok)
        return {};

    cv::Size size{end - start}, dest_size;

    if (!options.scale)
    {
        if (options.width)
            options.scale = (double)*options.width / size.width;
        else if (options.height)
            options.scale = (double)*options.height / size.height;
        else
            std::abort();
    }

    dest_size = {(int)std::round(*options.scale * size.width),
                 (int)std::round(*options.scale * size.height)};

    if (size.width < dest_size.width || size.height < dest_size.height)
    {
        Error{} << "refusing to upscale image" << filename;
        return {};
    }

    cv::Mat4b resized{size};
    cv::resize(mat({start, size}), resized, dest_size, 0, 0, cv::INTER_LANCZOS4);
    if (!cv::imwrite(output_filename.string(), resized))
    {
        Error{} << "failed writing image" << output_filename;
        return false;
    }
    Magnum::Vector2i ground = {
        (int)std::round((group.ground[0] - start[0]) * *options.scale),
        (int)std::round((group.ground[1] - start[1]) * *options.scale),
    };
    group.frames.push_back({ground});
    return true;
}

static bool load_directory(anim_group& group, const path& dirname, const path& output_dir)
{
    if (std::error_code ec{}; !std::filesystem::exists(dirname / ".", ec))
    {
        Error{} << "can't open directory" << dirname << ':' << ec.message();
        return {};
    }

    int i;
    for (i = 1; i <= 9999; i++)
    {
        char buf[9];
        sprintf(buf, "%04d.png", i);
        if (!std::filesystem::exists(dirname/buf))
            break;
        if (!load_file(group, dirname/buf, output_dir/buf))
            return false;
    }

    if (i == 1)
    {
        Error{} << "no files in anim group directory" << dirname;
        return false;
    }

    return true;
}

int main(int argc, char** argv)
{
    Corrade::Utility::Arguments args{};
#ifdef _WIN32
    if (auto* c = strrchr(argv[0], '\\'); c && c[1])
    {
        if (auto* s = strrchr(c, '.'); s && !strcmp(".exe", s))
            *s = '\0';
        args.setCommand(c+1);
    }
#else
    if (auto* c = strrchr(argv[0], '/'); c && c[1])
        args.setCommand(c+1);
#endif
    args.addOption('o', "output", "./output")
        .addArgument("directory")
        .addOption('W', "width", "")
        .addOption('H', "height", "");
    args.parse(argc, argv);
    const path output_dir = args.value<std::string>("output");
    const path input_dir = args.value<std::string>("directory");
    auto anim_info = anim::from_json(input_dir / "atlas.json");
    //std::vector<dir> dirs; dirs.reserve((std::size_t)anim_direction::COUNT);

    if (!anim_info)
        goto usage;

    if (unsigned w = args.value<unsigned>("width"); w != 0)
        options.width = w;
    if (unsigned h = args.value<unsigned>("height"); h != 0)
        options.height = h;
    if (!(!options.width ^ !options.height))
    {
        Error{} << "exactly one of --width, --height must be given";
        goto usage;
    }

    try {
        std::filesystem::create_directory(output_dir);
    } catch (const std::filesystem::filesystem_error& error) {
        Error{} << "failed to create output directory" << output_dir << ':' << error.what();
        return EX_CANTCREAT;
    }

    for (std::size_t i = 0; i < (std::size_t)anim_direction::COUNT; i++)
    {
        auto group_name = anim_group::direction_to_string((anim_direction)i);
        try {
            std::filesystem::remove_all(output_dir/group_name);
            std::filesystem::create_directory(output_dir/group_name);
        } catch (const std::filesystem::filesystem_error& e) {
            Error{} << "failed creating output directory" << group_name << ':' << e.what();
            return EX_CANTCREAT;
        }
        auto& group = anim_info->groups[i];
        group.frames.clear(); group.frames.reserve(64);
        if (!load_directory(group, input_dir/group_name, input_dir/group_name))
            return EX_DATAERR;
        if (!anim_info->to_json(output_dir/"atlas.json"))
            return EX_CANTCREAT;
    }

    return 0;

usage:
    Error{Error::Flag::NoNewlineAtTheEnd} << Corrade::Containers::StringView{args.usage()};
    return EX_USAGE;
}