Algorithm Search⌘K

Algorithmcore

S3 texture compression

Also called S3TC, DXT1, BC1 compression.

Code each 4x4 block of texels in 64 bits, as two 16-bit endpoint colors and a 2-bit index per texel into the line between them, for 4 bits per texel and random access on the GPU.

Time
Θ(N) worst
Space
Θ(1) extra
Where
N = the number of texels of the image
Properties
deterministicnot in placeonlineiterative
Origin
Konstantine Iourcha, Krishna Nayak, Zhou Hong, 1997

S3 texture compression stores a color texture in fixed-size blocks that the GPU decodes as it samples. Each block of 4×44 \times 4 texels takes 64 bits: two endpoint colors of 16 bits, and a 2-bit index per texel that picks one of four colors on the line between the endpoints. So every texel costs 4 bits, and the GPU finds any texel at a fixed address. S3TC is a family of formats. This page covers its basic RGB format, which Direct3D names BC1, and mentions the formats with alpha as variants. Adaptive scalable texture compression is a later fixed-rate format with 128-bit blocks of many sizes, many color modes and a choice of bit rate. Both differ from general image codecs such as JPEG, which have a variable rate and cannot decode one texel without its neighbors.

In plain words

A small patch of a photo seldom holds many different colors. Most of the time the colors of a 4×44 \times 4 patch lie close to one straight line between a darker and a lighter color.

So, for each patch, store only the two end colors, in a short form of 16 bits each. Between them the decoder makes two more colors, one third and two thirds of the way along. Then for each of the 16 texels, store a number from 0 to 3 that says which of the four colors to use.

Every patch takes the same 8 bytes. The graphics card can jump straight to the patch it needs, read 8 bytes, and get the color of any texel in it.

The problem

The input is an image of W×HW \times H RGB texels, with WW and HH multiples of 4. The output is WH/16W H / 16 blocks of 64 bits. The decoder must be a fixed and cheap function of one block, so that the texture unit can sample a compressed texture at random places, with mipmaps and filtering. The encoder may be slow, because it runs once, offline. Its goal is a small error between the image and the decoded image.

A color word is RGB565: red in bits 15 to 11, green in bits 10 to 5 and blue in bits 4 to 0. The word ww stands for the color E(w)=(R/31,G/63,B/31)E(w) = (R/31, G/63, B/31). Green gets one more bit because the eye is most sensitive to it.

part of the block bits
color0, a little-endian RGB565 word 16
color1, a little-endian RGB565 word 16
16 indices of 2 bits, texel i=4y+xi = 4y + x in bits 2i2i and 2i+12i + 1 of a little-endian 32-bit word 32
total for 16 texels 64, so 4 bits per texel

Against 24-bit RGB this is a ratio of 6 to 1.

The algorithm

  1. BC1-DECODE(block)
  2. 1c0, c1 ← the first two 16-bit words; bits ← the last 32 bits
  3. 2C0, C1 ← E(c0), E(c1) ▷ expand RGB565
  4. 3if c0 > c1 then P ← (C0, C1, (2 C0 + C1)/3, (C0 + 2 C1)/3)
  5. 4else P ← (C0, C1, (C0 + C1)/2, transparent black)
  6. 5return texel i = P[(bits >> 2i) & 3] for i = 0..15
  7. BC1-ENCODE(16 colors)
  8. 6axis ← the principal axis of the colors ▷ power iteration on the covariance
  9. 7lo, hi ← the colors with the least and the greatest projection on the axis
  10. 8c0, c1 ← RGB565 of hi and lo, swapped so that c0 > c1 ▷ equal words: all indices 0
  11. 9for each texel pick the index of the nearest color of P
  12. 10return c0, c1 and the 16 indices packed

Decoding is lines L1 to L5, a fixed function of the block. The comparison of the two words in lines L3 and L4 is the trick of the format: the order of the endpoints, which costs no bits, picks one of two palettes. The four-color palette suits smooth blocks. The three-color palette has a transparent texel for cut-out textures such as leaves.

