diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0125442..bf28c57 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -126,8 +126,10 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - **image** + - codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): - codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). + - codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, - codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, - codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index bef9ca8..dd1c74b 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -40,6 +40,7 @@ | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `tests/gen/wad` (cut down from the nix freedoom package at fixture time, not committed) | Freedoom 0.13 (freedoom.github.io) | BSD-3-Clause: [freedoom-COPYING.txt](freedoom-COPYING.txt) | | `src/Formats/codecs/compress/Explode.luau` (the PKWARE DCL code tables and bit order) | blast.c 1.3 (Mark Adler, zlib contrib) | zlib: [blast-LICENSE.txt](blast-LICENSE.txt) | +| `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/pillow-bcn-CC0.txt b/licenses/pillow-bcn-CC0.txt new file mode 100644 index 0000000..e47711c --- /dev/null +++ b/licenses/pillow-bcn-CC0.txt @@ -0,0 +1,134 @@ +Pillow src/libImaging/BcnDecode.c (https://github.com/python-pillow/Pillow), file header: + +/* + * The Python Imaging Library + * + * decoder for DXTn-compressed data + * + * Format documentation: + * https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt + * + * The contents of this file are in the public domain (CC0) + * Full text of the CC0 license: + * https://creativecommons.org/publicdomain/zero/1.0/ + */ + +The full CC0 1.0 text follows. + +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + + diff --git a/src/Formats/codecs/image/Bcn/Decode.luau b/src/Formats/codecs/image/Bcn/Decode.luau new file mode 100644 index 0000000..8b892d1 --- /dev/null +++ b/src/Formats/codecs/image/Bcn/Decode.luau @@ -0,0 +1,498 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's +-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where +-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit +-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate +-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte +-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +local Half = require("@formats/codecs/image/Half") + +local Decode = {} + +local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 +local pal = buffer.create(16) -- 4 rgba8 colours + +local function c565(c: number): (number, number, number) + local r = rshift(band(c, 0xF800), 8) + local g = rshift(band(c, 0x7E0), 3) + local b = lshift(band(c, 0x1F), 3) + return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) +end + +-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) + local c0, c1 = readu16(src, p), readu16(src, p + 2) + local r0, g0, b0 = c565(c0) + local r1, g1, b1 = c565(c1) + writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) + writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) + if c0 > c1 or fourColour then + writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000) + writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000) + else + writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000) + writeu32(pal, 12, 0) + end + local idx = readu32(src, p + 4) + for i = 0, 15 do + writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) + end +end + +-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals +local vals = table.create(8, 0) +local function ramp8(a0: number, a1: number) + vals[1], vals[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + vals[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + vals[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + vals[7], vals[8] = 0, 255 + end +end + +-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 +local function ramp8s(u0: number, u1: number) + local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) + local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) + vals[1], vals[2] = s0 + 128, s1 + 128 + if s0 > s1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 + end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 + end + vals[7], vals[8] = 1, 255 + end +end + +-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) +local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) + if signed then + ramp8s(readu8(src, p), readu8(src, p + 1)) + else + ramp8(readu8(src, p), readu8(src, p + 1)) + end + local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 + local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 + for i = 0, 15 do + local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7) + local v = vals[sel + 1] + local o = i * 4 + if spread then + writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) + else + writeu8(blk, o + channel, v) + end + end +end + +function Decode.bc1(src: buffer, p: number, blk: buffer) + colour(src, p, blk, false) +end + +function Decode.bc2(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + for i = 0, 15 do + local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) + writeu8(blk, i * 4 + 3, a * 17) + end +end + +function Decode.bc3(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + single(src, p, blk, 3, false, false) +end + +function Decode.bc4(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, false, true) +end + +function Decode.bc4s(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, true, true) +end + +local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) + for i = 0, 15 do + writeu32(blk, i * 4, 0xFF000000) + end + single(src, p, blk, 0, signed, false) + single(src, p + 8, blk, 1, signed, false) +end +function Decode.bc5(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, false) +end +function Decode.bc5s(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, true) +end + +-- ------------------------------------------------------------------------------------------------ BPTC tables +-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices +local SI2 = { + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, + 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, + 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +} +local SI3 = { + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, + 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, + 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, + 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +} +local AI0 = { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +} +local AI1 = { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +} +local AI2 = { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +} +local W2 = { [0] = 0, 21, 43, 64 } +local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } +local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } +local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } +Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS + +local function subset(ns: number, part: number, i: number): number + if ns == 2 then + return band(rshift(SI2[part + 1], i), 1) + elseif ns == 3 then + return band(rshift(SI3[part + 1], 2 * i), 3) + end + return 0 +end + +-- the 128-bit block as four u32 words: bits(at, n) for n <= 16 +local w0, w1, w2, w3 = 0, 0, 0, 0 +local function load(src: buffer, p: number) + w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) +end +local function word(i: number): number + return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 +end +local function bits(at: number, n: number): number + if n == 0 then + return 0 + end + local wi, sh = rshift(at, 5), band(at, 31) + local v = rshift(word(wi), sh) + if sh + n > 32 and wi < 3 then + v = bor(v, lshift(word(wi + 1), 32 - sh)) + end + return band(v, lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ BC7 +-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 +local MODES7 = { + { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, + { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, + { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, + { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, + { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, + { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, + { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, + { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, +} +local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) + +local function expand(v: number, n: number): number + v = band(lshift(v, 8 - n), 255) + return bor(v, rshift(v, n)) +end + +function Decode.bc7(src: buffer, p: number, blk: buffer) + local m0 = readu8(src, p) + if m0 == 0 then + buffer.fill(blk, 0, 0, 64) + return + end + load(src, p) + local mode = 0 + while band(m0, lshift(1, mode)) == 0 do + mode += 1 + end + local info = MODES7[mode + 1] + local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] + local bit = mode + 1 + local part = bits(bit, pb) + bit += pb + local rot = bits(bit, rb) + bit += rb + local sel = bits(bit, isb) + bit += isb + local nep = ns * 2 + for i = 1, nep do + er[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eg[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eb[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + if ab > 0 then + ea[i] = bits(bit, ab) + bit += ab + else + ea[i] = 255 + end + end + if epb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep do + local v = bits(bit, 1) + bit += 1 + er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v + if ab > 0 then + ea[i] = ea[i] * 2 + v + end + end + end + if spb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep, 2 do + local v = bits(bit, 1) + bit += 1 + for j = i, i + 1 do + er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v + if ab > 0 then + ea[j] = ea[j] * 2 + v + end + end + end + end + for i = 1, nep do + er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) + if ab > 0 then + ea[i] = expand(ea[i], ab) + end + end + local cw = WEIGHTS[ib] + local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw + local cbit = bit + local abit = cbit + 16 * ib - ns + local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1 + local a2 = if ns == 3 then AI2[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 2 + 1 + local n = ib + if i == 0 or i == a1 or i == a2 then + n -= 1 + end + local i0 = bits(cbit, n) + cbit += n + local wc, wa + if ab > 0 and ib2 > 0 then + local n2 = if i == 0 then ib2 - 1 else ib2 + local i1 = bits(abit, n2) + abit += n2 + if sel == 1 then + wc, wa = aw[i1], cw[i0] + else + wc, wa = cw[i0], aw[i1] + end + else + wc, wa = cw[i0], cw[i0] + end + local tc, ta = 64 - wc, 64 - wa + local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) + local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) + local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) + local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) + if rot == 1 then + r, a = a, r + elseif rot == 2 then + g, a = a, g + elseif rot == 3 then + b, a = a, b + end + writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end +end + +-- ------------------------------------------------------------------------------------------------ BC6H +-- ns, transformed, pb, epb, rb, gb, bb +local MODES6 = { + { 2, 1, 5, 10, 5, 5, 5 }, + { 2, 1, 5, 7, 6, 6, 6 }, + { 2, 1, 5, 11, 5, 4, 4 }, + { 2, 1, 5, 11, 4, 5, 4 }, + { 2, 1, 5, 11, 4, 4, 5 }, + { 2, 1, 5, 9, 5, 5, 5 }, + { 2, 1, 5, 8, 6, 5, 5 }, + { 2, 1, 5, 8, 5, 6, 5 }, + { 2, 1, 5, 8, 5, 5, 6 }, + { 2, 0, 5, 6, 6, 6, 6 }, + { 1, 0, 0, 10, 10, 10, 10 }, + { 1, 1, 0, 11, 9, 9, 9 }, + { 1, 1, 0, 12, 8, 8, 8 }, + { 1, 1, 0, 16, 4, 4, 4 }, +} +-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) +local PACK6 = { + { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, +} +local ep = table.create(12, 0) +local uq = table.create(12, 0) + +local function signExtend(v: number, n: number): number + v = band(v, lshift(1, n) - 1) + return if v >= lshift(1, n - 1) then v - lshift(1, n) else v +end + +local function unquantize(x: number, n: number, signed: boolean): number + if not signed then + if n >= 15 or x == 0 then + return x + elseif x == lshift(1, n) - 1 then + return 0xFFFF + end + return rshift(x * 32768 + 0x4000, n - 1) + end + if n >= 16 then + return x + end + local neg = x < 0 + if neg then + x = -x + end + if x ~= 0 then + if x >= lshift(1, n - 1) - 1 then + x = 0x7FFF + else + x = rshift(x * 32768 + 0x4000, n - 1) + end + end + return if neg then -x else x +end + +local function finish(v: number, signed: boolean): number + if signed then + if v < 0 then + return -HALF[(-v * 31) // 32] + end + return HALF[(v * 31) // 32] + end + return HALF[(v * 31) // 64] +end + +-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) +function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) + load(src, p) + local m = band(w0, 31) + local mode, bit, epbits, ib + local low = band(m, 3) + if low < 2 then + mode, bit, epbits, ib = low, 2, 75, 3 + elseif low == 2 then + mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 + else + mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 + end + if mode >= 14 then + for i = 0, 15 do + local o = i * 16 + writef32(blk, o, 0) + writef32(blk, o + 4, 0) + writef32(blk, o + 8, 0) + writef32(blk, o + 12, 1) + end + return + end + local info = MODES6[mode + 1] + local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] + local nep = if ns == 2 then 12 else 6 + for i = 1, 12 do + ep[i] = 0 + end + local pack = PACK6[mode + 1] + for i = 1, epbits do + local d = pack[i] + local e = rshift(d, 4) + 1 + ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) + end + bit += epbits + local part = bits(bit, pb) + bit += pb + local mask = lshift(1, epb) - 1 + if signed then + ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) + end + if signed or tr == 1 then + for i = 4, nep, 3 do + ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) + end + end + if tr == 1 then + for i = 4, nep, 3 do + for c = 0, 2 do + local v = band(ep[i + c] + ep[1 + c], mask) + ep[i + c] = if signed then signExtend(v, epb) else v + end + end + end + for i = 1, nep do + uq[i] = unquantize(ep[i], epb, signed) + end + local w = WEIGHTS[ib] + local a1 = if ns == 2 then AI0[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 6 + 1 + local n = if i == 0 or i == a1 then ib - 1 else ib + local wt = w[bits(bit, n)] + bit += n + local t = 64 - wt + local o = i * 16 + -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would + writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed)) + writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed)) + writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed)) + writef32(blk, o + 12, 1) + end +end + +return Decode diff --git a/src/Formats/codecs/image/Bcn/Encode.luau b/src/Formats/codecs/image/Bcn/Encode.luau new file mode 100644 index 0000000..2aea052 --- /dev/null +++ b/src/Formats/codecs/image/Bcn/Encode.luau @@ -0,0 +1,442 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in formats-luau; the approach follows stb_dxt by +-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the +-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping +-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as +-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +local Encode = {} + +local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +local function exp5(v: number): number + return bor(lshift(v, 3), rshift(v, 2)) +end +local function exp6(v: number): number + return bor(lshift(v, 2), rshift(v, 4)) +end + +-- ------------------------------------------------------------------------------------------------ single colours +-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) +-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit +local OM: { { number } }? = nil +local function singleTables(): { { number } } + local om = OM + if om then + return om + end + local t: { { number } } = {} + for k = 1, 4 do + local bitsN = if k <= 2 then 5 else 6 + local maxq = lshift(1, bitsN) - 1 + local exp: (number) -> number = if bitsN == 5 then exp5 else exp6 + local best = table.create(256, 1e9) + local pick = table.create(256, 0) + for a = 0, maxq do + local ea = exp(a) + for b = 0, maxq do + local eb = exp(b) + local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2 + -- prefer endpoints close to each other (less error if the colour shifts) + local e = math.abs(ea - eb) * 0.01 + for target = math.max(0, v - 8), math.min(255, v + 8) do + local err = (target - v) ^ 2 + e + if err < best[target + 1] then + best[target + 1] = err + pick[target + 1] = a * 256 + b + end + end + end + end + t[k] = pick + end + OM = t + return t +end + +-- ------------------------------------------------------------------------------------------------ BC1 colour +local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) +local USE = table.create(16, true) +local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) +local IDX = table.create(16, 0) +local BEST = table.create(16, 0) + +local function palette(c0: number, c1: number, four: boolean) + local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) + local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) + PR[1], PG[1], PB[1] = r0, g0, b0 + PR[2], PG[2], PB[2] = r1, g1, b1 + if four then + PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3 + PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3 + else + PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2 + PR[4], PG[4], PB[4] = 0, 0, 0 + end +end + +-- indices for the palette into IDX (0-based); returns the squared error of the used pixels +local function assign(four: boolean): number + local n = if four then 4 else 3 + local total = 0 + for i = 1, 16 do + if USE[i] then + local r, g, b = R[i], G[i], B[i] + local bi, be = 0, math.huge + for k = 1, n do + local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] + local e = dr * dr + dg * dg + db * db + if e < be then + be, bi = e, k - 1 + end + end + IDX[i] = bi + total += be + else + IDX[i] = 3 + end + end + return total +end + +local function q565(r: number, g: number, b: number): number + local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) + local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) + local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) + return qr * 2048 + qg * 32 + qb +end + +-- the endpoint weights of index k (the e0 share) +local W4 = { 1, 0, 2 / 3, 1 / 3 } +local W3 = { 1, 0, 0.5, 0 } + +-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate +local function refine(four: boolean): (number?, number?) + local W = if four then W4 else W3 + local aa, bb, ab = 0, 0, 0 + local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + local w = W[IDX[i] + 1] + local v = 1 - w + aa += w * w + bb += v * v + ab += w * v + ar += w * R[i] + ag += w * G[i] + ab_ += w * B[i] + br += v * R[i] + bg += v * G[i] + bb_ += v * B[i] + end + end + local det = aa * bb - ab * ab + if math.abs(det) < 1e-9 then + return nil, nil + end + local f = 1 / det + local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f + local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f + return q565(r0, g0, b0), q565(r1, g1, b1) +end + +-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode +-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels +local function colourBlock(out: buffer, o: number, four: boolean) + local n, mr, mg, mb = 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + n += 1 + mr += R[i] + mg += G[i] + mb += B[i] + end + end + if n == 0 then + writeu16(out, o, 0) + writeu16(out, o + 2, 0) + writeu32(out, o + 4, 0xFFFFFFFF) + return + end + mr, mg, mb = mr / n, mg / n, mb / n + local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 + local same = true + local fr, fg, fb = -1, -1, -1 + for i = 1, 16 do + if USE[i] then + if fr < 0 then + fr, fg, fb = R[i], G[i], B[i] + elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then + same = false + end + local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb + crr += dr * dr + cgg += dg * dg + cbb += db * db + crg += dr * dg + crb += dr * db + cgb += dg * db + end + end + local c0, c1 + if same then + local t = singleTables() + local k = if four then 0 else 1 + local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] + c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) + c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) + local i2 = 2 + if c0 == c1 then + i2 = 0 + end + -- index 2 everywhere (or 0 for an exact endpoint); order fixed below + for i = 1, 16 do + IDX[i] = if USE[i] then i2 else 3 + end + else + -- principal axis + local vr, vg, vb = 1, 1, 1 + for _ = 1, 8 do + local nr = crr * vr + crg * vg + crb * vb + local ng = crg * vr + cgg * vg + cgb * vb + local nb = crb * vr + cgb * vg + cbb * vb + local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) + if m < 1e-9 then + break + end + vr, vg, vb = nr / m, ng / m, nb / m + end + local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 + for i = 1, 16 do + if USE[i] then + local d = R[i] * vr + G[i] * vg + B[i] * vb + if d < lo then + lo, li = d, i + end + if d > hi then + hi, hi_ = d, i + end + end + end + c0 = q565(R[hi_], G[hi_], B[hi_]) + c1 = q565(R[li], G[li], B[li]) + palette(c0, c1, four) + local err = assign(four) + for i = 1, 16 do + BEST[i] = IDX[i] + end + for _ = 1, 2 do + local n0, n1 = refine(four) + if not n0 or not n1 then + break + end + palette(n0, n1, four) + local e2 = assign(four) + if e2 < err then + err, c0, c1 = e2, n0, n1 + for i = 1, 16 do + BEST[i] = IDX[i] + end + else + break + end + end + for i = 1, 16 do + IDX[i] = BEST[i] + end + end + -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 + if four then + if c0 < c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2 + end + elseif c0 == c1 then + for i = 1, 16 do + IDX[i] = 0 + end + end + elseif c0 > c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v + end + end + writeu16(out, o, c0) + writeu16(out, o + 2, c1) + local bitsv = 0 + for i = 16, 1, -1 do + bitsv = bitsv * 4 + IDX[i] + end + writeu32(out, o + 4, bitsv) +end + +-- ------------------------------------------------------------------------------------------------ BC4 channel +local V = table.create(16, 0) +local RAMP = table.create(8, 0) +local SEL = table.create(16, 0) +local SELB = table.create(16, 0) + +local function ramp(a0: number, a1: number) + RAMP[1], RAMP[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + RAMP[7], RAMP[8] = 0, 255 + end +end + +local function pick(): number + local total = 0 + for i = 1, 16 do + local v = V[i] + local bi, be = 0, math.huge + for k = 1, 8 do + local d = v - RAMP[k] + local e = d * d + if e < be then + be, bi = e, k - 1 + end + end + SEL[i] = bi + total += be + end + return total +end + +-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] +local function channelBlock(out: buffer, o: number) + local lo, hi = 255, 0 + local lo2, hi2 = 255, 0 + for i = 1, 16 do + local v = V[i] + lo, hi = math.min(lo, v), math.max(hi, v) + if v > 0 and v < 255 then + lo2, hi2 = math.min(lo2, v), math.max(hi2, v) + end + end + local a0, a1 + if lo == hi then + a0, a1 = lo, lo + ramp(a0, a1) + pick() + else + -- 8-value ramp, then a few nudged endpoints + local bestErr, b0, b1 = math.huge, hi, lo + for d0 = 0, 2 do + for d1 = 0, 2 do + local x0, x1 = hi - d0, lo + d1 + if x0 > x1 then + ramp(x0, x1) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, x0, x1 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + end + end + end + -- 6-value ramp with the 0 / 255 extremes + if lo2 > hi2 then + lo2, hi2 = lo, lo + end + ramp(lo2, hi2) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, lo2, hi2 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + a0, a1 = b0, b1 + for i = 1, 16 do + SEL[i] = SELB[i] + end + end + writeu8(out, o, a0) + writeu8(out, o + 1, a1) + local lo24, hi24 = 0, 0 + for i = 8, 1, -1 do + lo24 = lo24 * 8 + SEL[i] + hi24 = hi24 * 8 + SEL[i + 8] + end + writeu8(out, o + 2, band(lo24, 255)) + writeu8(out, o + 3, band(rshift(lo24, 8), 255)) + writeu8(out, o + 4, rshift(lo24, 16)) + writeu8(out, o + 5, band(hi24, 255)) + writeu8(out, o + 6, band(rshift(hi24, 8), 255)) + writeu8(out, o + 7, rshift(hi24, 16)) +end + +-- ------------------------------------------------------------------------------------------------ whole images +-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) +local function gather(px: buffer, w: number, h: number, bx: number, by: number) + for y = 0, 3 do + local sy = math.min(by * 4 + y, h - 1) + for x = 0, 3 do + local sx = math.min(bx * 4 + x, w - 1) + local s = (sy * w + sx) * 4 + local i = y * 4 + x + 1 + R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) + end + end +end + +-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) +function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 + local out = buffer.create(bw * bh * bytes) + local o = 0 + for by = 0, bh - 1 do + for bx = 0, bw - 1 do + gather(px, w, h, bx, by) + if kind == "bc1" then + local any = false + for i = 1, 16 do + local u = A[i] >= threshold + USE[i] = u + any = any or not u + end + colourBlock(out, o, not any) + elseif kind == "bc3" then + for i = 1, 16 do + USE[i] = true + V[i] = A[i] + end + channelBlock(out, o) + colourBlock(out, o + 8, true) + elseif kind == "bc4" then + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + else + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + for i = 1, 16 do + V[i] = G[i] + end + channelBlock(out, o + 8) + end + o += bytes + end + end + return out +end + +return Encode diff --git a/src/Formats/codecs/image/Bcn/init.luau b/src/Formats/codecs/image/Bcn/init.luau new file mode 100644 index 0000000..c0bd23b --- /dev/null +++ b/src/Formats/codecs/image/Bcn/init.luau @@ -0,0 +1,121 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): +-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, +-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). +-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. +-- +-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) +-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) +-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) +-- +-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by +-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below +-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +local Decode = require("@formats/codecs/image/Bcn/Decode") +local Encode = require("@formats/codecs/image/Bcn/Encode") + +local Bcn = {} + +-- kind -> bytes per 4x4 block +Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } +-- kinds that decode to rgbaf32 +Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { + bc1 = Decode.bc1, + bc2 = Decode.bc2, + bc3 = Decode.bc3, + bc4 = Decode.bc4, + bc4s = Decode.bc4s, + bc5 = Decode.bc5, + bc5s = Decode.bc5s, + bc7 = Decode.bc7, + bc6h = function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, false) + end, + bc6hs = function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, true) + end, +} + +-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) +function Bcn.size(kind: string, w: number, h: number): number? + local b = Bcn.BLOCK[kind] + if not b then + return nil + end + return ((w + 3) // 4) * ((h + 3) // 4) * b +end + +-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. +-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. +function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) + local fn = BLOCKS[kind] + if not fn then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Bcn.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local float = Bcn.FLOAT[kind] == true + local bpp = if float then 16 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local bytes = Bcn.BLOCK[kind] + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + fn(src, p, blk) + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + if cols == 4 and not float then + for y = 0, rows - 1 do + local d, s = base + y * rowBytes, y * 16 + writeu32(dst, d, readu32(blk, s)) + writeu32(dst, d + 4, readu32(blk, s + 4)) + writeu32(dst, d + 8, readu32(blk, s + 8)) + writeu32(dst, d + 12, readu32(blk, s + 12)) + end + else + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + end + return dst, nil +end + +export type EncodeOptions = { + alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque) +} + +-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. +function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) + if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then + return nil, "unsupported: no encoder for " .. tostring(kind) + end + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then + return nil, "needs w x h rgba8 pixels" + end + local t = opts and opts.alphaThreshold or 128 + return Encode.run(kind, px, w, h, t), nil +end + +return Bcn diff --git a/src/Formats/codecs/image/Half.luau b/src/Formats/codecs/image/Half.luau new file mode 100644 index 0000000..f32e49a --- /dev/null +++ b/src/Formats/codecs/image/Half.luau @@ -0,0 +1,74 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, +-- OpenEXR HALF channels). New in formats-luau. Never throws. +-- +-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) +-- local f = Half.toFloat(h) -- the same, computed +-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +local Half = {} + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +-- toFloat(h) -> number (h a 16-bit pattern) +local function toFloat(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = band(rshift(h, 10), 31) + local m = band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1024 + m) * 2 ^ (e - 25) +end +Half.toFloat = toFloat + +local TABLE: { [number]: number } = table.create(65536, 0) +for h = 0, 65535 do + TABLE[h] = toFloat(h) +end +Half.TABLE = TABLE + +local scratch = buffer.create(4) + +-- fromFloat(f) -> the nearest half bit pattern (ties to even) +function Half.fromFloat(f: number): number + if f ~= f then + return 0x7E00 + end + buffer.writef32(scratch, 0, f) + local x = buffer.readu32(scratch, 0) + local sign = band(rshift(x, 16), 0x8000) + local e = band(rshift(x, 23), 0xFF) + local m = band(x, 0x7FFFFF) + if e == 255 then + return bor(sign, 0x7C00) + end + local ne = e - 112 + if ne >= 31 then + return bor(sign, 0x7C00) + elseif ne <= 0 then + if ne < -10 then + return sign + end + m = bor(m, 0x800000) + local shift = 14 - ne + local hm = rshift(m, shift) + local rem = band(m, lshift(1, shift) - 1) + local halfway = lshift(1, shift - 1) + if rem > halfway or (rem == halfway and band(hm, 1) == 1) then + hm += 1 + end + return sign + hm + end + local hm = rshift(m, 13) + local rem = band(m, 0x1FFF) + if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then + hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should + end + return sign + ne * 1024 + hm +end + +return Half diff --git a/tests/codecs/bcn.luau b/tests/codecs/bcn.luau new file mode 100644 index 0000000..15a1dc6 --- /dev/null +++ b/tests/codecs/bcn.luau @@ -0,0 +1,241 @@ +-- codecs/image/Bcn tests: random BC1..BC7 blocks (every BC7 and BC6H mode, the BC1 3-colour mode, odd sizes) against +-- Pillow's and Godot's (bcdec) decodes; BC6H floats against Godot; the encoders (BC1 / BC3 / BC4 / BC5) within reach +-- of Pillow's encoder PSNR, exact on flat blocks; argument errors; the fuzz no-throw pass. Fixtures: tools/fixtures/bcn.py. +local T = require("@tests/T") +local Bcn = require("@formats/codecs/image/Bcn") +local Half = require("@formats/codecs/image/Half") +local Fx = require("@tests/gen/bcn") + +local t = T.suite("bcn") + +-- the largest per-byte difference between two rgba8 buffers (channels: which of r, g, b, a count) +local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number) + local worst, at = 0, -1 + for i = 0, n - 1 do + for _, c in channels do + local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c)) + if d > worst then + worst, at = d, i + end + end + end + return worst, at +end + +local RGBA, RGB, RG, R = { 0, 1, 2, 3 }, { 0, 1, 2 }, { 0, 1 }, { 0 } +-- which channels each reference defines, and the allowed difference to it +local PILLOW: { [string]: { any } } = { + bc1 = { RGBA, 0 }, + bc2 = { RGBA, 0 }, + bc3 = { RGBA, 0 }, + bc4 = { RGB, 0 }, + bc5 = { RG, 0 }, + bc5s = { RG, 1 }, -- Pillow interpolates the biased unsigned values with truncation + bc7 = { RGBA, 0 }, +} + +local stats = { pillow = 0, godot = 0 } +for _, c in Fx.cases do + local src = buffer.fromstring(c.data) + local px, err = Bcn.decode(c.kind, src, 0, c.w, c.h) + t:check(px, c.name .. ": " .. tostring(err)) + local n = c.w * c.h + if Bcn.FLOAT[c.kind] then + t:eq(buffer.len(px), n * 16, c.name .. ": rgbaf32 size") + -- Godot (bcdec) floats: exact half values + local g = buffer.fromstring(c.godot) + local worst = 0 + for i = 0, n - 1 do + for ch = 0, 2 do + local a, b = buffer.readf32(px, i * 16 + ch * 4), buffer.readf32(g, i * 16 + ch * 4) + local d = math.abs(a - b) / math.max(math.abs(b), 1e-3) + worst = math.max(worst, d) + end + end + t:check(worst < 1e-3, string.format("%s: relative error %g against Godot", c.name, worst)) + stats.godot += 1 + -- Pillow: 8-bit truncation of the clamped float (and no rounding term in its interpolation): within 1. Its + -- signed BC6H differs from bcdec and the spec (negative endpoints), so only BC6H UF16 is compared. + local p = buffer.fromstring(c.pillow) + local w2 = 0 + for i = 0, n - 1 do + for ch = 0, 2 do + local v = math.clamp(buffer.readf32(px, i * 16 + ch * 4), 0, 1) + w2 = math.max(w2, math.abs(math.floor(v * 255) - buffer.readu8(p, i * 4 + ch))) + end + end + if c.kind == "bc6h" then + t:check(w2 <= 1, string.format("%s: %d off Pillow", c.name, w2)) + stats.pillow += 1 + end + else + t:eq(buffer.len(px), n * 4, c.name .. ": rgba8 size") + local ref = PILLOW[c.kind] + local d, at = maxDiff(px, buffer.fromstring(c.pillow), n, ref[1]) + t:check(d <= ref[2], string.format("%s: %d off Pillow at pixel %d", c.name, d, at)) + stats.pillow += 1 + if c.godot then + local chans = if c.kind == "bc4" then R elseif c.kind == "bc5" then RG else RGBA + local dg, atg = maxDiff(px, buffer.fromstring(c.godot), n, chans) + -- bcdec rounds some interpolated values where Pillow truncates: within 1 + t:check(dg <= 1, string.format("%s: %d off Godot at pixel %d", c.name, dg, atg)) + stats.godot += 1 + end + end + -- into a bigger buffer at an offset, from an offset + local big = buffer.create(buffer.len(src) + 5) + buffer.copy(big, 5, src) + local bpp = if Bcn.FLOAT[c.kind] then 16 else 4 + local out = buffer.create(n * bpp + 8) + local px2 = Bcn.decode(c.kind, big, 5, c.w, c.h, out, 8) + t:check(px2 == out and buffer.readstring(out, 8, n * bpp) == buffer.readstring(px, 0, n * bpp), c.name .. ": offsets") +end +t:note("%d block images decoded: %d Pillow, %d Godot comparisons", #Fx.cases, stats.pillow, stats.godot) + +-- BC4 SNORM = the red channel of BC5 SNORM +do + for _, c in Fx.cases do + if c.kind == "bc5s" then + local src = buffer.fromstring(c.data) + local nb = buffer.len(src) // 16 + local b4 = buffer.create(nb * 8) + for i = 0, nb - 1 do + buffer.copy(b4, i * 8, src, i * 16, 8) + end + local p4 = Bcn.decode("bc4s", b4, 0, c.w, c.h) :: buffer + local p5 = Bcn.decode("bc5s", src, 0, c.w, c.h) :: buffer + local ok = true + for i = 0, c.w * c.h - 1 do + ok = ok and buffer.readu8(p4, i * 4) == buffer.readu8(p5, i * 4) and buffer.readu8(p4, i * 4 + 1) == buffer.readu8(p5, i * 4) + end + t:check(ok, c.name .. ": bc4s = bc5s red") + end + end +end + +-- encoders +local function psnr(a: buffer, b: buffer, n: number, channels: { number }): number + local se = 0 + for i = 0, n - 1 do + for _, c in channels do + local d = buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c) + se += d * d + end + end + return if se == 0 then 99 else 10 * math.log10(255 * 255 * n * #channels / se) +end + +for _, e in Fx.enc do + local px = buffer.fromstring(e.rgba) + local n = e.w * e.h + for _, k in { { "bc1", RGB }, { "bc3", RGBA }, { "bc5", RG }, { "bc4", R } } do + local kind, ch = k[1], k[2] + local blocks, err = Bcn.encode(kind, px, e.w, e.h) + t:check(blocks, kind .. " encode: " .. tostring(err)) + t:eq(buffer.len(blocks), Bcn.size(kind, e.w, e.h), e.name .. " " .. kind .. ": size") + local back = Bcn.decode(kind, blocks, 0, e.w, e.h) :: buffer + local p = psnr(px, back, n, ch) + local base = e.psnr[kind] + if base then + t:check(p >= base - 0.5, string.format("%s %s: PSNR %.2f dB, Pillow %.2f dB", e.name, kind, p, base)) + t:note("%s %s: %.2f dB (Pillow %.2f dB)", e.name, kind, p, base) + else + t:check(p >= 35, string.format("%s %s: PSNR %.2f dB", e.name, kind, p)) + end + if kind == "bc1" then + -- the transparent pixels survive (3-colour mode) + local bad = 0 + for i = 0, n - 1 do + local a = buffer.readu8(px, i * 4 + 3) + if (a >= 128) ~= (buffer.readu8(back, i * 4 + 3) == 255) then + bad += 1 + end + end + t:eq(bad, 0, e.name .. " bc1: alpha mask") + end + end +end + +-- flat colours are exact through the single-colour tables (BC1 4-colour and 3-colour, BC4) +do + local rand = T.rng(3) + local worst = 0 + for _ = 1, 200 do + local r, g, b = rand(256), rand(256), rand(256) + local px = buffer.create(64) + for i = 0, 15 do + buffer.writeu32(px, i * 4, r + g * 256 + b * 65536 + (if i == 5 then 0 else 255) * 16777216) + end + for _, opaque in { true, false } do + if opaque then + buffer.writeu8(px, 23, 255) + else + buffer.writeu8(px, 23, 0) + end + local back = Bcn.decode("bc1", Bcn.encode("bc1", px, 4, 4) :: buffer, 0, 4, 4) :: buffer + for i = 0, 15 do + if opaque or i ~= 5 then + for c = 0, 2 do + worst = math.max(worst, math.abs(buffer.readu8(back, i * 4 + c) - buffer.readu8(px, i * 4 + c))) + end + end + end + end + end + -- 5 / 6-bit endpoints reach every 8-bit value within 1 (4-colour) / 2 (3-colour midpoints) + t:check(worst <= 2, "flat bc1 colours within " .. worst) + local px = buffer.create(64) + for v = 0, 255, 5 do + for i = 0, 15 do + buffer.writeu32(px, i * 4, v + 0xFF000000) + end + local back = Bcn.decode("bc4", Bcn.encode("bc4", px, 4, 4) :: buffer, 0, 4, 4) :: buffer + t:eq(buffer.readu8(back, 0), v, "flat bc4 " .. v) + end +end + +-- Half +do + t:eq(Half.fromFloat(1), 0x3C00, "half 1") + t:eq(Half.fromFloat(-2), 0xC000, "half -2") + t:eq(Half.fromFloat(65504), 0x7BFF, "half max") + t:eq(Half.fromFloat(1e6), 0x7C00, "half overflow") + t:eq(Half.fromFloat(2 ^ -24), 1, "half smallest subnormal") + t:eq(Half.fromFloat(0 / 0), 0x7E00, "half NaN") + local ok = true + for h = 0, 65535 do + local f = Half.TABLE[h] + if f == f and Half.fromFloat(f) ~= h and not (h == 0x8000) then + ok = false + end + end + t:check(ok, "half round trip of every pattern") +end + +-- errors +do + local _, e1 = Bcn.decode("bc9", buffer.create(8), 0, 4, 4) + t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind") + local _, e2 = Bcn.decode("bc1", buffer.create(7), 0, 4, 4) + t:check(e2 and string.find(e2, "truncated") ~= nil, "short data") + local _, e3 = Bcn.encode("bc7", buffer.create(64), 4, 4) + t:check(e3 ~= nil, "no bc7 encoder") + local _, e4 = Bcn.encode("bc1", buffer.create(10), 4, 4) + t:check(e4 ~= nil, "short pixels") +end + +-- fuzz: random block data of every kind and size +local samples = {} +for _, c in Fx.cases do + table.insert(samples, buffer.fromstring(c.data)) +end +for _, kind in { "bc1", "bc2", "bc3", "bc4", "bc4s", "bc5", "bc5s", "bc6h", "bc6hs", "bc7" } do + t:fuzz("decode " .. kind, function(b: buffer) + local n = buffer.len(b) // Bcn.BLOCK[kind] + if n < 1 then + return Bcn.decode(kind, b, 0, 4, 4) + end + return Bcn.decode(kind, b, 0, 4 * n - 1, 3) + end, samples, { mutations = 2 }) +end +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..5486408 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,27 @@ do jitTune(false) end end +do + -- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode) + -- or input (encode); BC6H of rgbaf32 output + local Bcn = require("@formats/codecs/image/Bcn") + local BB = require("@tests/gen/bcn_bench") + local w, h = BB.w, BB.h + local px = buffer.fromstring(BB.rgba) + for _, kind in { "bc1", "bc3", "bc5" } do + local blocks = Bcn.encode(kind, px, w, h) :: buffer + bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function() + Bcn.decode(kind, blocks, 0, w, h) + end) + bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function() + Bcn.encode(kind, px, w, h) + end) + end + local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h) + bench("bcn decode bc7 256x256", 5, w * h * 4, function() + Bcn.decode("bc7", b7, 0, w, h) + end) + bench("bcn decode bc6h 256x256", 5, w * h * 16, function() + Bcn.decode("bc6h", b6, 0, w, h) + end) +end diff --git a/tools/fixtures/_tex_reference.py b/tools/fixtures/_tex_reference.py new file mode 100644 index 0000000..af25edf --- /dev/null +++ b/tools/fixtures/_tex_reference.py @@ -0,0 +1,107 @@ +# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix. +# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is +# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian +# bytes when float is true +# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes) +# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data +import os, shutil, struct, tempfile + +# Godot Image.Format numbers (checked against Godot 4.7) +GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25, + "eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31, + "etc2_rgba1": 32} + +GD_SCRIPT = r'''extends SceneTree +func _init(): + var dir = OS.get_cmdline_user_args()[0] + var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false) + for line in lines: + var a = line.split(" ") + var data = FileAccess.get_file_as_bytes(dir + "/" + a[0]) + var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data) + img.decompress() + if a[4] == "1": + img.convert(Image.FORMAT_RGBAF) + else: + img.convert(Image.FORMAT_RGBA8) + var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE) + f.store_buffer(img.get_data()) + f.close() + quit() +''' + + +def godot(ctx, jobs): + work = tempfile.mkdtemp(prefix="formats-godot-") + try: + lines = [] + for i, (data, w, h, fmt, flt) in enumerate(jobs): + with open(os.path.join(work, "j%d" % i), "wb") as f: + f.write(data) + lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0)) + with open(os.path.join(work, "jobs.txt"), "w") as f: + f.write("\n".join(lines) + "\n") + with open(os.path.join(work, "run.gd"), "w") as f: + f.write(GD_SCRIPT) + ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work]) + out = [] + for i in range(len(jobs)): + with open(os.path.join(work, "j%d.out" % i), "rb") as f: + out.append(f.read()) + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + +def pillow(ctx, files): + """files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)""" + work = tempfile.mkdtemp(prefix="formats-pillow-") + try: + for i, data in enumerate(files): + with open(os.path.join(work, "f%d" % i), "wb") as f: + f.write(data) + code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n" + " im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n" + " open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n" + " open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files)) + ctx.python(["pillow"], code) + out = [] + for i in range(len(files)): + mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split() + out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read())) + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + +def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0): + if mips: + flags |= 0x20000 + return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf + + struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4) + + +def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0): + pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20 + return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data + + +def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0): + pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20 + return dds_header(w, h, pf, mips=mips, caps2=caps2) + data + + +def rgba_from(mode, raw): + """Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes""" + if mode == "RGBA": + return raw + out = bytearray() + if mode == "L": + for v in raw: + out += bytes((v, v, v, 255)) + elif mode == "RGB": + for i in range(0, len(raw), 3): + out += raw[i:i + 3] + b"\xff" + else: + raise ValueError(mode) + return bytes(out) diff --git a/tools/fixtures/bcn.py b/tools/fixtures/bcn.py new file mode 100644 index 0000000..aeb90b8 --- /dev/null +++ b/tools/fixtures/bcn.py @@ -0,0 +1,119 @@ +# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1 +# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder +# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them. +# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h, +# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H) +# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau +import importlib.util, math, os, random, struct + +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98} +BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16} +BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31] + + +def blocks(rng, kind, n, mode=None): + out = bytearray() + for _ in range(n): + b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind])) + if kind == "bc7" and mode is not None: + b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode) + elif kind.startswith("bc6h") and mode is not None: + bitsn = 2 if mode < 2 else 5 + b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode + out += b + return bytes(out) + + +def test_image(w, h, rng, alpha): + px = bytearray() + for y in range(h): + for x in range(w): + r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0)) + g = int(255 * x / (w - 1)) + b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40 + n = rng.randrange(-12, 13) + r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)] + a = 255 + if alpha: + a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255 + px += bytes((r, g, b, a)) + return bytes(px) + + +def psnr(a, b, channels): + se, n = 0, 0 + for i in range(0, len(a), 4): + for c in channels: + d = a[i + c] - b[i + c] + se += d * d + n += 1 + return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se) + + +def generate(ctx): + rng = random.Random(7) + cases = [] + + def add(name, kind, w, h, data): + cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data}) + + for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"): + add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64)) + add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8)) + for m in range(8): + add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m)) + add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12)) + for kind in ("bc6h", "bc6hs"): + for m in BC6_HEADERS: + add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m)) + # Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit) + files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases] + for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)): + c["pillow"] = R.rgba_from(mode, raw) + # Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats + gj, gi = [], [] + for i, c in enumerate(cases): + if c["kind"] in R.GODOT: + gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h"))) + gi.append(i) + for i, out in zip(gi, R.godot(ctx, gj)): + cases[i]["godot"] = out + + # encoder baselines: Pillow's encoder on the same images, decoded by Pillow + enc = [] + for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)): + px = test_image(w, h, rng, alpha) + e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}} + enc.append(e) + import tempfile, shutil + work = tempfile.mkdtemp(prefix="formats-bcn-") + try: + for i, e in enumerate(enc): + open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"]) + code = ("import os\nfrom PIL import Image\nw=%r\n" + "for i, (W, H) in enumerate(%r):\n" + " im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n" + " for pf in ('DXT1','DXT5','BC5'):\n" + " p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n" + " (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n" + " back=Image.open(p).convert('RGBA')\n" + " open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc]) + ctx.python(["pillow"], code) + for i, e in enumerate(enc): + for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))): + back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read() + e["psnr"][kind] = psnr(e["rgba"], back, ch) + finally: + shutil.rmtree(work, ignore_errors=True) + ctx.emit("bcn", {"cases": cases, "enc": enc}) + + # bench: a 512 x 512 image, and random BC7 blocks of every mode + w = h = 256 + px = test_image(w, h, rng, True) + bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)), + "bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)} + ctx.emit("bcn_bench", bench)