Skip to content
Myr

render: fix rounding error when calculating background color with alpha

Before adoption: this commit came in with the history the project adopted, so no landing records it.

We use pre-multiplied alpha color channels, but were having bad rounding errors due to the alpha divider being truncated to an integer. The algorithm for pre-multiplying a color channel is: alpha_divider = 0xffff / alpha pre_mult_color = color / alpha_divider In order to fix the rounding errors, we could turn ‘alpha_divider’ into a double. That however would introduce a performance penalty since now we’d need to do floating point math for each cell. The algorithm can be trivially converted to: pre_mult_color = color * alpha / 0xffff Since both color and alpa values are < 65536, the multiplication is “safe”; it will not overflow an uint32_t.

authored by Daniel Eklöf · committed by Daniel Eklöf · parent cfbe11b · Browse files · 2 files+7 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+7 added−8 removed

  • other:+7 added−8 removed

2 files+7 added−8 removed

modified:CHANGELOG.md+4 added
modified:render.c+3 added-8 removed
75 unmodified lines
7677static pixman_color_t78rgba2pixman(struct rgba rgba)79{80 if (rgba.a == 0.)81 return (pixman_color_t){0, 0, 0, 0};8280 uint16_t r = rgba.r * 65535.0;81 uint16_t g = rgba.g * 65535.0;82 uint16_t b = rgba.b * 65535.0;83 uint16_t a = rgba.a * 65535.0;8488 uint16_t a_div = 0xffff / a;8985 return (pixman_color_t){91 .red = r / a_div,92 .green = g / a_div,93 .blue = b / a_div,86 .red = r * a / 0xffff,87 .green = g * a / 0xffff,88 .blue = b * a / 0xffff,89 .alpha = a,90 };91}92
376 unmodified lines