Skip to content

Score RGBGFX palette assignments with exact fractions - #2246

Closed
vulcandth wants to merge 1 commit into
gbdev:masterfrom
vulcandth:codex/rgbgfx-relative-size
Closed

vulcandth wants to merge 1 commit into
gbdev:masterfrom
vulcandth:codex/rgbgfx-relative-size

Conversation

@vulcandth

Copy link
Copy Markdown
Contributor

Fixes #2245.

I’m Chatgpt Astra, an AI agent. I wrote the code, regression fixtures, and this pull request description.

RGBGFX can score an overloaded palette exactly with ordinary 64-bit integers. Each tile uses at most four colors, so each score needs at most four fractions. This change removes the invalid divisibility assumption while preserving the existing placement and removal rules. It also adds a six-tile regression that needs two palettes with those rules and three if overloaded pages are skipped.

What went wrong

A Game Boy Color tile is an eight-by-eight square of pixels. It needs one palette that contains every color used by that square. Tiles can share palettes. RGBGFX groups tiles that use the same colors, then decides how to place the resulting color sets. It gives a color a smaller cost when more sets on the candidate palette already share it. For example, a color that appears in three assigned sets contributes one quarter to the score of a candidate. A color that appears in none contributes one.

The old code multiplied each contribution by 12,252,240 before dividing. Every integer from 1 through 17 divides that number evenly. The code told the compiler that every division would be exact. That promise depended on a limit that applies to a finished palette. During packing, RGBGFX deliberately lets a palette hold too many colors. If all assigned sets have the same efficiency, it leaves them there and can add more sets later.

An image with 18 tiles exposes the error. Give each tile black and a different shade of red. All the sets have the same efficiency on the temporary palette. When RGBGFX scores the eighteenth assigned set, black contributes one nineteenth. The old scale happens to be divisible by 18, but 19 leaves a remainder. An assertion-enabled build stops at that division. In a release build the compiler can treat this reachable situation as impossible, which is undefined behavior even when the resulting palette file looks right. Original integer-scoring change and pull request 1565

What the fix does

RGBGFX stores each score as a numerator and a denominator. Adding one fifth to a running score of one third, for example, gives eight fifteenths. The code uses that same elementary addition for each color. It can leave the fraction unreduced because at most four additions are needed. Both palette selection and the decision to remove a set use the exact result.

The comparison also stays within 64 bits. It first compares the whole-number parts of two fractions. If those match, a fraction with a remainder is larger than one that ended exactly. If both have a remainder, the code turns the remaining fractions upside down and reverses the comparison. For example, comparing one third with two fifths becomes a comparison of three with two and a half in the opposite direction. Each repetition replaces a positive denominator with a strictly smaller positive remainder. This guarantees termination, handles equal fractions such as one half and two quarters, and avoids the potentially oversized products from cross multiplication.

Why the numbers fit

  1. A finished palette with four opaque colors can cover at most 15 distinct nonempty color sets. Each of its four colors can be present or absent, giving 16 possibilities, and one of those is empty. With fewer opaque colors the bound is smaller. RGBGFX has already combined duplicate sets and excluded empty ones before it calls the packer.
  2. RGBGFX supports at most 256 palettes. Even if each palette covered 15 different sets, the entire output could cover only 3,840. The new check uses the requested palette count and actual opaque capacity. It rejects an input early only when the requested output is already impossible. Such an input now gets an explanation of the capacity limit. The 256-palette option remains available. RGBGFX manual
  3. Each set is assigned to at most one slot on a page. A removed set leaves its slot before the queue handles it again. Consequently, a color can occur on a temporary page at most 3,840 times, even if that page contains every set. Adding one gives a positive divisor of at most 3,841.
  4. Multiplying four such divisors gives at most 217,659,300,264,961. Each contribution is at most one, so the numerator is at most four times that number. Calculating efficiency also multiplies a denominator by at most four. The largest bound in either calculation is 870,637,201,059,844, below the 64-bit unsigned maximum of 18,446,744,073,709,551,615. Every intermediate addition and multiplication is covered because all terms are nonnegative. Efficiency divides by a positive score because each scored set has at least one color.

Where the old scale divided evenly, scores differed from these fractions by the same positive factor. Their order and their ties are therefore identical. For larger divisors the new code implements the same scoring rule exactly. The packing algorithm is a heuristic, so it can still use more palettes than the best possible arrangement. The proof covers the arithmetic and its decisions.

Why the proposed shortcuts matter

Skipping an overloaded page can make a valid conversion fail. The six tile color pairs in the regression image are (3,4), (2,5), (1,5), (3,5), (0,1), and (4,5), in that order. RGBGFX assigns them to palettes 0, 0, 1, 0, 1, and 0. Palette 0 contains colors 2, 3, 4, and 5. Palette 1 contains colors 0, 1, and 5. In a comparison build whose only change was to skip overloaded candidates, the same input needed three palettes. A two-palette limit therefore distinguishes the two implementations. Forcing an eviction whenever all efficiencies tie would also change an explicit decision in the algorithm. Section 3.3 of the paper describes the tie rule and the later redistribution of overloaded pages. Grange, Kacem and Martin, section 3.3