Encoding is a search over endpoints and indices, and lines L6 to L10 are one simple strategy, a range fit. It takes the axis of largest spread of the colors, as in principal component analysis computed by power iteration, and uses the two extreme colors along it. For fixed endpoints, line L9 picks the best index for every texel.

Example

Take a block in which every row holds the colors (0.8,0.4,0.1)(0.8, 0.4, 0.1), (0.7,0.4,0.2)(0.7, 0.4, 0.2), (0.6,0.4,0.3)(0.6, 0.4, 0.3) and (0.5,0.4,0.4)(0.5, 0.4, 0.4). They lie on a line, so the principal axis is the direction (1,0,−1)(1, 0, -1). The extremes are (0.8,0.4,0.1)(0.8, 0.4, 0.1) and (0.5,0.4,0.4)(0.5, 0.4, 0.4).

Rounding gives R=25R = 25, G=25G = 25, B=3B = 3 for the first, the word 0xCB23, and R=16R = 16, G=25G = 25, B=12B = 12 for the second, the word 0x832C. Since 0xCB23 > 0x832C, the palette has four colors:

index (R/31,G/63,B/31)(R/31, G/63, B/31) about
0 (25/31,25/63,3/31)(25/31, 25/63, 3/31) (0.806,0.397,0.097)(0.806, 0.397, 0.097)
1 (16/31,25/63,12/31)(16/31, 25/63, 12/31) (0.516,0.397,0.387)(0.516, 0.397, 0.387)
2 (22/31,25/63,6/31)(22/31, 25/63, 6/31) (0.710,0.397,0.194)(0.710, 0.397, 0.194)
3 (19/31,25/63,9/31)(19/31, 25/63, 9/31) (0.613,0.397,0.290)(0.613, 0.397, 0.290)

The four texels of a row get the indices 0, 2, 3 and 1. As 2-bit fields from the low bits up, this is the byte 0+2⋅4+3⋅16+1⋅64=1200 + 2 \cdot 4 + 3 \cdot 16 + 1 \cdot 64 = 120, or 0x78. The whole block is the 8 bytes 23 CB 2C 83 78 78 78 78. The largest error of a channel is 0.0160.016, about 4 levels of 255, which comes from the rounding to RGB565.

Correctness

The proof file shows three facts. First, the 64 bits split into fields that do not overlap, and every 64-bit string decodes, so decoding is a fixed function of the block with random access. Second, for fixed endpoints the index of line L9 gives the least total squared error, because each texel adds its own term. Third, if all colors of a block lie on the palette of two RGB565 words c0>c1c_0 > c_1, and both endpoints occur, the encoder finds exactly those words and the decoded block equals the input. The covariance of such a block has rank one, so the power iteration finds the line in one step.

Proof: The BC1 decoder is a fixed function of the block, and the encoder is lossless on palette colorsfull

We use the pseudocode and the notation of the page. The decoder works on integers and exact fractions. For the encoder we assume exact real arithmetic (real-ram) for the principal axis and the projections. The code uses floats there, and the code tests check the same claims in floats.

For an RGB565 word ww, let E(w)=(R/31,G/63,B/31)E(w) = (R/31, G/63, B/31) with R=⌊w/211⌋R = \lfloor w / 2^{11} \rfloor, G=⌊w/25⌋ mod 64G = \lfloor w / 2^5 \rfloor \bmod 64 and B=w mod 32B = w \bmod 32. The map EE is one to one from {0,…,65535}\{0, \dots, 65535\} to colors, because the three fields of ww are disjoint bit ranges and each field divides by a fixed number.

Theorem 1 (the rate and the layout). A block has 6464 bits and codes 16 texels, so the rate is 64/16=464/16 = 4 bits per texel. Every 64-bit string is a valid block, and lines L1 to L5 give a texel for each one.

Proof. Lines L1 and L2 read two 16-bit words and a 32-bit word, 16+16+32=6416 + 16 + 32 = 64 bits. Line L5 reads 16 fields of 2 bits, 3232 bits, so the fields of texels ii and j≠ij \ne i do not overlap. Each 2-bit field is a number in {0,1,2,3}\{0, 1, 2, 3\}, and both palettes of lines L3 and L4 have 4 entries, so every index is valid. □\square

