Switch image textures to premultiplied alpha The renderer intentionally chose unmultiplied alpha for gradients, in order to not lose color information with transparent stops. But for this very same reason, we need *premultiplied* alpha for image textures. Otherwise, the (transparent) background color can bleed into edges. Switch image textures to premultiplied, while keeping gradients unmultiplied. Diffs= a70f0f84dd Switch image textures to premultiplied alpha (#9377) Co-authored-by: Chris Dalton <99840794+csmartdalton@users.noreply.github.com> Co-authored-by: blakdragan7 <jcopela4@Gmail.com>
diff --git a/.rive_head b/.rive_head index 79e096f..ae2b08b 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -9d516a9ece7c618a9ca4c861baefcd963497d2e0 +a70f0f84dda65ddd956b1229b9530aed37f44b18
diff --git a/decoders/include/rive/decoders/bitmap_decoder.hpp b/decoders/include/rive/decoders/bitmap_decoder.hpp index e9b9856..bdad7be 100644 --- a/decoders/include/rive/decoders/bitmap_decoder.hpp +++ b/decoders/include/rive/decoders/bitmap_decoder.hpp
@@ -15,7 +15,8 @@ enum class PixelFormat : uint8_t { RGB, - RGBA + RGBA, + RGBAPremul, }; Bitmap(uint32_t width, @@ -43,9 +44,6 @@ { return std::move(m_Bytes); } - size_t byteSize() const; - size_t byteSize(PixelFormat format) const; - size_t bytesPerPixel(PixelFormat format) const; enum class ImageType {
diff --git a/decoders/src/bitmap_decoder.cpp b/decoders/src/bitmap_decoder.cpp index b31e012..c6fa8b5 100644 --- a/decoders/src/bitmap_decoder.cpp +++ b/decoders/src/bitmap_decoder.cpp
@@ -4,9 +4,9 @@ #include "rive/decoders/bitmap_decoder.hpp" #include "rive/rive_types.hpp" +#include "rive/math/simd.hpp" #include <stdio.h> #include <string.h> -#include <vector> Bitmap::Bitmap(uint32_t width, uint32_t height, @@ -25,47 +25,80 @@ Bitmap(width, height, pixelFormat, std::unique_ptr<const uint8_t[]>(bytes)) {} -size_t Bitmap::bytesPerPixel(PixelFormat format) const +static size_t bytes_per_pixel(Bitmap::PixelFormat format) { switch (format) { - case PixelFormat::RGB: + case Bitmap::PixelFormat::RGB: return 3; - case PixelFormat::RGBA: + case Bitmap::PixelFormat::RGBA: + case Bitmap::PixelFormat::RGBAPremul: return 4; } RIVE_UNREACHABLE(); } -size_t Bitmap::byteSize(PixelFormat format) const -{ - return m_Width * m_Height * bytesPerPixel(format); -} - -size_t Bitmap::byteSize() const { return byteSize(m_PixelFormat); } - void Bitmap::pixelFormat(PixelFormat format) { if (format == m_PixelFormat) { return; } - auto nextByteSize = byteSize(format); - auto nextBytes = std::unique_ptr<uint8_t[]>(new uint8_t[nextByteSize]); - size_t fromBytesPerPixel = bytesPerPixel(m_PixelFormat); - size_t toBytesPerPixel = bytesPerPixel(format); + size_t imageNumPixels = m_Height * m_Width; + size_t fromBytesPerPixel = bytes_per_pixel(m_PixelFormat); + size_t toBytesPerPixel = bytes_per_pixel(format); + size_t toSizeInBytes = imageNumPixels * toBytesPerPixel; + + // Round our allocation up to a multiple of 8 so we can premultiply two + // pixels at once if needed. + size_t allocSize = (toSizeInBytes + 7) & ~7llu; + assert(allocSize >= toSizeInBytes && allocSize <= toSizeInBytes + 7); + auto toBytes = std::unique_ptr<uint8_t[]>(new uint8_t[allocSize]); + + // Copy into the new pixel buffer. int writeIndex = 0; int readIndex = 0; - for (uint32_t i = 0; i < m_Width * m_Height; i++) + for (size_t i = 0; i < imageNumPixels; i++) { for (size_t j = 0; j < toBytesPerPixel; j++) { - nextBytes[writeIndex++] = + toBytes[writeIndex++] = j < fromBytesPerPixel ? m_Bytes[readIndex++] : 255; } } - m_Bytes = std::move(nextBytes); + if (format == PixelFormat::RGBAPremul) + { + // Convert to premultiplied alpha. + for (size_t i = 0; i < toSizeInBytes; i += 8) + { + // Load 2 pixels into 64 bits. We overallocated our buffer to ensure + // we could always premultiply in twos. + assert(i + 8 <= allocSize); + rive::uint8x8 twoPx = rive::simd::load<uint8_t, 8>(&toBytes[i]); + uint8_t a0 = twoPx[3]; + uint8_t a1 = twoPx[7]; + // Don't premultiply fully opaque pixels. + if (a0 != 255 || a1 != 255) + { + // Cast to 16 bits to avoid overflow. + rive::uint16x8 widePx = rive::simd::cast<uint16_t>(twoPx); + // Multiply by alpha. + rive::uint16x8 alpha = {a0, a0, a0, 255, a1, a1, a1, 255}; + widePx = rive::simd::div255(widePx * alpha); + // Cast back to 8 bits and store. + twoPx = rive::simd::cast<uint8_t>(widePx); + rive::simd::store(&toBytes[i], twoPx); + } + } + } + else + { + // Unmultiplying alpha is not currently supported. + assert(m_PixelFormat != PixelFormat::RGBAPremul); + } + + m_Bytes = std::move(toBytes); m_PixelFormat = format; }
diff --git a/decoders/src/bitmap_decoder_cg.mm b/decoders/src/bitmap_decoder_cg.mm index fef1062..a9d5129 100644 --- a/decoders/src/bitmap_decoder_cg.mm +++ b/decoders/src/bitmap_decoder_cg.mm
@@ -4,7 +4,6 @@ #include "rive/decoders/bitmap_decoder.hpp" #include "rive/rive_types.hpp" -#include "rive/math/simd.hpp" #include "rive/math/math_types.hpp" #include "rive/core/type_conversions.hpp" #include "utils/auto_cf.hpp" @@ -112,57 +111,9 @@ return nullptr; } - // CG only supports premultiplied alpha. Unmultiply now. - size_t imageNumPixels = image.height * image.width; - size_t imageSizeInBytes = imageNumPixels * 4; - // Process 2 pixels at once, deal with odd number of pixels - if (imageNumPixels & 1) - { - imageSizeInBytes -= 4; - } - size_t i; - for (i = 0; i < imageSizeInBytes; i += 8) - { - // Load 2 pixels into 64 bits - auto twoPixels = rive::simd::load<uint8_t, 8>(&image.pixels[i]); - auto a0 = twoPixels[3]; - auto a1 = twoPixels[7]; - // Avoid computation if both pixels are either fully transparent or - // opaque pixels - if ((a0 > 0 && a0 < 255) || (a1 > 0 && a1 < 255)) - { - // Avoid potential division by zero - a0 = std::max<uint8_t>(a0, 1); - a1 = std::max<uint8_t>(a1, 1); - // Cast to 16 bits to avoid overflow - rive::uint16x8 rgbaWidex2 = rive::simd::cast<uint16_t>(twoPixels); - // Unpremult: multiply by RGB by "255.0 / alpha" - rgbaWidex2 *= rive::uint16x8{255, 255, 255, 1, 255, 255, 255, 1}; - rgbaWidex2 /= rive::uint16x8{a0, a0, a0, 1, a1, a1, a1, 1}; - // Cast back to 8 bits and store - twoPixels = rive::simd::cast<uint8_t>(rgbaWidex2); - rive::simd::store(&image.pixels[i], twoPixels); - } - } - // Process last odd pixel if needed - if (imageNumPixels & 1) - { - // Load 1 pixel into 32 bits - auto rgba = rive::simd::load<uint8_t, 4>(&image.pixels[i]); - // Avoid computation for fully transparent or opaque pixels - if (rgba.a > 0 && rgba.a < 255) - { - // Cast to 16 bits to avoid overflow - rive::uint16x4 rgbaWide = rive::simd::cast<uint16_t>(rgba); - // Unpremult: multiply by RGB by "255.0 / alpha" - rgbaWide *= rive::uint16x4{255, 255, 255, 1}; - rgbaWide /= rive::uint16x4{rgba.a, rgba.a, rgba.a, 1}; - // Cast back to 8 bits and store - rgba = rive::simd::cast<uint8_t>(rgbaWide); - rive::simd::store(&image.pixels[i], rgba); - } - } - - return std::make_unique<Bitmap>( - image.width, image.height, PixelFormat::RGBA, std::move(image.pixels)); + return std::make_unique<Bitmap>(image.width, + image.height, + // CG always premultiplies alpha. + PixelFormat::RGBAPremul, + std::move(image.pixels)); }
diff --git a/include/rive/math/simd.hpp b/include/rive/math/simd.hpp index c52c995..d8d1e91 100644 --- a/include/rive/math/simd.hpp +++ b/include/rive/math/simd.hpp
@@ -457,6 +457,15 @@ } #endif +// Returns "(x + 127) / 255", for x in the range 0..255*255. +template <int N> +SIMD_ALWAYS_INLINE gvec<uint16_t, N> div255(gvec<uint16_t, N> x) +{ + assert(all(x <= 255u * 255u)); + x += 128; + return (x + (x >> 8)) >> 8; +} + // Approximates acos(x) within 0.96 degrees, using the rational polynomial: // // acos(x) ~= (bx^3 + ax) / (dx^4 + cx^2 + 1) + pi/2
diff --git a/renderer/include/rive/renderer/d3d/render_context_d3d_impl.hpp b/renderer/include/rive/renderer/d3d/render_context_d3d_impl.hpp index 60b6e77..2ee6701 100644 --- a/renderer/include/rive/renderer/d3d/render_context_d3d_impl.hpp +++ b/renderer/include/rive/renderer/d3d/render_context_d3d_impl.hpp
@@ -122,7 +122,7 @@ rcp<Texture> makeImageTexture(uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) override; + const uint8_t imageDataRGBAPremul[]) override; std::unique_ptr<BufferRing> makeUniformBufferRing( size_t capacityInBytes) override;
diff --git a/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp b/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp index e275516..b3c8172 100644 --- a/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp +++ b/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp
@@ -46,7 +46,7 @@ rcp<Texture> makeImageTexture(uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) override; + const uint8_t imageDataRGBAPremul[]) override; // Takes ownership of textureID and responsibility for deleting it. rcp<Texture> adoptImageTexture(uint32_t width,
diff --git a/renderer/include/rive/renderer/metal/render_context_metal_impl.h b/renderer/include/rive/renderer/metal/render_context_metal_impl.h index 6d2157e..a38e365 100644 --- a/renderer/include/rive/renderer/metal/render_context_metal_impl.h +++ b/renderer/include/rive/renderer/metal/render_context_metal_impl.h
@@ -124,7 +124,7 @@ rcp<Texture> makeImageTexture(uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) override; + const uint8_t imageDataRGBAPremul[]) override; // Atomic mode requires a barrier between overlapping draws. We have to // implement this barrier in various different ways, depending on which
diff --git a/renderer/include/rive/renderer/render_context_helper_impl.hpp b/renderer/include/rive/renderer/render_context_helper_impl.hpp index 3b58653..1079a52 100644 --- a/renderer/include/rive/renderer/render_context_helper_impl.hpp +++ b/renderer/include/rive/renderer/render_context_helper_impl.hpp
@@ -70,10 +70,11 @@ BufferRing* tessSpanBufferRing() { return m_tessSpanBuffer.get(); } BufferRing* triangleBufferRing() { return m_triangleBuffer.get(); } - virtual rcp<Texture> makeImageTexture(uint32_t width, - uint32_t height, - uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) = 0; + virtual rcp<Texture> makeImageTexture( + uint32_t width, + uint32_t height, + uint32_t mipLevelCount, + const uint8_t imageDataRGBAPremul[]) = 0; virtual std::unique_ptr<BufferRing> makeUniformBufferRing( size_t capacityInBytes) = 0;
diff --git a/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp b/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp index 496318a..964bc4d 100644 --- a/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp +++ b/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp
@@ -94,7 +94,7 @@ rcp<Texture> makeImageTexture(uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) override; + const uint8_t imageDataRGBAPremul[]) override; protected: RenderContextWebGPUImpl(wgpu::Device device,
diff --git a/renderer/src/d3d/render_context_d3d_impl.cpp b/renderer/src/d3d/render_context_d3d_impl.cpp index 59c69f1..576ee7a 100644 --- a/renderer/src/d3d/render_context_d3d_impl.cpp +++ b/renderer/src/d3d/render_context_d3d_impl.cpp
@@ -679,7 +679,7 @@ UINT width, UINT height, UINT mipLevelCount, - const uint8_t imageDataRGBA[]) : + const uint8_t imageDataRGBAPremul[]) : Texture(width, height) { m_texture = renderContextImpl->makeSimple2DTexture( @@ -701,7 +701,7 @@ renderContextImpl->gpuContext()->UpdateSubresource(m_texture.Get(), 0, &box, - imageDataRGBA, + imageDataRGBAPremul, width * 4, 0); @@ -728,13 +728,13 @@ uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) + const uint8_t imageDataRGBAPremul[]) { return make_rcp<TextureD3DImpl>(this, width, height, mipLevelCount, - imageDataRGBA); + imageDataRGBAPremul); } class BufferRingD3D : public BufferRing
diff --git a/renderer/src/gl/render_context_gl_impl.cpp b/renderer/src/gl/render_context_gl_impl.cpp index dcb8d87..ae4d11f 100644 --- a/renderer/src/gl/render_context_gl_impl.cpp +++ b/renderer/src/gl/render_context_gl_impl.cpp
@@ -336,7 +336,7 @@ uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) + const uint8_t imageDataRGBAPremul[]) { GLuint textureID; glGenTextures(1, &textureID); @@ -351,7 +351,7 @@ height, GL_RGBA, GL_UNSIGNED_BYTE, - imageDataRGBA); + imageDataRGBAPremul); glutils::SetTexture2DSamplingParams(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return adoptImageTexture(width, height, textureID);
diff --git a/renderer/src/metal/render_context_metal_impl.mm b/renderer/src/metal/render_context_metal_impl.mm index b387fd7..98ef812 100644 --- a/renderer/src/metal/render_context_metal_impl.mm +++ b/renderer/src/metal/render_context_metal_impl.mm
@@ -713,7 +713,7 @@ uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) : + const uint8_t imageDataRGBAPremul[]) : Texture(width, height) { // Create the texture. @@ -730,7 +730,7 @@ MTLRegion region = MTLRegionMake2D(0, 0, width, height); [m_texture replaceRegion:region mipmapLevel:0 - withBytes:imageDataRGBA + withBytes:imageDataRGBAPremul bytesPerRow:width * 4]; } @@ -758,10 +758,10 @@ uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) + const uint8_t imageDataRGBAPremul[]) { return make_rcp<TextureMetalImpl>( - m_gpu, width, height, mipLevelCount, imageDataRGBA); + m_gpu, width, height, mipLevelCount, imageDataRGBAPremul); } std::unique_ptr<BufferRing> RenderContextMetalImpl::makeUniformBufferRing(
diff --git a/renderer/src/render_context_helper_impl.cpp b/renderer/src/render_context_helper_impl.cpp index ec2ae25..bd6d608 100644 --- a/renderer/src/render_context_helper_impl.cpp +++ b/renderer/src/render_context_helper_impl.cpp
@@ -21,9 +21,9 @@ if (bitmap) { // For now, RenderContextImpl::makeImageTexture() only accepts RGBA. - if (bitmap->pixelFormat() != Bitmap::PixelFormat::RGBA) + if (bitmap->pixelFormat() != Bitmap::PixelFormat::RGBAPremul) { - bitmap->pixelFormat(Bitmap::PixelFormat::RGBA); + bitmap->pixelFormat(Bitmap::PixelFormat::RGBAPremul); } uint32_t width = bitmap->width(); uint32_t height = bitmap->height();
diff --git a/renderer/src/shaders/advanced_blend.glsl b/renderer/src/shaders/advanced_blend.glsl index 7978f62..9310224 100644 --- a/renderer/src/shaders/advanced_blend.glsl +++ b/renderer/src/shaders/advanced_blend.glsl
@@ -142,14 +142,6 @@ } #endif // ENABLE_HSL_BLEND_MODES -INLINE half3 unmultiply_rgb(half4 premul) -{ - // We *could* return preciesly 1 when premul.rgb == premul.a, but we can - // also be approximate here. The blend modes that depend on this exact level - // of precision (colordodge and colorburn) account for it with dstPremul. - return premul.rgb * (premul.a != .0 ? 1. / premul.a : .0); -} - // The advanced blend coefficients are generated from un-multiplied RGB values, // and control the look of each blend mode. half3 advanced_blend_coeffs(half3 src, half4 dstPremul, ushort mode) @@ -273,16 +265,13 @@ return coeffs; } -// Returns an intermediate RGB color that won't produce the desired blend mode -// until *AFTER* being blended into the framebuffer with hardware coefficients -// of [SRC_ALPHA, ONE_MINUS_SRC_ALPHA]. +// Performs the given advanced blend operation with a solid RGB src color (no +// srcAlpha). // -// NOTE: Alpha follows standard src-over rules in all blend modes, so the shader -// can just output the paint's alpha value, unmodified, directly to the blend -// unit. -INLINE half3 advanced_color_blend_pre_src_over(half3 src, - half4 dstPremul, - ushort mode) +// NOTE: This method is sufficient for all blending because alpha in the src +// can be accounted for afterward using a standard src-over blend operation. +// (See advanced_blend().) +INLINE half3 advanced_color_blend(half3 src, half4 dstPremul, ushort mode) { // The weighting functions p0, p1, and p2 are defined as follows: // @@ -290,27 +279,22 @@ // p1(As,Ad) = As*(1 - Ad) // p2(As,Ad) = Ad*(1 - As) // + // Since srcAlpha (As) == 1, this simplifies to: + // + // p0(As,Ad) = Ad + // p1(As,Ad) = (1 - Ad) + // p2(As,Ad) = 0 + // // Blending is performed according to the following equations: // - // R = coeffs(Rs',Rd')*p0(As,Ad) + Y*Rs'*p1(As,Ad) + Z*Rd'*p2(As,Ad) - // G = coeffs(Gs',Gd')*p0(As,Ad) + Y*Gs'*p1(As,Ad) + Z*Gd'*p2(As,Ad) - // B = coeffs(Bs',Bd')*p0(As,Ad) + Y*Bs'*p1(As,Ad) + Z*Bd'*p2(As,Ad) - // A = X*p0(As,Ad) + Y*p1(As,Ad) + Z*p2(As,Ad) + // R = coeffs(Rs',Rd')*p0 + Y*Rs'*p1 + Z*Rd'*p2 + // G = coeffs(Gs',Gd')*p0 + Y*Gs'*p1 + Z*Gd'*p2 + // B = coeffs(Bs',Bd')*p0 + Y*Bs'*p1 + Z*Bd'*p2 + // A = X*p0 + Y*p1 + Z*p2 // // NOTE: (X,Y,Z) always == 1, so it is ignored in this implementation. // Also, since (X,Y,Z) == 1, alpha simplifies to standard src-over // rules: A = Ad * (1 - As) + As - // - // Since we are returning an intermediate value for use *BEFORE* src-over - // blend, we make two modifications: - // - // 1) To cancel the effect of the upcoming src-over blend, we subtract - // "RGBd * (1 - As)" from the final RGB values. This cancels out p2 - // entirely. - // - // 2) Since the caller is expected to premultiply alpha, don't multiply - // p0 or p1 by As. - // half3 coeffs = advanced_blend_coeffs(src, dstPremul, mode); half2 p = make_half2(dstPremul.a, 1. - dstPremul.a); // p2 cancelled to 0. return MUL(make_half2x3(coeffs, src), p); @@ -318,9 +302,12 @@ INLINE half4 advanced_blend(half4 src, half4 dstPremul, ushort mode) { - src.rgb = advanced_color_blend_pre_src_over(src.rgb, dstPremul, mode); + // First blend without srcAlpha. + src.rgb = advanced_color_blend(src.rgb, dstPremul, mode); + // All advanced blend operations are structured such that alpha in the src + // can be accounted for afterward using a standard src-over blend operation. src.rgb *= src.a; - return src + dstPremul * (1. - src.a); + return dstPremul * (1. - src.a) + src; } #endif // ENABLE_ADVANCED_BLEND
diff --git a/renderer/src/shaders/atomic_draw.glsl b/renderer/src/shaders/atomic_draw.glsl index 27e1836..c24946f 100644 --- a/renderer/src/shaders/atomic_draw.glsl +++ b/renderer/src/shaders/atomic_draw.glsl
@@ -488,9 +488,8 @@ (blendMode = cast_uint_to_ushort((paintData.x >> 4) & 0xfu)) != 0u) { half4 dstColorPremul = PLS_LOAD4F(colorBuffer); - fragColorOut.rgb = advanced_color_blend_pre_src_over(fragColorOut.rgb, - dstColorPremul, - blendMode); + fragColorOut.rgb = + advanced_color_blend(fragColorOut.rgb, dstColorPremul, blendMode); } #endif // !FIXED_FUNCTION_COLOR_OUTPUT && ENABLE_ADVANCED_BLEND @@ -789,8 +788,6 @@ apply_clip(imageDrawUniforms.clipID, clipData, imageCoverage); } #endif // ENABLE_CLIPPING - imageColor.a *= - imageCoverage * cast_float_to_half(imageDrawUniforms.opacity); // Prepare imageColor for premultiplied src-over blending. #if !defined(@FIXED_FUNCTION_COLOR_OUTPUT) && defined(@ENABLE_ADVANCED_BLEND) @@ -801,16 +798,14 @@ PLS_LOAD4F(colorBuffer) * (1. - fragColorOut.a) + fragColorOut; // Calculate the imageColor to emit *BEFORE* src-over blending, such // that the post-src-over-blend result is equivalent to the blendMode. - imageColor.rgb = advanced_color_blend_pre_src_over( - imageColor.rgb, - dstColorPremul, - cast_uint_to_ushort(imageDrawUniforms.blendMode)); + imageColor.rgb = advanced_color_blend( + unmultiply_rgb(imageColor), + dstColorPremul, + cast_uint_to_ushort(imageDrawUniforms.blendMode)) * + imageColor.a; } #endif // !FIXED_FUNCTION_COLOR_OUTPUT && ENABLE_ADVANCED_BLEND - - // Image draws use a premultiplied blend state; premultiply alpha here in - // the shader. - imageColor.rgb *= imageColor.a; + imageColor *= imageCoverage * cast_float_to_half(imageDrawUniforms.opacity); // Leverage the property that premultiplied src-over blending is associative // and blend the imageColor and fragColorOut before passing them on to the
diff --git a/renderer/src/shaders/common.glsl b/renderer/src/shaders/common.glsl index 08ede1f..dc247c1 100644 --- a/renderer/src/shaders/common.glsl +++ b/renderer/src/shaders/common.glsl
@@ -175,6 +175,14 @@ return make_half4(color.rgb * color.a, color.a); } +INLINE half3 unmultiply_rgb(half4 premul) +{ + // We *could* return preciesly 1 when premul.rgb == premul.a, but we can + // also be approximate here. The blend modes that depend on this exact level + // of precision (colordodge and colorburn) account for it with dstPremul. + return premul.rgb * (premul.a != .0 ? 1. / premul.a : .0); +} + INLINE half min_value(half4 min4) { half2 min2 = min(min4.xy, min4.zw);
diff --git a/renderer/src/shaders/draw_image_mesh.glsl b/renderer/src/shaders/draw_image_mesh.glsl index 48388d0..53c5ee1 100644 --- a/renderer/src/shaders/draw_image_mesh.glsl +++ b/renderer/src/shaders/draw_image_mesh.glsl
@@ -146,22 +146,19 @@ #endif // Blend with the framebuffer color. - color.a *= imageDrawUniforms.opacity * coverage; half4 dstColorPremul = PLS_LOAD4F(colorBuffer); #ifdef @ENABLE_ADVANCED_BLEND if (@ENABLE_ADVANCED_BLEND && imageDrawUniforms.blendMode != BLEND_SRC_OVER) { - color = - advanced_blend(color, - dstColorPremul, - cast_uint_to_ushort(imageDrawUniforms.blendMode)); + color.rgb = advanced_color_blend( + unmultiply_rgb(color), + dstColorPremul, + cast_uint_to_ushort(imageDrawUniforms.blendMode)) * + color.a; } - else #endif - { - color.rgb *= color.a; - color = color + dstColorPremul * (1. - color.a); - } + color *= imageDrawUniforms.opacity * coverage; + color += dstColorPremul * (1. - color.a); PLS_STORE4F(colorBuffer, color); PLS_PRESERVE_UI(clipBuffer); @@ -178,22 +175,19 @@ { VARYING_UNPACK(v_texCoord, float2); - half4 color = TEXTURE_SAMPLE(@imageTexture, imageSampler, v_texCoord); - color.a *= imageDrawUniforms.opacity; + half4 color = TEXTURE_SAMPLE(@imageTexture, imageSampler, v_texCoord) * + imageDrawUniforms.opacity; #ifdef @ENABLE_ADVANCED_BLEND if (@ENABLE_ADVANCED_BLEND) { half4 dstColorPremul = TEXEL_FETCH(@dstColorTexture, int2(floor(_fragCoord.xy))); + color.rgb = unmultiply_rgb(color); color = advanced_blend(color, dstColorPremul, imageDrawUniforms.blendMode); } - else #endif // !ENABLE_ADVANCED_BLEND - { - color = premultiply(color); - } EMIT_FRAG_DATA(color); }
diff --git a/renderer/src/shaders/draw_path.glsl b/renderer/src/shaders/draw_path.glsl index b026cad..4d9f06d 100644 --- a/renderer/src/shaders/draw_path.glsl +++ b/renderer/src/shaders/draw_path.glsl
@@ -2,6 +2,17 @@ * Copyright 2022 Rive */ +#ifdef @ENABLE_ADVANCED_BLEND +// If advanced blend is enabled, we generate unmultiplied paint colors in the +// shader. Otherwise we would have to just turn around and unmultiply them in +// order to run the blend equation. +#define GENERATE_PREMULTIPLIED_PAINT_COLORS !@ENABLE_ADVANCED_BLEND +#else +// As long as advanced blend is not enabled, it's more efficient for the shader +// to generate premultiplied paint colors from the start. +#define GENERATE_PREMULTIPLIED_PAINT_COLORS true +#endif + #ifdef @VERTEX ATTR_BLOCK_BEGIN(Attrs) #ifdef @DRAW_INTERIOR_TRIANGLES @@ -194,6 +205,8 @@ if (paintType == SOLID_COLOR_PAINT_TYPE) { half4 color = unpackUnorm4x8(paintData.y); + if (GENERATE_PREMULTIPLIED_PAINT_COLORS) + color.rgb *= color.a; v_paint = float4(color); } #ifdef @ENABLE_CLIPPING @@ -314,11 +327,19 @@ FRAG_STORAGE_BUFFER_BLOCK_BEGIN FRAG_STORAGE_BUFFER_BLOCK_END -INLINE half4 find_paint_color(float4 paint FRAGMENT_CONTEXT_DECL) +INLINE half4 find_paint_color(float4 paint, + float coverage FRAGMENT_CONTEXT_DECL) { + half4 color; if (paint.a >= .0) // Is the paint a solid color? { - return cast_float4_to_half4(paint); + // The vertex shader will have premultiplied 'paint' (or not) based on + // GENERATE_PREMULTIPLIED_PAINT_COLORS. + color = cast_float4_to_half4(paint); + if (GENERATE_PREMULTIPLIED_PAINT_COLORS) + color *= coverage; + else + color.a *= coverage; } else if (paint.a > -1.) // Is paint is a gradient (linear or radial)? { @@ -332,22 +353,28 @@ : /*two texels*/ (1. / GRAD_TEXTURE_WIDTH) * t + span; float row = -paint.a; // Our gradient texture is not mipmapped. Issue a texture-sample that - // explicitly does not find derivatives for LOD computation (by - // specifying derivatives directly). - return TEXTURE_SAMPLE_LOD(@gradTexture, - gradSampler, - float2(x, row), - .0); + // explicitly does not find derivatives for LOD computation. + color = + TEXTURE_SAMPLE_LOD(@gradTexture, gradSampler, float2(x, row), .0); + color.a *= coverage; + // Gradients are always unmultiplied so we don't lose color data while + // doing the hardware filter. + if (GENERATE_PREMULTIPLIED_PAINT_COLORS) + color.rgb *= color.a; } else // The paint is an image. { half lod = -paint.a - 2.; - half4 color = - TEXTURE_SAMPLE_LOD(@imageTexture, imageSampler, paint.rg, lod); - half opacity = paint.b; - color.a *= opacity; - return color; + color = TEXTURE_SAMPLE_LOD(@imageTexture, imageSampler, paint.rg, lod); + half opacity = paint.b * coverage; + // Images are always premultiplied so the (transparent) background color + // doesn't bleed into the edges during the hardware filter. + if (GENERATE_PREMULTIPLIED_PAINT_COLORS) + color *= opacity; + else + color = make_half4(unmultiply_rgb(color), color.a * opacity); } + return color; } #ifndef @RENDER_MODE_MSAA @@ -557,8 +584,8 @@ } #endif // ENABLE_CLIP_RECT - half4 color = find_paint_color(v_paint FRAGMENT_CONTEXT_UNPACK); - color.a *= coverage; + half4 color = + find_paint_color(v_paint, coverage FRAGMENT_CONTEXT_UNPACK); half4 dstColorPremul; #ifdef @ATLAS_BLIT @@ -588,17 +615,22 @@ // Blend with the framebuffer color. #ifdef @ENABLE_ADVANCED_BLEND - if (@ENABLE_ADVANCED_BLEND && - v_blendMode != cast_uint_to_half(BLEND_SRC_OVER)) + if (@ENABLE_ADVANCED_BLEND) { - color.rgb = advanced_color_blend_pre_src_over( - color.rgb, - dstColorPremul, - cast_half_to_ushort(v_blendMode)); + // GENERATE_PREMULTIPLIED_PAINT_COLORS is false in this case because + // advanced blend needs unmultiplied colors. + if (v_blendMode != cast_uint_to_half(BLEND_SRC_OVER)) + { + color.rgb = + advanced_color_blend(color.rgb, + dstColorPremul, + cast_half_to_ushort(v_blendMode)); + } + // Premultiply alpha now. + color.rgb *= color.a; } #endif - color.rgb *= color.a; - color = color + dstColorPremul * (1. - color.a); + color += dstColorPremul * (1. - color.a); PLS_STORE4F(colorBuffer, color); PLS_PRESERVE_UI(clipBuffer); @@ -624,27 +656,28 @@ VARYING_UNPACK(v_blendMode, half); #endif - half4 color = find_paint_color(v_paint); + half coverage = #ifdef @ATLAS_BLIT - color.a *= filter_feather_atlas( - v_atlasCoord, - uniforms.atlasTextureInverseSize TEXTURE_CONTEXT_FORWARD); + filter_feather_atlas( + v_atlasCoord, + uniforms.atlasTextureInverseSize TEXTURE_CONTEXT_FORWARD); +#else + 1.; #endif + half4 color = find_paint_color(v_paint, coverage FRAGMENT_CONTEXT_UNPACK); #ifdef @ENABLE_ADVANCED_BLEND if (@ENABLE_ADVANCED_BLEND) { + // GENERATE_PREMULTIPLIED_PAINT_COLORS is false in this case because + // advanced blend needs unmultiplied colors. half4 dstColorPremul = TEXEL_FETCH(@dstColorTexture, int2(floor(_fragCoord.xy))); color = advanced_blend(color, dstColorPremul, cast_half_to_ushort(v_blendMode)); } - else #endif // ENABLE_ADVANCED_BLEND - { - color = premultiply(color); - } EMIT_FRAG_DATA(color); }
diff --git a/renderer/src/vulkan/render_context_vulkan_impl.cpp b/renderer/src/vulkan/render_context_vulkan_impl.cpp index eb35a2f..d8dfcbc 100644 --- a/renderer/src/vulkan/render_context_vulkan_impl.cpp +++ b/renderer/src/vulkan/render_context_vulkan_impl.cpp
@@ -447,7 +447,7 @@ uint32_t height, uint32_t mipLevelCount, TextureFormat format, - const void* imageData) : + const void* imageDataRGBAPremul) : Texture(width, height), m_vk(std::move(vk)), m_texture(m_vk->makeTexture({ @@ -466,7 +466,7 @@ vkutil::Mappability::writeOnly)) { memcpy(m_imageUploadBuffer->contents(), - imageData, + imageDataRGBAPremul, m_imageUploadBuffer->info().size); m_imageUploadBuffer->flushContents(); } @@ -635,10 +635,11 @@ auto bitmap = Bitmap::decode(encodedBytes.data(), encodedBytes.size()); if (bitmap) { - // For now, RenderContextImpl::makeImageTexture() only accepts RGBA. - if (bitmap->pixelFormat() != Bitmap::PixelFormat::RGBA) + // For now, RenderContextImpl::makeImageTexture() only accepts + // RGBAPremul. + if (bitmap->pixelFormat() != Bitmap::PixelFormat::RGBAPremul) { - bitmap->pixelFormat(Bitmap::PixelFormat::RGBA); + bitmap->pixelFormat(Bitmap::PixelFormat::RGBAPremul); } uint32_t width = bitmap->width(); uint32_t height = bitmap->height();
diff --git a/renderer/src/webgpu/render_context_webgpu_impl.cpp b/renderer/src/webgpu/render_context_webgpu_impl.cpp index 53d8e56..6f9594a 100644 --- a/renderer/src/webgpu/render_context_webgpu_impl.cpp +++ b/renderer/src/webgpu/render_context_webgpu_impl.cpp
@@ -1711,7 +1711,7 @@ uint32_t width, uint32_t height, uint32_t mipLevelCount, - const uint8_t imageDataRGBA[]) + const uint8_t imageDataRGBAPremul[]) { wgpu::TextureDescriptor textureDesc = { .usage = @@ -1736,7 +1736,7 @@ width * 4, width, height, - imageDataRGBA, + imageDataRGBAPremul, height * width * 4); if (mipLevelCount > 1)
diff --git a/tests/unit_tests/renderer/advanced_blend_test.cpp b/tests/unit_tests/renderer/advanced_blend_test.cpp index 8a17e86..91c8b6b 100644 --- a/tests/unit_tests/renderer/advanced_blend_test.cpp +++ b/tests/unit_tests/renderer/advanced_blend_test.cpp
@@ -12,6 +12,20 @@ { #include "cpp.glsl" #include "generated/shaders/constants.minified.glsl" +#if 0 +// "common.glsl" is currently too complicated to compile for C++. If we really +// need it we can make it work, but for now it works to just declare our own +// version of unmultiply_rgb. +#include "generated/shaders/common.minified.glsl" +#else +static half3 unmultiply_rgb(half4 premul) +{ + // We *could* return preciesly 1 when premul.rgb == premul.a, but we can + // also be approximate here. The blend modes that depend on this exact level + // of precision (colordodge and colorburn) account for it with dstPremul. + return premul.rgb * (premul.a != .0 ? 1. / premul.a : .0); +} +#endif #define FRAGMENT #define ENABLE_ADVANCED_BLEND true #define ENABLE_HSL_BLEND_MODES true
diff --git a/tests/unit_tests/runtime/simd_test.cpp b/tests/unit_tests/runtime/simd_test.cpp index 45f21bc..b16b933 100644 --- a/tests/unit_tests/runtime/simd_test.cpp +++ b/tests/unit_tests/runtime/simd_test.cpp
@@ -571,6 +571,18 @@ CHECK_ALL((simd::sqrt(vec<3>{kInf, 0, 1}) == vec<3>{kInf, 0, 1})); } +// Check simd::div255. +TEST_CASE("div255", "[simd]") +{ + for (uint32_t i = 0; i < 255 * 255; i += 8) + { + uint16x8 x = + static_cast<uint16_t>(i) + uint16x8{0, 1, 2, 3, 4, 5, 6, 7}; + x = simd::min(x, uint16x8(255 * 255)); + CHECK_ALL(simd::div255(x) == (x + 127) / 255); + } +} + static bool check_fast_acos(float x, float fast_acos_x) { float acosf_x = acosf(x);