A larger fixed scale can split an exact tie. With the suggested scale of 13,008,876,591,110,400, consider the two scores 1/23 + 1/184 and 1/24 + 1/138. Both equal 9/184. Dividing each scaled term with integer truncation gives totals of 636,303,746,304,312 and 636,303,746,304,313. The one-unit difference is enough to turn a tie into an ordering. This is an arithmetic counterexample. The six-tile example above is a separately tested image. Clamping the count likewise makes distinct contributions equal once both counts reach the clamp. Suggested scale and factorization

The reference Python implementation uses exact fractions. It adds one to the count when scoring a candidate and uses the existing count when scoring a resident tile. RGBGFX and the linked Rust rewrite add one in both situations. This patch preserves the RGBGFX convention. The Rust implementation uses floating point, which the earlier RGBDS change removed because platforms could disagree. The bounds above let RGBGFX keep integer arithmetic without a new library or an arbitrary-precision number implementation. Python reference, candidate scoring, resident scoring, Python fractions, and Rust implementation

Testing

  • The original code from revision 4c29408a failed its divisibility assertion on the new 18-tile image. The fixed version produced the six expected groups of three tiles. The six-tile counterexample is a second permanent regression. Both run through the regular RGBGFX test suite, with input from a file and from standard input.
  • The three inputs attached to Computing the "relative size" of a color set has a wrong assumption #2245 produced 12, 18, and 256 palettes for 36, 52, and 768 tiles. Each tile's palette-map entry led to a palette containing every one of its colors. These counts are the minimum for these particular images because a palette holds black and at most three unique foreground colors. The original GCC release binary and the corrected GCC and Clang binaries produced byte-identical palette files and maps on all three inputs.
  • The 768-tile palette rendering matched the published image pixel for pixel. For the 52-tile image, every row contained the same visible colors as the published rendering, with their order reversed within all 18 rows. The original local release build produced the same palette bytes as the fix on the downloaded PNG. The difference from that screenshot therefore predates this change. Published 52-tile rendering and 768-tile example
  • An independent Python implementation used exact fractions to predict every placement, removal, and tie in the overload phase. It matched 21,893 placements, 6,870 removals, and 7,578 decisions to retain a tied page across 2,083 PNGs. The inputs included all 1,023 nonempty selections of two-color tiles drawn from five colors in a fixed order, 1,000 seeded cases, and 60 cases built around a shared color. They covered opaque capacities from one to four, including 376 images with transparency. The checker also read the final palette and map files and verified coverage for all 15,023 tiles.
  • Boundary tests accepted 256 distinct single-color tiles with one color per palette and rejected the 257th. Another image supplied all six possible pairs from each of 256 disjoint four-color groups. All 1,536 sets fit into 256 palettes. An image with 3,841 distinct sets reached the new early rejection. A shared-black image with 769 foreground colors required 257 palettes. The 768-foreground image also failed as expected when the requested limit was lowered to 255.
  • The C++ fraction comparison matched independent Python integer arithmetic on 293,612 pairs in both argument orders. The cases included unreduced ties, zero numerators, consecutive Fibonacci ratios, and fractions near the largest 64-bit integer that differ by just one in their exact cross products. The tests ran with 64-bit Clang under undefined-behavior and unsigned-overflow checks, and with an optimized 32-bit MSVC executable.
  • The GCC release build passed all 1,828 internal tests, including 364 RGBGFX tests. The full RGBGFX suite also passed with Clang AddressSanitizer and UndefinedBehaviorSanitizer. The GCC development build completed with the project's warnings-as-errors configuration. External game-project builds were outside this test run.

Reproducing the regression tests

Build the project and run bash test/run-tests.sh --only-internal from the repository root. To run just the two new fixtures, the commands below write the palette maps to standard output and compare them with their expected bytes.

./rgbgfx -q - test/gfx/overloaded_shared_color.png | cmp - test/gfx/overloaded_shared_color.out.palmap
./rgbgfx -n 2 -q - test/gfx/overloaded_page_candidate.png | cmp - test/gfx/overloaded_page_candidate.out.palmap

Bound distinct input sets by the number of nonempty subsets the requested palettes can cover. Each tile score then fits in 64 bits, and quotient and remainder comparisons preserve exact ties on overloaded pages.

Assisted-by: Codex:GPT-6 ASan UBSan
@Rangi42

Rangi42 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for opening this! It was a very helpful reference for #2250. I'm glad Astra gave such a thorough description of what it did and why it works (and thoroughly tested its work with an entire Python reimplementation).

@Rangi42 Rangi42 closed this Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Computing the "relative size" of a color set has a wrong assumption

2 participants