So decoding is a fixed function of the block alone. A texel at (x,y)(x, y) needs only the block (⌊x/4⌋,⌊y/4⌋)(\lfloor x/4 \rfloor, \lfloor y/4 \rfloor), which gives random access at a fixed address. The code test test_random_access_and_determinism checks this.

Lemma 1 (the palettes). If c0>c1c_0 > c_1, the palette is C0C_0, C1C_1, 23C0+13C1\tfrac23 C_0 + \tfrac13 C_1, 13C0+23C1\tfrac13 C_0 + \tfrac23 C_1 with Cj=E(cj)C_j = E(c_j), all opaque. These lie on the segment from C1C_1 to C0C_0 at the parameters 1,0,23,131, 0, \tfrac23, \tfrac13, and they are four different colors. If c0≤c1c_0 \le c_1, the palette is C0C_0, C1C_1, 12(C0+C1)\tfrac12 (C_0 + C_1) and transparent black.

Proof. This is lines L3 and L4. If c0>c1c_0 > c_1, then c0≠c1c_0 \ne c_1, so C0≠C1C_0 \ne C_1 because EE is one to one. The four parameters are different, and a segment of nonzero length maps different parameters to different points. □\square

Lemma 2 (the index choice is optimal). For fixed endpoints, line L9 gives each texel an index of a palette color nearest to it. So no other choice of the 16 indices gives a smaller total squared error for these endpoints.

Proof. The total error is a sum of 16 terms, and the index of texel ii appears only in term ii. Line L9 minimizes each term on its own. □\square

The endpoints themselves are not optimal. The range fit of lines L6 to L8 is a heuristic. Its error is a measurement, given on the page.

Theorem 2 (lossless on palette colors). Let c0>c1c_0 > c_1 be two RGB565 words, and let every texel of a block be one of the four palette colors of Lemma 1, with both C0C_0 and C1C_1 present. Then the encoder returns a block that decodes to exactly the input texels.

Proof. Let d=C0−C1≠0d = C_0 - C_1 \ne 0. Each texel is C1+sidC_1 + s_i d with si∈{0,13,23,1}s_i \in \{0, \tfrac13, \tfrac23, 1\}. The mean is μ=C1+sˉd\mu = C_1 + \bar s d, and the covariance is Σ=σddT\Sigma = \sigma d d^T with σ=∑i(si−sˉ)2>0\sigma = \sum_i (s_i - \bar s)^2 > 0, since both s=0s = 0 and s=1s = 1 occur.

Line L6 starts the power iteration at the unit axis eae_a with the largest diagonal entry Σaa=σda2\Sigma_{aa} = \sigma d_a^2. Some coordinate of dd is not zero, so da≠0d_a \ne 0. Then Σea=σdad\Sigma e_a = \sigma d_a d, a nonzero multiple of dd, and every later step maps a multiple of dd to a multiple of dd, because Σd=σ∣d∣2d\Sigma d = \sigma |d|^2 d. So the axis is αd\alpha d for some α≠0\alpha \ne 0.

The projection of texel ii on the axis is (si−sˉ)α∣d∣2(s_i - \bar s) \alpha |d|^2, a strictly monotone function of sis_i. So line L7 picks a texel with s=0s = 0 and a texel with s=1s = 1 as the two extremes, which are the colors C1C_1 and C0C_0 (in some order, by the sign of α\alpha). Line L8 rounds each to the nearest RGB565 word. Cj=E(cj)C_j = E(c_j) has the components R/31R/31, G/63G/63 and B/31B/31, so the rounding gives back RR, GG and BB exactly, and the words are c0c_0 and c1c_1. Line L8 orders them so that the first is larger, which is (c0,c1)(c_0, c_1), and c0≠c1c_0 \ne c_1, so the encoder does not take the branch for equal words. The palette is the palette of Lemma 1. Each texel equals one palette color, at distance 0, and the other three colors are different from it, so line L9 picks that color. The decoder returns it. □\square

