载入中...
搜索中...
未找到
SourcePng.cpp
浏览该文件的文档.
1#include "asset/SourcePng.h"
2#include <zlib.h>
3#include <algorithm>
4#include <array>
5#include <limits>
6#include <map>
7#include <string_view>
8#include "asset/SourceBc3.h"
9#include "asset/SourceTga.h"
10#include "asset/SourceTiff.h"
11
12// SourcePng.cpp
13namespace eve::asset::detail {
15 std::span<const std::uint8_t> pixels, std::uint64_t maximumBytes) {
16 auto fail = [] {
17 return Result<std::vector<std::uint8_t>>::failure(
18 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid PNG pixel dimensions or encoding budget", {},
19 {}, "asset.image.png"));
20 };
21 const std::uint64_t count = std::uint64_t(width) * height;
22 if (!width || !height || count > pixels.size() / 4 || count * 4 != pixels.size() ||
23 pixels.size() > std::numeric_limits<uLong>::max() - std::uint64_t(height))
24 return fail();
25 const std::uint64_t row = std::uint64_t(width) * 4, total = pixels.size() + std::uint64_t(height);
26 if (total > maximumBytes || total > std::numeric_limits<uLong>::max()) return fail();
27 uLongf bound = compressBound(static_cast<uLong>(total));
28 if (bound > maximumBytes || maximumBytes - bound < 57 || bound > UINT32_MAX - 4) return fail();
29 std::vector<std::uint8_t> scanlines;
30 scanlines.reserve(std::size_t(total));
31 for (std::size_t y = 0; y < height; ++y) {
32 scanlines.push_back(0);
33 scanlines.insert(scanlines.end(), pixels.begin() + y * row, pixels.begin() + (y + 1) * row);
34 }
35 std::vector<std::uint8_t> compressed(bound);
36 if (compress2(compressed.data(), &bound, scanlines.data(), static_cast<uLong>(total), 6) != Z_OK) return fail();
37 compressed.resize(bound);
38 std::vector<std::uint8_t> result{137, 80, 78, 71, 13, 10, 26, 10};
39 auto put = [](auto& out, std::uint32_t v) {
40 for (int shift = 24; shift >= 0; shift -= 8) out.push_back(std::uint8_t(v >> shift));
41 };
42 auto chunk = [&](const char* type, std::span<const std::uint8_t> payload) {
43 put(result, std::uint32_t(payload.size()));
44 const auto at = result.size();
45 result.insert(result.end(), type, type + 4);
46 result.insert(result.end(), payload.begin(), payload.end());
47 put(result, crc32(0, result.data() + at, static_cast<uInt>(payload.size() + 4)));
48 };
49 std::vector<std::uint8_t> header;
50 put(header, width);
51 put(header, height);
52 header.insert(header.end(), {8, 6, 0, 0, 0});
53 chunk("IHDR", header);
54 chunk("IDAT", compressed);
55 chunk("IEND", {});
56 return Result<std::vector<std::uint8_t>>::success(std::move(result));
57}
58} // namespace eve::asset::detail
59
60// SourceTga.cpp
61namespace eve::asset::detail {
62Result<TgaPixels> decodeTgaRgba8(std::span<const std::uint8_t> b, std::uint64_t budget) {
63 auto fail = [](DiagnosticCode code, const char* message) {
64 return Result<TgaPixels>::failure(Diagnostic::error(code, message, {}, {}, "asset.image.tga"));
65 };
66 if (b.size() < 18) return fail(DiagnosticCode::ParseError, "truncated TGA header");
67 auto u16 = [&](std::size_t p) { return std::uint32_t(b[p]) | (std::uint32_t(b[p + 1]) << 8); };
68 auto u32 = [&](std::size_t p) { return u16(p) | (u16(p + 2) << 16); };
69 const auto w = u16(12), h = u16(14);
70 const unsigned channels = b[16] / 8, attributes = b[17] & 15;
71 if (b[1] != 0 || (b[2] != 2 && b[2] != 10) || (b[16] != 24 && b[16] != 32) || (b[17] & 192) != 0 ||
72 (attributes != 0 && !(channels == 4 && attributes == 8)))
73 return fail(DiagnosticCode::Unsupported, "TGA requires non-interleaved 24/32-bit true-color raw or RLE pixels");
74 const std::uint64_t count = std::uint64_t(w) * h;
75 if (!w || !h || budget < 24 || count > (budget - 24) / 4)
76 return fail(DiagnosticCode::InvalidArgument, "TGA dimensions exceed decoded budget");
77 std::size_t end = b.size(), cursor = 18 + b[0];
78 constexpr std::string_view signature("TRUEVISION-XFILE.\0", 18);
79 if (b.size() >= 26 && std::equal(signature.begin(), signature.end(), b.end() - 18)) {
80 end = b.size() - 26;
81 const auto extension = u32(end), developer = u32(end + 4);
82 if (extension) {
83 if (extension < cursor || extension > end || end - extension < 495 || u16(extension) != 495)
84 return fail(DiagnosticCode::ParseError, "invalid TGA extension area");
85 if (b[extension + 494] > 3)
86 return fail(DiagnosticCode::Unsupported, "premultiplied or unknown TGA alpha semantics");
87 end = extension;
88 }
89 if (developer) {
90 if (developer < cursor || developer > b.size() - 26 || b.size() - 26 - developer < 2)
91 return fail(DiagnosticCode::ParseError, "invalid TGA developer area");
92 end = std::min(end, std::size_t(developer));
93 }
94 }
95 if (cursor > end) return fail(DiagnosticCode::ParseError, "truncated TGA image ID");
96 TgaPixels out{w, h, std::vector<std::uint8_t>(std::size_t(count) * 4)};
97 std::size_t written = 0;
98 auto pixel = [&](std::size_t p) {
99 const std::size_t x = written % w, y = written / w;
100 const auto dx = (b[17] & 16) ? w - 1 - x : x, dy = (b[17] & 32) ? y : h - 1 - y;
101 const auto dst = (dy * w + dx) * 4;
102 out.rgba[dst] = b[p + 2];
103 out.rgba[dst + 1] = b[p + 1];
104 out.rgba[dst + 2] = b[p];
105 out.rgba[dst + 3] = channels == 4 ? b[p + 3] : 255;
106 ++written;
107 };
108 while (written < count) {
109 std::size_t run = 1;
110 bool repeated = false;
111 if (b[2] == 10) {
112 if (cursor == end) return fail(DiagnosticCode::ParseError, "truncated TGA RLE packet");
113 auto header = b[cursor++];
114 run = (header & 127) + 1;
115 repeated = (header & 128) != 0;
116 }
117 if (run > count - written || (repeated ? channels : run * channels) > end - cursor)
118 return fail(DiagnosticCode::ParseError, "TGA packet exceeds image or source bounds");
119 for (std::size_t i = 0; i < run; ++i) pixel(cursor + (repeated ? 0 : i * channels));
120 cursor += (repeated ? 1 : run) * channels;
121 }
122 return Result<TgaPixels>::success(std::move(out));
123}
124} // namespace eve::asset::detail
125
126// SourceBc3.cpp
127namespace eve::asset::detail {
128Result<std::vector<std::uint8_t>> decodeBc3Rgba8(std::span<const std::uint8_t> bytes, std::uint32_t width,
129 std::uint32_t height, std::uint64_t maximumDecodedBytes) {
130 const auto pixels = std::uint64_t(width) * height;
131 const auto columns = (std::uint64_t(width) + 3) / 4;
132 const auto rows = (std::uint64_t(height) + 3) / 4;
133 if (!width || !height || pixels > maximumDecodedBytes / 4 || pixels > std::numeric_limits<std::size_t>::max() / 4 ||
134 columns * rows > std::numeric_limits<std::uint64_t>::max() / 16 || columns * rows * 16 != bytes.size())
135 return Result<std::vector<std::uint8_t>>::failure(
136 Diagnostic::error(DiagnosticCode::InvalidArgument, "BC3 dimensions, byte count or decoded budget invalid",
137 {}, {}, "asset.bc3"));
138 std::vector<std::uint8_t> output(std::size_t(pixels * 4));
139 for (std::uint64_t by = 0; by < rows; ++by) {
140 for (std::uint64_t bx = 0; bx < columns; ++bx) {
141 const auto block = bytes.subspan(std::size_t((by * columns + bx) * 16), 16);
142 std::array<unsigned, 8> alpha{block[0], block[1]};
143 if (alpha[0] > alpha[1]) {
144 for (unsigned i = 1; i <= 6; ++i) alpha[i + 1] = ((7 - i) * alpha[0] + i * alpha[1]) / 7;
145 } else {
146 for (unsigned i = 1; i <= 4; ++i) alpha[i + 1] = ((5 - i) * alpha[0] + i * alpha[1]) / 5;
147 alpha[6] = 0;
148 alpha[7] = 255;
149 }
150 std::array<std::array<unsigned, 3>, 4> color{};
151 for (unsigned i = 0; i < 2; ++i) {
152 const unsigned rgb = block[8 + i * 2] | (unsigned(block[9 + i * 2]) << 8);
153 const unsigned r = rgb >> 11, g = (rgb >> 5) & 63, b = rgb & 31;
154 color[i] = {(r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)};
155 }
156 for (unsigned c = 0; c < 3; ++c) {
157 color[2][c] = (2 * color[0][c] + color[1][c]) / 3;
158 color[3][c] = (color[0][c] + 2 * color[1][c]) / 3;
159 }
160 std::uint64_t alphaIndices = 0;
161 std::uint32_t colorIndices = 0;
162 for (unsigned i = 0; i < 6; ++i) alphaIndices |= std::uint64_t(block[2 + i]) << (8 * i);
163 for (unsigned i = 0; i < 4; ++i) colorIndices |= std::uint32_t(block[12 + i]) << (8 * i);
164 for (unsigned i = 0; i < 16; ++i) {
165 const auto x = bx * 4 + i % 4, y = by * 4 + i / 4;
166 if (x >= width || y >= height) continue;
167 const auto at = std::size_t((y * width + x) * 4);
168 for (unsigned c = 0; c < 3; ++c) output[at + c] = std::uint8_t(color[(colorIndices >> (2 * i)) & 3][c]);
169 output[at + 3] = std::uint8_t(alpha[(alphaIndices >> (3 * i)) & 7]);
170 }
171 }
172 }
173 return Result<std::vector<std::uint8_t>>::success(std::move(output));
174}
175} // namespace eve::asset::detail
176
177// SourceTiff.cpp
178namespace eve::asset::detail {
179namespace {
180struct Invalid {};
181struct Unsupported {};
182struct Reader {
183 std::span<const std::uint8_t> bytes;
184 bool little;
185 std::uint32_t read(std::size_t at, unsigned count) const {
186 if (at > bytes.size() || count > bytes.size() - at) throw Invalid{};
187 std::uint32_t result = 0;
188 for (unsigned i = 0; i < count; ++i)
189 result |= std::uint32_t(bytes[at + i]) << ((little ? i : count - 1 - i) * 8);
190 return result;
191 }
192};
193struct Tag {
194 std::uint32_t type, count, offset;
195};
196
197std::vector<std::uint8_t> lzw(std::span<const std::uint8_t> source, std::size_t expected) {
198 std::array<std::uint16_t, 4096> prefix{};
199 std::array<std::uint8_t, 4096> suffix{}, stack{};
200 std::vector<std::uint8_t> out;
201 out.reserve(expected);
202 std::size_t bit = 0;
203 unsigned width = 9, next = 258, previous = 4096;
204 std::uint8_t first = 0;
205 bool cleared = false;
206 while (true) {
207 if (bit > source.size() * 8 || width > source.size() * 8 - bit) throw Invalid{};
208 unsigned code = 0;
209 for (unsigned i = 0; i < width; ++i, ++bit) code = (code << 1) | ((source[bit / 8] >> (7 - bit % 8)) & 1);
210 if (code == 256) {
211 width = 9;
212 next = 258;
213 previous = 4096;
214 cleared = true;
215 continue;
216 }
217 if (!cleared) throw Invalid{};
218 if (code == 257) {
219 if (out.size() != expected) throw Invalid{};
220 return out;
221 }
222 const unsigned original = code;
223 std::size_t length = 0;
224 if (code == next && previous != 4096) {
225 stack[length++] = first;
226 code = previous;
227 } else if (code >= next)
228 throw Invalid{};
229 while (code >= 258) {
230 if (code >= next || length >= stack.size()) throw Invalid{};
231 stack[length++] = suffix[code];
232 code = prefix[code];
233 }
234 if (code >= 256 || length >= stack.size()) throw Invalid{};
235 first = std::uint8_t(code);
236 stack[length++] = first;
237 if (length > expected - out.size()) throw Invalid{};
238 while (length) out.push_back(stack[--length]);
239 if (previous != 4096 && next < 4096) {
240 prefix[next] = std::uint16_t(previous);
241 suffix[next] = first;
242 ++next;
243 // TIFF uses early-change code widths, unlike GIF's late-change LZW.
244 if (width < 12 && next == (1u << width) - 1) ++width;
245 }
246 previous = original;
247 }
248}
249} // namespace
250
251Result<TiffPixels> decodeTiffRgba8(std::span<const std::uint8_t> bytes, std::uint64_t maximumDecodedBytes) {
252 try {
253 if (bytes.size() < 8 || !((bytes[0] == 'I' && bytes[1] == 'I') || (bytes[0] == 'M' && bytes[1] == 'M')))
254 throw Invalid{};
255 Reader r{bytes, bytes[0] == 'I'};
256 if (r.read(2, 2) != 42) throw Unsupported{};
257 const auto ifd = r.read(4, 4), count = r.read(ifd, 2);
258 if (ifd < 8 || count > 4096 || std::uint64_t(ifd) + 2 + 12ull * count + 4 > bytes.size()) throw Invalid{};
259 std::map<unsigned, Tag> tags;
260 for (unsigned i = 0; i < count; ++i) {
261 const auto at = ifd + 2 + i * 12, id = r.read(at, 2), type = r.read(at + 2, 2), n = r.read(at + 4, 4);
262 unsigned size = type == 1 || type == 2 || type == 6 || type == 7 ? 1
263 : type == 3 || type == 8 ? 2
264 : type == 4 || type == 9 || type == 11 ? 4
265 : type == 5 || type == 10 || type == 12 ? 8
266 : 0;
267 if (!size) throw Unsupported{};
268 const auto offset = std::uint64_t(n) * size <= 4 ? at + 8 : r.read(at + 8, 4);
269 if (offset > bytes.size() || std::uint64_t(n) * size > bytes.size() - offset) throw Invalid{};
270 if (!tags.emplace(id, Tag{type, n, offset}).second) throw Invalid{};
271 }
272 if (r.read(ifd + 2 + 12 * count, 4) != 0) throw Unsupported{};
273 auto values = [&](unsigned id, std::vector<std::uint32_t> fallback = {}) {
274 const auto it = tags.find(id);
275 if (it == tags.end()) return fallback;
276 const auto& t = it->second;
277 if ((t.type != 3 && t.type != 4) || t.count > maximumDecodedBytes / 4) throw Invalid{};
278 std::vector<std::uint32_t> result;
279 result.reserve(t.count);
280 const auto step = t.type == 3 ? 2 : 4;
281 for (unsigned i = 0; i < t.count; ++i) result.push_back(r.read(t.offset + std::size_t(i) * step, step));
282 return result;
283 };
284 auto scalar = [&](unsigned id, unsigned fallback) {
285 auto v = values(id, {fallback});
286 if (v.size() != 1) throw Invalid{};
287 return v[0];
288 };
289 const auto w = scalar(256, 0), h = scalar(257, 0), channels = scalar(277, 1), compression = scalar(259, 1);
290 const auto rows = scalar(278, UINT32_MAX), orientation = scalar(274, 1), predictor = scalar(317, 1);
291 if (!w || !h || !rows || maximumDecodedBytes < 24 || std::uint64_t(w) * h > (maximumDecodedBytes - 24) / 4)
292 throw Invalid{};
293 if (scalar(262, 0) != 2 || scalar(284, 1) != 1 || (channels != 3 && channels != 4) || orientation < 1 ||
294 orientation > 4 || (predictor != 1 && predictor != 2) || scalar(266, 1) != 1)
295 throw Unsupported{};
296 auto bits = values(258), format = values(339, {1}), extra = values(338);
297 if (bits.size() != channels || (bits[0] != 8 && bits[0] != 16) ||
298 (format.size() != 1 && format.size() != channels) ||
299 !std::all_of(bits.begin(), bits.end(), [&](auto b) { return b == bits[0]; }) ||
300 !std::all_of(format.begin(), format.end(), [](auto f) { return f == 1; }))
301 throw Unsupported{};
302 if (channels == 4 && (extra.size() != 1 || (extra[0] != 0 && extra[0] != 2))) throw Unsupported{};
303 if (channels == 3 && !extra.empty()) throw Unsupported{};
304 if (compression != 1 && compression != 5 && compression != 8 && compression != 32946) throw Unsupported{};
305 auto offsets = values(273), sizes = values(279);
306 if (offsets.size() != (std::uint64_t(h) + rows - 1) / rows || sizes.size() != offsets.size()) throw Invalid{};
307 TiffPixels out{w, h, std::vector<std::uint8_t>(std::size_t(w) * h * 4)};
308 const unsigned sampleBytes = bits[0] / 8;
309 for (std::size_t strip = 0; strip < offsets.size(); ++strip) {
310 const auto start = strip * rows, lines = std::min<std::size_t>(rows, h - start);
311 const std::uint64_t decodedSize = std::uint64_t(w) * lines * channels * sampleBytes;
312 if (decodedSize > maximumDecodedBytes || decodedSize > std::numeric_limits<uLongf>::max() ||
313 offsets[strip] > bytes.size() || sizes[strip] > bytes.size() - offsets[strip])
314 throw Invalid{};
315 auto source = bytes.subspan(offsets[strip], sizes[strip]);
316 std::vector<std::uint8_t> raw;
317 if (compression == 1) {
318 if (source.size() != decodedSize) throw Invalid{};
319 raw.assign(source.begin(), source.end());
320 } else if (compression == 5)
321 raw = lzw(source, std::size_t(decodedSize));
322 else {
323 raw.resize(std::size_t(decodedSize));
324 uLongf length = static_cast<uLongf>(decodedSize);
325 uLong input = static_cast<uLong>(source.size());
326 if (uncompress2(raw.data(), &length, source.data(), &input) != Z_OK || length != decodedSize ||
327 input != source.size())
328 throw Invalid{};
329 }
330 Reader pixels{raw, r.little};
331 const auto rowSamples = std::size_t(w) * channels;
332 std::array<unsigned, 4> previous{};
333 for (std::size_t y = 0; y < lines; ++y) {
334 previous.fill(0);
335 for (std::size_t x = 0; x < w; ++x) {
336 const auto dstX = (orientation == 2 || orientation == 3) ? w - 1 - x : x;
337 const auto srcY = start + y, dstY = orientation >= 3 ? h - 1 - srcY : srcY;
338 const auto dst = (dstY * w + dstX) * 4;
339 for (unsigned c = 0; c < channels; ++c) {
340 auto v = pixels.read((y * rowSamples + x * channels + c) * sampleBytes, sampleBytes);
341 if (predictor == 2) v = (v + previous[c]) & (sampleBytes == 1 ? 255 : 65535);
342 previous[c] = v;
343 out.rgba[dst + c] = std::uint8_t(sampleBytes == 1 ? v : (v + 128) / 257);
344 }
345 if (channels == 3) out.rgba[dst + 3] = 255;
346 }
347 }
348 }
349 return Result<TiffPixels>::success(std::move(out));
350 } catch (const Unsupported&) {
353 "unsupported TIFF layout; requires unsigned 8/16-bit RGB(A) strips with raw, LZW or Deflate compression",
354 {}, {}, "asset.image.tiff"));
355 } catch (const Invalid&) {
357 DiagnosticCode::ParseError, "malformed TIFF or decoded image budget exceeded", {}, {}, "asset.image.tiff"));
358 }
359}
360} // namespace eve::asset::detail
double y
double x
Value::Object payload
Duration start
float w
Definition AnimClip.cpp:738
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string output
std::size_t cursor
glm::vec4 p[6]
double raw
std::uint64_t decodedSize
EvpackChunkInput input
Definition Evpack.cpp:170
int rows
std::string message
DiagnosticCode code
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
std::int32_t first
int h
std::uint32_t height
std::uint32_t width
float length
std::function< Numbers(b3JointId)> read
size_t offset
std::string id
Poco::JSON::Object::Ptr result
std::uint64_t bytes
std::unordered_set< std::string > tags
MeleePoint3 b
Definition MeleeHit.cpp:41
glm::dvec3 dx
std::shared_ptr< const OceanSprayFrame > previous
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
float f
std::set< std::string > values
float t
uint8_t * pixels
std::map< std::string, double > attributes
ScriptStructure out
std::string_view source
size_t end
float dy
Definition Shadow.cpp:151
bool little
int count
int columns
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
std::vector< std::string_view > lines
std::size_t at
double compression
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Result< std::vector< std::uint8_t > > encodeSourcePng(std::uint32_t width, std::uint32_t height, std::span< const std::uint8_t > pixels, std::uint64_t maximumBytes)
Encode top-down RGBA8 source pixels without transfer conversion.
Definition SourcePng.cpp:14
Result< TgaPixels > decodeTgaRgba8(std::span< const std::uint8_t > b, std::uint64_t budget)
Decode true-color 24/32-bit raw or RLE TGA with bounded allocation.
Definition SourcePng.cpp:62
Result< TiffPixels > decodeTiffRgba8(std::span< const std::uint8_t > bytes, std::uint64_t maximumDecodedBytes)
Decode bounded strip-based unsigned RGB TIFF (8/16 bits, raw/LZW/Deflate).
EVENGINE_API_FOUNDATION Result< std::vector< std::uint8_t > > decodeBc3Rgba8(std::span< const std::uint8_t > bytes, std::uint32_t width, std::uint32_t height, std::uint64_t maximumDecodedBytes)
Decode one BC3/DXT5 mip level into tightly packed RGBA8 in source row order.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Owning top-down RGBA8 pixels decoded from a TGA source.
Definition SourceTga.h:10
Owning top-down RGB(A) TIFF pixels; unspecified fourth samples remain alpha data.
Definition SourceTiff.h:10
glm::vec4 color