Cost. Decoding a texel takes O(1)O(1) time: two words, one palette and one 2-bit field. Encoding a block of 16 texels takes O(1)O(1) time for a fixed number of power iterations: the covariance is 3×33 \times 3, and line L9 compares each texel with 4 colors. An image of W×HW \times H texels takes Θ(WH)\Theta(WH) time to encode and WH/2W H / 2 bytes.

Complexity

Decoding a texel reads one block and does a few integer operations, O(1)O(1) in the word-RAM model. Encoding a block with the range fit takes O(1)O(1) time, for a fixed number of iterations on a 3×33 \times 3 matrix and 16 comparisons with 4 colors. So an image of NN texels takes Θ(N)\Theta(N) time to encode and N/2N / 2 bytes to store. Better encoders search more endpoints per block and cost more, but the decoder stays the same.

Properties

  • Fixed rate. Every block has 64 bits. This is a property of the format.
  • Random access. The address of a texel is known, and its block decodes alone. This is proved.
  • Lossless on palette colors. Proved for the encoder of this page, as above.
  • Measured error. On 300 random blocks of diagonal color gradients with a little noise, the encoder of the code has a root mean square error of about 3.4 levels of 255 when the colors in a block span at most 0.15, and about 11.5 levels when they span the full range. These are measurements. Four colors cannot follow a gradient of seven steps exactly.
  • Not exact across GPUs. The format specification gives the palette formulas but no rounding rule for the thirds and the halves, and GPUs differ in the last bit. The decoder of the code gives exact fractions.

Variants and improvements

  • Formats with alpha. Direct3D names them BC2 and BC3. BC2 adds 4 bits of alpha per texel. BC3 adds an alpha block of two 8-bit endpoints and 3-bit indices. Both use 128 bits per block, 8 bits per texel.
  • One and two channels. BC4 and BC5 use the alpha block of BC3 for one or two channels, which suits height maps and normal maps.
  • Later block formats. BC6H codes HDR color and BC7 codes high-quality RGBA, both in 128-bit blocks with several modes and partitions. ASTC has many block sizes.
  • Better encoders. Refine the endpoints by least squares for the chosen indices and repeat, or try many endpoint pairs around the range fit. Cluster fit tries every split of the sorted colors into the four palette slots.
  • Hardware rounding. Some decoders round the expansion to 8 bits and the thirds in integer arithmetic. A test that must match one GPU bit for bit needs its rounding rule.

When to use it

Use it for color textures on GPUs that support it, which includes nearly all desktop GPUs, when 4 bits per texel are worth a small loss. Use the alpha variants for textures with smooth alpha, and the three-color mode only for cut-out alpha. Use ASTC or BC7 where a better quality or another bit rate is needed. Do not use it for data that needs exact values, such as lookup tables or masks with many levels.

Pitfalls

  • Endpoints in the wrong order. If an encoder writes color0 <= color1 by accident, the block switches to the three-color palette, and index 3 becomes black or transparent. When the two rounded words are equal, the four-color mode is impossible, so write all indices 0.
  • Opaque black or transparent black. In the RGB variant of the OpenGL extension, index 3 of the three-color palette is opaque black. In the RGBA variant it is transparent. The code returns transparent black.
  • Gradients and banding. Smooth gradients over large areas show steps, because a block has only four colors and the endpoints have only 5 or 6 bits.
  • Normal maps. Storing xx, yy and zz in the three channels of this format gives poor normals. Use two channels in BC5 and rebuild zz.
  • Image size. The sides must be multiples of 4. Small mip levels still use whole blocks.
  • sRGB. For an sRGB texture, the decoder interpolates the stored values, and the sampler converts to linear after decoding. An encoder that measures the error in linear space and then stores sRGB values chooses worse endpoints.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

s3_texture_compression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/s3-texture-compression/. The authors are listed in prov/EBSNSC.jsonl.

"""S3 texture compression, the basic RGB format: decoder and a simple encoder.

A block codes 4 x 4 texels in 64 bits:
- bytes 0-1: color0, an RGB565 word, little endian (red in bits 15..11,
  green in bits 10..5, blue in bits 4..0);
- bytes 2-3: color1, the same;
- bytes 4-7: a 32-bit little-endian word of 16 indices of 2 bits; texel
  i = 4 y + x uses bits 2i and 2i + 1.

If color0 > color1 as unsigned numbers, the palette is color0, color1,
(2 color0 + color1) / 3 and (color0 + 2 color1) / 3. Otherwise it is color0,
color1, (color0 + color1) / 2 and transparent black.

The decoder returns exact Fractions in [0, 1], with the 5-bit and 6-bit
values divided by 31 and 63. Hardware rounds the thirds and the expansion to
8 bits in slightly different ways, so a bit-exact match with one GPU needs
its own rounding rule. The encoder is a range fit along the principal axis
of the block, which is fast but not optimal; its error is measured in the tests.
"""

from fractions import Fraction

BLOCK_BITS = 64
TEXELS = 16
BITS_PER_TEXEL = Fraction(BLOCK_BITS, TEXELS)  # 4 bits per texel


def unpack565(word):
    """RGB565 word -> (r, g, b) as exact Fractions in [0, 1]."""
    r, g, b = (word >> 11) & 31, (word >> 5) & 63, word & 31
    return (Fraction(r, 31), Fraction(g, 63), Fraction(b, 31))


def pack565(rgb):
    """(r, g, b) in [0, 1] -> the nearest RGB565 word."""
    r, g, b = (min(max(c, 0.0), 1.0) for c in rgb)
    return (int(round(r * 31)) << 11) | (int(round(g * 63)) << 5) | int(round(b * 31))


def palette(c0, c1):
    """The four RGBA palette entries of a block with endpoint words c0 and c1."""
    a, b = unpack565(c0), unpack565(c1)
    if c0 > c1:  # @line L3
        p2 = tuple((2 * x + y) / 3 for x, y in zip(a, b))
        p3 = tuple((x + 2 * y) / 3 for x, y in zip(a, b))
        return [a + (1,), b + (1,), p2 + (1,), p3 + (1,)]
    mid = tuple((x + y) / 2 for x, y in zip(a, b))  # @line L4
    return [a + (1,), b + (1,), mid + (1,), (0, 0, 0, 0)]


def decode_block(block):
    """8 bytes -> 16 RGBA texels in raster order, as exact Fractions."""
    if len(block) != 8:
        raise ValueError("a BC1 block has 8 bytes")
    c0 = block[0] | (block[1] << 8)  # @line L1
    c1 = block[2] | (block[3] << 8)
    bits = block[4] | (block[5] << 8) | (block[6] << 16) | (block[7] << 24)
    pal = palette(c0, c1)  # @line L2
    return [pal[(bits >> (2 * i)) & 3] for i in range(TEXELS)]  # @line L5


def pack_block(c0, c1, indices):
    bits = 0
    for i, k in enumerate(indices):
        bits |= (k & 3) << (2 * i)
    return bytes((c0 & 255, c0 >> 8, c1 & 255, c1 >> 8,
                  bits & 255, (bits >> 8) & 255, (bits >> 16) & 255, bits >> 24))


def principal_axis(colors, iterations=24):
    """The dominant eigenvector of the 3 x 3 covariance, by power iteration."""
    n = len(colors)
    mean = [sum(c[a] for c in colors) / n for a in range(3)]
    cov = [[sum((c[a] - mean[a]) * (c[b] - mean[b]) for c in colors) for b in range(3)] for a in range(3)]
    # Start from the axis with the largest variance. In rare cases this start
    # is orthogonal to the dominant eigenvector, and the iteration ends on
    # another eigenvector. That axis still gives a valid, if worse, encoding.
    v = [0.0, 0.0, 0.0]
    v[max(range(3), key=lambda a: cov[a][a])] = 1.0
    for _ in range(iterations):
        w = [sum(cov[a][b] * v[b] for b in range(3)) for a in range(3)]
        norm = max(abs(x) for x in w)
        if norm == 0:
            return mean, [1.0, 0.0, 0.0]
        v = [x / norm for x in w]
    return mean, v


def sq_err(rgb, entry):
    return sum((float(x) - float(y)) ** 2 for x, y in zip(rgb, entry[:3]))


def nearest_indices(colors, pal, count):
    return [min(range(count), key=lambda k: sq_err(c, pal[k])) for c in colors]


def encode_block(colors):
    """16 RGB colors in [0, 1] -> 8 bytes in the 4-color mode (range fit)."""
    if len(colors) != TEXELS:
        raise ValueError("a BC1 block has 16 texels")
    mean, axis = principal_axis(colors)  # @line L6
    proj = [sum((c[a] - mean[a]) * axis[a] for a in range(3)) for c in colors]
    lo = colors[min(range(TEXELS), key=lambda i: proj[i])]  # @line L7
    hi = colors[max(range(TEXELS), key=lambda i: proj[i])]
    c0, c1 = pack565(hi), pack565(lo)  # @line L8
    if c0 < c1:
        c0, c1 = c1, c0
    if c0 == c1:
        return pack_block(c0, c1, [0] * TEXELS)
    idx = nearest_indices(colors, palette(c0, c1), 4)  # @line L9
    return pack_block(c0, c1, idx)  # @line L10


def encode_image(pixels, width, height):
    """Encode an image (rows of RGB tuples) whose sides are multiples of 4."""
    if width % 4 or height % 4:
        raise ValueError("the sides must be multiples of 4")
    out = []
    for by in range(0, height, 4):
        for bx in range(0, width, 4):
            out.append(encode_block([pixels[by + y][bx + x] for y in range(4) for x in range(4)]))
    return out


def decode_texel(blocks, width, x, y):
    """Random access: decode only the block that holds texel (x, y)."""
    block = blocks[(y // 4) * (width // 4) + x // 4]
    return decode_block(block)[4 * (y % 4) + x % 4]
test_s3_texture_compression.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/s3-texture-compression/. The authors are listed in prov/EBSNSC.jsonl.

"""Tests of the BC1 decoder and encoder.

The decoder is checked on the bit layout and on exact palettes. The encoder
is checked to be lossless on blocks whose colors lie on the palette of two
RGB565 endpoints, to choose the best index for its endpoints, and to have a
measured error on smooth blocks with noise.
"""

import random
from fractions import Fraction
from math import sqrt

from s3_texture_compression import (
    BITS_PER_TEXEL,
    decode_block,
    decode_texel,
    encode_block,
    encode_image,
    pack_block,
    palette,
    sq_err,
    unpack565,
)


def test_layout_and_rate():
    assert BITS_PER_TEXEL == 4
    rng = random.Random(1)
    for _ in range(200):
        c0, c1 = rng.randrange(65536), rng.randrange(65536)
        idx = [rng.randrange(4) for _ in range(16)]
        block = pack_block(c0, c1, idx)
        assert len(block) * 8 == 64
        pal = palette(c0, c1)
        assert decode_block(block) == [pal[k] for k in idx]


def test_known_block():
    red, blue = 0xF800, 0x001F
    block = pack_block(red, blue, [0, 1, 2, 3] * 4)
    assert block[:4] == bytes((0x00, 0xF8, 0x1F, 0x00))
    assert block[4:] == bytes((0xE4,) * 4)  # indices 0, 1, 2, 3 from the low bits up
    t = decode_block(block)
    assert t[0] == (1, 0, 0, 1) and t[1] == (0, 0, 1, 1)
    assert t[2] == (Fraction(2, 3), 0, Fraction(1, 3), 1)
    assert t[3] == (Fraction(1, 3), 0, Fraction(2, 3), 1)
    # Swap the endpoints: c0 <= c1 selects the 3-color mode with transparency.
    t = decode_block(pack_block(blue, red, [0, 1, 2, 3] * 4))
    assert t[2] == (Fraction(1, 2), 0, Fraction(1, 2), 1) and t[3] == (0, 0, 0, 0)


def test_palette_is_exact():
    rng = random.Random(2)
    for _ in range(300):
        c0, c1 = rng.randrange(65536), rng.randrange(65536)
        a, b = unpack565(c0), unpack565(c1)
        pal = palette(c0, c1)
        if c0 > c1:
            for j in range(3):
                assert pal[2][j] == Fraction(2, 3) * a[j] + Fraction(1, 3) * b[j]
                assert pal[3][j] == Fraction(1, 3) * a[j] + Fraction(2, 3) * b[j]
        else:
            assert pal[3] == (0, 0, 0, 0)
            assert all(pal[2][j] == (a[j] + b[j]) / 2 for j in range(3))


def test_lossless_on_palette_colors():
    rng = random.Random(3)
    done = 0
    while done < 200:
        c0, c1 = rng.randrange(65536), rng.randrange(65536)
        if c0 <= c1:
            continue
        pal = palette(c0, c1)
        idx = [0, 1] + [rng.randrange(4) for _ in range(14)]
        rng.shuffle(idx)
        colors = [tuple(float(x) for x in pal[k][:3]) for k in idx]
        out = decode_block(encode_block(colors))
        assert out == [pal[k] for k in idx]
        done += 1


def test_index_choice_is_best_for_the_endpoints():
    rng = random.Random(4)
    for _ in range(200):
        colors = [(rng.random(), rng.random(), rng.random()) for _ in range(16)]
        block = encode_block(colors)
        c0, c1 = block[0] | block[1] << 8, block[2] | block[3] << 8
        pal = palette(c0, c1)
        out = decode_block(block)
        for c, got in zip(colors, out):
            assert sq_err(c, got) <= min(sq_err(c, p) for p in pal[:4] if p[3] == 1) + 1e-15


def gradient_rmse(amplitude, seed=5, blocks=300):
    """RMSE in levels of 255 on diagonal gradient blocks with a little noise."""
    rng = random.Random(seed)
    total, count = 0.0, 0
    for _ in range(blocks):
        a = [rng.random() for _ in range(3)]
        b = [min(1.0, max(0.0, a[j] + rng.uniform(-amplitude, amplitude))) for j in range(3)]
        colors = []
        for y in range(4):
            for x in range(4):
                t = (x + y) / 6
                colors.append(tuple(min(1.0, max(0.0, a[j] + t * (b[j] - a[j]) + rng.gauss(0, 0.01)))
                                    for j in range(3)))
        out = decode_block(encode_block(colors))
        total += sum(sq_err(c, d) for c, d in zip(colors, out))
        count += 48
    return 255 * sqrt(total / count)


def test_measured_error_on_smooth_blocks():
    # Measurements of this encoder on this data, with seed 5: about 3.4 levels
    # for a low contrast and 11.5 for the full range. A gradient of 7 steps
    # has only 4 palette colors, so a high contrast costs more.
    assert gradient_rmse(0.15) < 4.5
    assert gradient_rmse(1.0) < 14.0


def test_random_access_and_determinism():
    rng = random.Random(6)
    w, h = 8, 12
    img = [[(rng.random(), rng.random(), rng.random()) for _ in range(w)] for _ in range(h)]
    blocks = encode_image(img, w, h)
    assert blocks == encode_image(img, w, h)
    assert len(blocks) == (w // 4) * (h // 4)
    for y in range(h):
        for x in range(w):
            full = decode_block(blocks[(y // 4) * 2 + x // 4])[4 * (y % 4) + x % 4]
            assert decode_texel(blocks, w, x, y) == full

History

S3 Incorporated filed the patent for fixed-rate block compression with inferred pixel values in October 1997, with Konstantine Iourcha, Krishna Nayak and Zhou Hong as inventors, and it was granted in September 1999. The method builds on block truncation coding, which also codes a block by two colors and a bit per pixel. Microsoft licensed the formats for DirectX, where they were called DXTC, and later versions of Direct3D renamed them BC1 to BC3. OpenGL supports them through the EXT_texture_compression_s3tc extension. For many years they were the standard compressed texture formats on desktop GPUs.

References

  1. Iourcha, Nayak and Hong, US patent 5,956,431, 1999, the whole patent (two stored colors per block, inferred colors between them, and an index per pixel)
  2. Khronos Group, EXT_texture_compression_s3tc, OpenGL extension specification, version 1.6, 2013, the appendix on the S3TC formats (the 8 bytes of a block, code(x, y) from bits 2(4y + x) and 2(4y + x) + 1, and the palettes for color0 > color1 and color0 <= color1)
  3. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Section 6.2, Image Texturing, the part on texture compression (general locator)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example