• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/gpu/ganesh/SkGr.h"
9 
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkBitmap.h"
12 #include "include/core/SkColorFilter.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkPixelRef.h"
18 #include "include/core/SkPoint.h"
19 #include "include/core/SkRect.h"
20 #include "include/core/SkSize.h"
21 #include "include/core/SkSurfaceProps.h"
22 #include "include/effects/SkRuntimeEffect.h"
23 #include "include/gpu/GrBackendSurface.h"
24 #include "include/gpu/GrRecordingContext.h"
25 #include "include/private/SkIDChangeListener.h"
26 #include "include/private/base/SkTPin.h"
27 #include "include/private/gpu/ganesh/GrTypesPriv.h"
28 #include "src/core/SkBlendModePriv.h"
29 #include "src/core/SkBlenderBase.h"
30 #include "src/core/SkColorFilterBase.h"
31 #include "src/core/SkMaskFilterBase.h"
32 #include "src/core/SkMessageBus.h"
33 #include "src/core/SkPaintPriv.h"
34 #include "src/core/SkRuntimeEffectPriv.h"
35 #include "src/gpu/ResourceKey.h"
36 #include "src/gpu/Swizzle.h"
37 #include "src/gpu/ganesh/GrCaps.h"
38 #include "src/gpu/ganesh/GrColorInfo.h"
39 #include "src/gpu/ganesh/GrColorSpaceXform.h"
40 #include "src/gpu/ganesh/GrFPArgs.h"
41 #include "src/gpu/ganesh/GrFragmentProcessor.h"
42 #include "src/gpu/ganesh/GrPaint.h"
43 #include "src/gpu/ganesh/GrProxyProvider.h"
44 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
45 #include "src/gpu/ganesh/GrSurfaceProxy.h"
46 #include "src/gpu/ganesh/GrSurfaceProxyView.h"
47 #include "src/gpu/ganesh/GrTextureProxy.h"
48 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
49 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
50 #include "src/shaders/SkShaderBase.h"
51 
52 #include <optional>
53 #include <utility>
54 
55 class SkBlender;
56 class SkColorSpace;
57 enum SkColorType : int;
58 
GrMakeKeyFromImageID(skgpu::UniqueKey * key,uint32_t imageID,const SkIRect & imageBounds)59 void GrMakeKeyFromImageID(skgpu::UniqueKey* key, uint32_t imageID, const SkIRect& imageBounds) {
60     SkASSERT(key);
61     SkASSERT(imageID);
62     SkASSERT(!imageBounds.isEmpty());
63     static const skgpu::UniqueKey::Domain kImageIDDomain = skgpu::UniqueKey::GenerateDomain();
64     skgpu::UniqueKey::Builder builder(key, kImageIDDomain, 5, "Image");
65     builder[0] = imageID;
66     builder[1] = imageBounds.fLeft;
67     builder[2] = imageBounds.fTop;
68     builder[3] = imageBounds.fRight;
69     builder[4] = imageBounds.fBottom;
70 }
71 
72 ////////////////////////////////////////////////////////////////////////////////
73 
GrMakeUniqueKeyInvalidationListener(skgpu::UniqueKey * key,uint32_t contextID)74 sk_sp<SkIDChangeListener> GrMakeUniqueKeyInvalidationListener(skgpu::UniqueKey* key,
75                                                               uint32_t contextID) {
76     class Listener : public SkIDChangeListener {
77     public:
78         Listener(const skgpu::UniqueKey& key, uint32_t contextUniqueID)
79                 : fMsg(key, contextUniqueID) {}
80 
81         void changed() override {
82             SkMessageBus<skgpu::UniqueKeyInvalidatedMessage, uint32_t>::Post(fMsg);
83         }
84 
85     private:
86         skgpu::UniqueKeyInvalidatedMessage fMsg;
87     };
88 
89     auto listener = sk_make_sp<Listener>(*key, contextID);
90 
91     // We stick a SkData on the key that calls invalidateListener in its destructor.
92     auto invalidateListener = [](const void* ptr, void* /*context*/) {
93         auto listener = reinterpret_cast<const sk_sp<Listener>*>(ptr);
94         (*listener)->markShouldDeregister();
95         delete listener;
96     };
97     auto data = SkData::MakeWithProc(new sk_sp<Listener>(listener),
98                                      sizeof(sk_sp<Listener>),
99                                      invalidateListener,
100                                      nullptr);
101     SkASSERT(!key->getCustomData());
102     key->setCustomData(std::move(data));
103     return std::move(listener);
104 }
105 
GrCopyBaseMipMapToTextureProxy(GrRecordingContext * ctx,sk_sp<GrSurfaceProxy> baseProxy,GrSurfaceOrigin origin,std::string_view label,skgpu::Budgeted budgeted)106 sk_sp<GrSurfaceProxy> GrCopyBaseMipMapToTextureProxy(GrRecordingContext* ctx,
107                                                      sk_sp<GrSurfaceProxy> baseProxy,
108                                                      GrSurfaceOrigin origin,
109                                                      std::string_view label,
110                                                      skgpu::Budgeted budgeted) {
111     SkASSERT(baseProxy);
112 
113     // We don't allow this for promise proxies i.e. if they need mips they need to give them
114     // to us upfront.
115     if (baseProxy->isPromiseProxy()) {
116         return nullptr;
117     }
118     if (!ctx->priv().caps()->isFormatCopyable(baseProxy->backendFormat())) {
119         return nullptr;
120     }
121     auto copy = GrSurfaceProxy::Copy(ctx, std::move(baseProxy), origin, GrMipmapped::kYes,
122                                      SkBackingFit::kExact, budgeted, label);
123     if (!copy) {
124         return nullptr;
125     }
126     SkASSERT(copy->asTextureProxy());
127     return copy;
128 }
129 
GrCopyBaseMipMapToView(GrRecordingContext * context,GrSurfaceProxyView src,skgpu::Budgeted budgeted)130 GrSurfaceProxyView GrCopyBaseMipMapToView(GrRecordingContext* context,
131                                           GrSurfaceProxyView src,
132                                           skgpu::Budgeted budgeted) {
133     auto origin = src.origin();
134     auto swizzle = src.swizzle();
135     auto proxy = src.refProxy();
136     return {GrCopyBaseMipMapToTextureProxy(
137                     context, proxy, origin, /*label=*/"CopyBaseMipMapToView", budgeted),
138             origin,
139             swizzle};
140 }
141 
adjust_mipmapped(GrMipmapped mipmapped,const SkBitmap & bitmap,const GrCaps * caps)142 static GrMipmapped adjust_mipmapped(GrMipmapped mipmapped,
143                                     const SkBitmap& bitmap,
144                                     const GrCaps* caps) {
145     if (!caps->mipmapSupport() || bitmap.dimensions().area() <= 1) {
146         return GrMipmapped::kNo;
147     }
148     return mipmapped;
149 }
150 
choose_bmp_texture_colortype(const GrCaps * caps,const SkBitmap & bitmap)151 static GrColorType choose_bmp_texture_colortype(const GrCaps* caps, const SkBitmap& bitmap) {
152     GrColorType ct = SkColorTypeToGrColorType(bitmap.info().colorType());
153     if (caps->getDefaultBackendFormat(ct, GrRenderable::kNo).isValid()) {
154         return ct;
155     }
156     return GrColorType::kRGBA_8888;
157 }
158 
make_bmp_proxy(GrProxyProvider * proxyProvider,const SkBitmap & bitmap,GrColorType ct,GrMipmapped mipmapped,SkBackingFit fit,skgpu::Budgeted budgeted)159 static sk_sp<GrTextureProxy> make_bmp_proxy(GrProxyProvider* proxyProvider,
160                                             const SkBitmap& bitmap,
161                                             GrColorType ct,
162                                             GrMipmapped mipmapped,
163                                             SkBackingFit fit,
164                                             skgpu::Budgeted budgeted) {
165     SkBitmap bmpToUpload;
166     if (ct != SkColorTypeToGrColorType(bitmap.info().colorType())) {
167         SkColorType skCT = GrColorTypeToSkColorType(ct);
168         if (!bmpToUpload.tryAllocPixels(bitmap.info().makeColorType(skCT)) ||
169             !bitmap.readPixels(bmpToUpload.pixmap())) {
170             return {};
171         }
172         bmpToUpload.setImmutable();
173     } else {
174         bmpToUpload = bitmap;
175     }
176     auto proxy = proxyProvider->createProxyFromBitmap(bmpToUpload, mipmapped, fit, budgeted);
177     SkASSERT(!proxy || mipmapped == GrMipmapped::kNo || proxy->mipmapped() == GrMipmapped::kYes);
178     return proxy;
179 }
180 
181 std::tuple<GrSurfaceProxyView, GrColorType>
GrMakeCachedBitmapProxyView(GrRecordingContext * rContext,const SkBitmap & bitmap,std::string_view label,GrMipmapped mipmapped)182 GrMakeCachedBitmapProxyView(GrRecordingContext* rContext,
183                             const SkBitmap& bitmap,
184                             std::string_view label,
185                             GrMipmapped mipmapped) {
186     if (!bitmap.peekPixels(nullptr)) {
187         return {};
188     }
189 
190     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
191     const GrCaps* caps = rContext->priv().caps();
192 
193     skgpu::UniqueKey key;
194     SkIPoint origin = bitmap.pixelRefOrigin();
195     SkIRect subset = SkIRect::MakePtSize(origin, bitmap.dimensions());
196     GrMakeKeyFromImageID(&key, bitmap.pixelRef()->getGenerationID(), subset);
197 
198     mipmapped = adjust_mipmapped(mipmapped, bitmap, caps);
199     GrColorType ct = choose_bmp_texture_colortype(caps, bitmap);
200 
201     auto installKey = [&](GrTextureProxy* proxy) {
202         auto listener = GrMakeUniqueKeyInvalidationListener(&key, proxyProvider->contextID());
203         bitmap.pixelRef()->addGenIDChangeListener(std::move(listener));
204         proxyProvider->assignUniqueKeyToProxy(key, proxy);
205     };
206 
207     sk_sp<GrTextureProxy> proxy = proxyProvider->findOrCreateProxyByUniqueKey(key);
208     if (!proxy) {
209         proxy = make_bmp_proxy(
210                 proxyProvider, bitmap, ct, mipmapped, SkBackingFit::kExact, skgpu::Budgeted::kYes);
211         if (!proxy) {
212             return {};
213         }
214         SkASSERT(mipmapped == GrMipmapped::kNo || proxy->mipmapped() == GrMipmapped::kYes);
215         installKey(proxy.get());
216     }
217 
218     skgpu::Swizzle swizzle = caps->getReadSwizzle(proxy->backendFormat(), ct);
219     if (mipmapped == GrMipmapped::kNo || proxy->mipmapped() == GrMipmapped::kYes) {
220         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
221     }
222 
223     // We need a mipped proxy, but we found a proxy earlier that wasn't mipped. Thus we generate
224     // a new mipped surface and copy the original proxy into the base layer. We will then let
225     // the gpu generate the rest of the mips.
226     auto mippedProxy = GrCopyBaseMipMapToTextureProxy(
227             rContext, proxy, kTopLeft_GrSurfaceOrigin, /*label=*/"MakeCachedBitmapProxyView");
228     if (!mippedProxy) {
229         // We failed to make a mipped proxy with the base copied into it. This could have
230         // been from failure to make the proxy or failure to do the copy. Thus we will fall
231         // back to just using the non mipped proxy; See skbug.com/7094.
232         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
233     }
234     // In this case we are stealing the key from the original proxy which should only happen
235     // when we have just generated mipmaps for an originally unmipped proxy/texture. This
236     // means that all future uses of the key will access the mipmapped version. The texture
237     // backing the unmipped version will remain in the resource cache until the last texture
238     // proxy referencing it is deleted at which time it too will be deleted or recycled.
239     SkASSERT(proxy->getUniqueKey() == key);
240     proxyProvider->removeUniqueKeyFromProxy(proxy.get());
241     installKey(mippedProxy->asTextureProxy());
242     return {{std::move(mippedProxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
243 }
244 
GrMakeUncachedBitmapProxyView(GrRecordingContext * rContext,const SkBitmap & bitmap,GrMipmapped mipmapped,SkBackingFit fit,skgpu::Budgeted budgeted)245 std::tuple<GrSurfaceProxyView, GrColorType> GrMakeUncachedBitmapProxyView(
246         GrRecordingContext* rContext,
247         const SkBitmap& bitmap,
248         GrMipmapped mipmapped,
249         SkBackingFit fit,
250         skgpu::Budgeted budgeted) {
251     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
252     const GrCaps* caps = rContext->priv().caps();
253 
254     mipmapped = adjust_mipmapped(mipmapped, bitmap, caps);
255     GrColorType ct = choose_bmp_texture_colortype(caps, bitmap);
256 
257     if (auto proxy = make_bmp_proxy(proxyProvider, bitmap, ct, mipmapped, fit, budgeted)) {
258         skgpu::Swizzle swizzle = caps->getReadSwizzle(proxy->backendFormat(), ct);
259         SkASSERT(mipmapped == GrMipmapped::kNo || proxy->mipmapped() == GrMipmapped::kYes);
260         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
261     }
262     return {};
263 }
264 ///////////////////////////////////////////////////////////////////////////////
265 
SkColorToPMColor4f(SkColor c,const GrColorInfo & colorInfo)266 SkPMColor4f SkColorToPMColor4f(SkColor c, const GrColorInfo& colorInfo) {
267     SkColor4f color = SkColor4f::FromColor(c);
268     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
269         color = xform->apply(color);
270     }
271     return color.premul();
272 }
273 
SkColor4fPrepForDst(SkColor4f color,const GrColorInfo & colorInfo)274 SkColor4f SkColor4fPrepForDst(SkColor4f color, const GrColorInfo& colorInfo) {
275     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
276         color = xform->apply(color);
277     }
278     return color;
279 }
280 
281 ///////////////////////////////////////////////////////////////////////////////
282 
blender_requires_shader(const SkBlender * blender)283 static inline bool blender_requires_shader(const SkBlender* blender) {
284     SkASSERT(blender);
285     std::optional<SkBlendMode> mode = as_BB(blender)->asBlendMode();
286     return !mode.has_value() || *mode != SkBlendMode::kDst;
287 }
288 
289 #ifndef SK_IGNORE_GPU_DITHER
dither_range_for_config(GrColorType dstColorType)290 static inline float dither_range_for_config(GrColorType dstColorType) {
291     // We use 1 / (2^bitdepth-1) as the range since each channel can hold 2^bitdepth values
292     switch (dstColorType) {
293         // 4 bit
294         case GrColorType::kABGR_4444:
295         case GrColorType::kARGB_4444:
296         case GrColorType::kBGRA_4444:
297             return 1 / 15.f;
298         // 6 bit
299         case GrColorType::kBGR_565:
300             return 1 / 63.f;
301         // 8 bit
302         case GrColorType::kUnknown:
303         case GrColorType::kAlpha_8:
304         case GrColorType::kAlpha_8xxx:
305         case GrColorType::kGray_8:
306         case GrColorType::kGrayAlpha_88:
307         case GrColorType::kGray_8xxx:
308         case GrColorType::kR_8:
309         case GrColorType::kR_8xxx:
310         case GrColorType::kRG_88:
311         case GrColorType::kRGB_888:
312         case GrColorType::kRGB_888x:
313         case GrColorType::kRGBA_8888:
314         case GrColorType::kRGBA_8888_SRGB:
315         case GrColorType::kBGRA_8888:
316             return 1 / 255.f;
317         // 10 bit
318         case GrColorType::kRGBA_1010102:
319         case GrColorType::kBGRA_1010102:
320             return 1 / 1023.f;
321         // 16 bit
322         case GrColorType::kAlpha_16:
323         case GrColorType::kR_16:
324         case GrColorType::kRG_1616:
325         case GrColorType::kRGBA_16161616:
326             return 1 / 32767.f;
327         // Half
328         case GrColorType::kAlpha_F16:
329         case GrColorType::kGray_F16:
330         case GrColorType::kR_F16:
331         case GrColorType::kRG_F16:
332         case GrColorType::kRGBA_F16:
333         case GrColorType::kRGBA_F16_Clamped:
334         // Float
335         case GrColorType::kAlpha_F32xxx:
336         case GrColorType::kRGBA_F32:
337             return 0.f; // no dithering
338     }
339     SkUNREACHABLE;
340 }
341 
make_dither_lut()342 static SkBitmap make_dither_lut() {
343     static constexpr struct DitherTable {
344         constexpr DitherTable() : data() {
345             for (int x = 0; x < 8; ++x) {
346                 for (int y = 0; y < 8; ++y) {
347                     // The computation of 'm' and 'value' is lifted from CPU backend.
348                     unsigned int m = (y & 1) << 5 | (x & 1) << 4 |
349                                      (y & 2) << 2 | (x & 2) << 1 |
350                                      (y & 4) >> 1 | (x & 4) >> 2;
351                     float value = float(m) * 1.0 / 64.0 - 63.0 / 128.0;
352                     // Bias by 0.5 to be in 0..1, mul by 255 and round to nearest int to make byte.
353                     data[y * 8 + x] = (uint8_t)((value + 0.5) * 255.f + 0.5f);
354                 }
355             }
356         }
357         uint8_t data[64];
358     } gTable;
359     SkBitmap bmp;
360     bmp.setInfo(SkImageInfo::MakeA8(8, 8));
361     bmp.setPixels(const_cast<uint8_t*>(gTable.data));
362     bmp.setImmutable();
363     return bmp;
364 }
365 
make_dither_effect(GrRecordingContext * rContext,std::unique_ptr<GrFragmentProcessor> inputFP,float range,const GrCaps * caps)366 static std::unique_ptr<GrFragmentProcessor> make_dither_effect(
367         GrRecordingContext* rContext,
368         std::unique_ptr<GrFragmentProcessor> inputFP,
369         float range,
370         const GrCaps* caps) {
371     if (range == 0 || inputFP == nullptr) {
372         return inputFP;
373     }
374 
375     if (caps->avoidDithering()) {
376         return inputFP;
377     }
378 
379     // We used to use integer math on sk_FragCoord, when supported, and a fallback using floating
380     // point (on a 4x4 rather than 8x8 grid). Now we precompute a 8x8 table in a texture because
381     // it was shown to be significantly faster on several devices. Test was done with the following
382     // running in viewer with the stats layer enabled and looking at total frame time:
383     //      SkRandom r;
384     //      for (int i = 0; i < N; ++i) {
385     //          SkColor c[2] = {r.nextU(), r.nextU()};
386     //          SkPoint pts[2] = {{r.nextRangeScalar(0, 500), r.nextRangeScalar(0, 500)},
387     //                            {r.nextRangeScalar(0, 500), r.nextRangeScalar(0, 500)}};
388     //          SkPaint p;
389     //          p.setDither(true);
390     //          p.setShader(SkGradientShader::MakeLinear(pts, c, nullptr, 2, SkTileMode::kRepeat));
391     //          canvas->drawPaint(p);
392     //      }
393     // Device            GPU             N      no dither    int math dither   table dither
394     // Linux desktop     QuadroP1000     5000   304ms        400ms (1.31x)     383ms (1.26x)
395     // TecnoSpark3Pro    PowerVRGE8320   200    299ms        820ms (2.74x)     592ms (1.98x)
396     // Pixel 4           Adreno640       500    110ms        221ms (2.01x)     214ms (1.95x)
397     // Galaxy S20 FE     Mali-G77 MP11   600    165ms        360ms (2.18x)     260ms (1.58x)
398     static const SkBitmap gLUT = make_dither_lut();
399     auto [tex, ct] = GrMakeCachedBitmapProxyView(
400             rContext, gLUT, /*label=*/"MakeDitherEffect", GrMipmapped::kNo);
401     if (!tex) {
402         return inputFP;
403     }
404     SkASSERT(ct == GrColorType::kAlpha_8);
405     GrSamplerState sampler(GrSamplerState::WrapMode::kRepeat, SkFilterMode::kNearest);
406     auto te = GrTextureEffect::Make(
407             std::move(tex), kPremul_SkAlphaType, SkMatrix::I(), sampler, *caps);
408     static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
409         "uniform half range;"
410         "uniform shader inputFP;"
411         "uniform shader table;"
412         "half4 main(float2 xy) {"
413             "half4 color = inputFP.eval(xy);"
414             "half value = table.eval(sk_FragCoord.xy).a - 0.5;" // undo the bias in the table
415             // For each color channel, add the random offset to the channel value and then clamp
416             // between 0 and alpha to keep the color premultiplied.
417             "return half4(clamp(color.rgb + value * range, 0.0, color.a), color.a);"
418         "}"
419     );
420     return GrSkSLFP::Make(effect, "Dither", /*inputFP=*/nullptr,
421                           GrSkSLFP::OptFlags::kPreservesOpaqueInput,
422                           "range", range,
423                           "inputFP", std::move(inputFP),
424                           "table", GrSkSLFP::IgnoreOptFlags(std::move(te)));
425 }
426 #endif
427 
skpaint_to_grpaint_impl(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & ctm,std::optional<std::unique_ptr<GrFragmentProcessor>> shaderFP,SkBlender * primColorBlender,const SkSurfaceProps & surfaceProps,GrPaint * grPaint)428 static inline bool skpaint_to_grpaint_impl(
429         GrRecordingContext* context,
430         const GrColorInfo& dstColorInfo,
431         const SkPaint& skPaint,
432         const SkMatrix& ctm,
433         std::optional<std::unique_ptr<GrFragmentProcessor>> shaderFP,
434         SkBlender* primColorBlender,
435         const SkSurfaceProps& surfaceProps,
436         GrPaint* grPaint) {
437     // Convert SkPaint color to 4f format in the destination color space
438     SkColor4f origColor = SkColor4fPrepForDst(skPaint.getColor4f(), dstColorInfo);
439 
440     GrFPArgs fpArgs(context, &dstColorInfo, surfaceProps);
441 
442     // Setup the initial color considering the shader, the SkPaint color, and the presence or not
443     // of per-vertex colors.
444     std::unique_ptr<GrFragmentProcessor> paintFP;
445     const bool gpProvidesShader = shaderFP.has_value() && !*shaderFP;
446     if (!primColorBlender || blender_requires_shader(primColorBlender)) {
447         if (shaderFP.has_value()) {
448             paintFP = std::move(*shaderFP);
449         } else {
450             if (const SkShaderBase* shader = as_SB(skPaint.getShader())) {
451                 paintFP = shader->asFragmentProcessor(fpArgs, SkShaderBase::MatrixRec(ctm));
452                 if (paintFP == nullptr) {
453                     return false;
454                 }
455             }
456         }
457     }
458 
459     // Set this in below cases if the output of the shader/paint-color/paint-alpha/primXfermode is
460     // a known constant value. In that case we can simply apply a color filter during this
461     // conversion without converting the color filter to a GrFragmentProcessor.
462     bool applyColorFilterToPaintColor = false;
463     if (paintFP) {
464         if (primColorBlender) {
465             // There is a blend between the primitive color and the shader color. The shader sees
466             // the opaque paint color. The shader's output is blended using the provided mode by
467             // the primitive color. The blended color is then modulated by the paint's alpha.
468 
469             // The geometry processor will insert the primitive color to start the color chain, so
470             // the GrPaint color will be ignored.
471 
472             SkPMColor4f shaderInput = origColor.makeOpaque().premul();
473             paintFP = GrFragmentProcessor::OverrideInput(std::move(paintFP), shaderInput);
474             paintFP = as_BB(primColorBlender)->asFragmentProcessor(std::move(paintFP),
475                                                                    /*dstFP=*/nullptr,
476                                                                    fpArgs);
477             if (!paintFP) {
478                 return false;
479             }
480 
481             // We can ignore origColor here - alpha is unchanged by gamma
482             float paintAlpha = skPaint.getColor4f().fA;
483             if (1.0f != paintAlpha) {
484                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
485                 // color channels. It's value should be treated as the same in ANY color space.
486                 paintFP = GrFragmentProcessor::ModulateRGBA(
487                         std::move(paintFP), {paintAlpha, paintAlpha, paintAlpha, paintAlpha});
488             }
489         } else {
490             float paintAlpha = skPaint.getColor4f().fA;
491             if (paintAlpha != 1.0f) {
492                 // This invokes the shader's FP tree with an opaque version of the paint color,
493                 // then multiplies the final result by the incoming (paint) alpha.
494                 // We're actually putting the *unpremul* paint color on the GrPaint. This is okay,
495                 // because the shader is supposed to see the original (opaque) RGB from the paint.
496                 // ApplyPaintAlpha then creates a valid premul color by applying the paint alpha.
497                 // Think of this as equivalent to (but faster than) putting origColor.premul() on
498                 // the GrPaint, and ApplyPaintAlpha unpremuling it before passing it to the child.
499                 paintFP = GrFragmentProcessor::ApplyPaintAlpha(std::move(paintFP));
500                 grPaint->setColor4f({origColor.fR, origColor.fG, origColor.fB, origColor.fA});
501             } else {
502                 // paintFP will ignore its input color, so we must disable coverage-as-alpha.
503                 // TODO(skbug:11942): The alternative would be to always use ApplyPaintAlpha, but
504                 // we'd need to measure the cost of that shader math against the CAA benefit.
505                 paintFP = GrFragmentProcessor::DisableCoverageAsAlpha(std::move(paintFP));
506                 grPaint->setColor4f(origColor.premul());
507             }
508         }
509     } else {
510         if (primColorBlender) {
511             // The primitive itself has color (e.g. interpolated vertex color) and this is what
512             // the GP will output. Thus, we must get the paint color in separately below as a color
513             // FP. This could be made more efficient if the relevant GPs used GrPaint color and
514             // took the SkBlender to apply with primitive color. As it stands changing the SkPaint
515             // color will break batches.
516             grPaint->setColor4f(SK_PMColor4fWHITE);  // won't be used.
517             if (blender_requires_shader(primColorBlender)) {
518                 paintFP = GrFragmentProcessor::MakeColor(origColor.makeOpaque().premul());
519                 paintFP = as_BB(primColorBlender)->asFragmentProcessor(std::move(paintFP),
520                                                                        /*dstFP=*/nullptr,
521                                                                        fpArgs);
522                 if (!paintFP) {
523                     return false;
524                 }
525             }
526 
527             // The paint's *alpha* is applied after the paint/primitive color blend:
528             // We can ignore origColor here - alpha is unchanged by gamma
529             float paintAlpha = skPaint.getColor4f().fA;
530             if (paintAlpha != 1.0f) {
531                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
532                 // color channels. It's value should be treated as the same in ANY color space.
533                 paintFP = GrFragmentProcessor::ModulateRGBA(
534                         std::move(paintFP), {paintAlpha, paintAlpha, paintAlpha, paintAlpha});
535             }
536         } else {
537             // No shader, no primitive color.
538             grPaint->setColor4f(origColor.premul());
539             // We can do this if there isn't a GP that is acting as the shader.
540             applyColorFilterToPaintColor = !gpProvidesShader;
541         }
542     }
543 
544     SkColorFilter* colorFilter = skPaint.getColorFilter();
545     if (colorFilter) {
546         if (applyColorFilterToPaintColor) {
547             SkColorSpace* dstCS = dstColorInfo.colorSpace();
548             grPaint->setColor4f(colorFilter->filterColor4f(origColor, dstCS, dstCS).premul());
549         } else {
550             auto [success, fp] = as_CFB(colorFilter)->asFragmentProcessor(std::move(paintFP),
551                                                                           context, dstColorInfo,
552                                                                           surfaceProps);
553             if (!success) {
554                 return false;
555             }
556             paintFP = std::move(fp);
557         }
558     }
559 
560     SkMaskFilterBase* maskFilter = as_MFB(skPaint.getMaskFilter());
561     if (maskFilter) {
562         if (auto mfFP = maskFilter->asFragmentProcessor(fpArgs, ctm)) {
563             grPaint->setCoverageFragmentProcessor(std::move(mfFP));
564         }
565     }
566 
567 #ifndef SK_IGNORE_GPU_DITHER
568     GrColorType ct = dstColorInfo.colorType();
569     if (paintFP != nullptr && (
570             surfaceProps.isAlwaysDither() || SkPaintPriv::ShouldDither(skPaint, GrColorTypeToSkColorType(ct)))) {
571         float ditherRange = dither_range_for_config(ct);
572         paintFP = make_dither_effect(
573                 context, std::move(paintFP), ditherRange, context->priv().caps());
574     }
575 #endif
576 
577     // Note that for the final blend onto the canvas, we should prefer to use the GrXferProcessor
578     // instead of a SkBlendModeBlender to perform the blend. The Xfer processor is able to perform
579     // coefficient-based blends directly, without readback. This will be much more efficient.
580     if (auto bm = skPaint.asBlendMode()) {
581         // When the xfermode is null on the SkPaint (meaning kSrcOver) we need the XPFactory field
582         // on the GrPaint to also be null (also kSrcOver).
583         SkASSERT(!grPaint->getXPFactory());
584         if (bm.value() != SkBlendMode::kSrcOver) {
585             grPaint->setXPFactory(SkBlendMode_AsXPFactory(bm.value()));
586         }
587     } else {
588         // Apply a custom blend against the surface color, and force the XP to kSrc so that the
589         // computed result is applied directly to the canvas while still honoring the alpha.
590         paintFP = as_BB(skPaint.getBlender())->asFragmentProcessor(
591                 std::move(paintFP),
592                 GrFragmentProcessor::SurfaceColor(),
593                 fpArgs);
594         if (!paintFP) {
595             return false;
596         }
597         grPaint->setXPFactory(SkBlendMode_AsXPFactory(SkBlendMode::kSrc));
598     }
599 
600     if (GrColorTypeClampType(dstColorInfo.colorType()) == GrClampType::kManual) {
601         if (paintFP != nullptr) {
602             paintFP = GrFragmentProcessor::ClampOutput(std::move(paintFP));
603         } else {
604             auto color = grPaint->getColor4f();
605             grPaint->setColor4f({SkTPin(color.fR, 0.f, 1.f),
606                                  SkTPin(color.fG, 0.f, 1.f),
607                                  SkTPin(color.fB, 0.f, 1.f),
608                                  SkTPin(color.fA, 0.f, 1.f)});
609         }
610     }
611 
612     if (paintFP) {
613         grPaint->setColorFragmentProcessor(std::move(paintFP));
614     }
615 
616     return true;
617 }
618 
SkPaintToGrPaint(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & ctm,const SkSurfaceProps & surfaceProps,GrPaint * grPaint)619 bool SkPaintToGrPaint(GrRecordingContext* context,
620                       const GrColorInfo& dstColorInfo,
621                       const SkPaint& skPaint,
622                       const SkMatrix& ctm,
623                       const SkSurfaceProps& surfaceProps,
624                       GrPaint* grPaint) {
625     return skpaint_to_grpaint_impl(context,
626                                    dstColorInfo,
627                                    skPaint,
628                                    ctm,
629                                    /*shaderFP=*/std::nullopt,
630                                    /*primColorBlender=*/nullptr,
631                                    surfaceProps,
632                                    grPaint);
633 }
634 
635 /** Replaces the SkShader (if any) on skPaint with the passed in GrFragmentProcessor. */
SkPaintToGrPaintReplaceShader(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & ctm,std::unique_ptr<GrFragmentProcessor> shaderFP,const SkSurfaceProps & surfaceProps,GrPaint * grPaint)636 bool SkPaintToGrPaintReplaceShader(GrRecordingContext* context,
637                                    const GrColorInfo& dstColorInfo,
638                                    const SkPaint& skPaint,
639                                    const SkMatrix& ctm,
640                                    std::unique_ptr<GrFragmentProcessor> shaderFP,
641                                    const SkSurfaceProps& surfaceProps,
642                                    GrPaint* grPaint) {
643     return skpaint_to_grpaint_impl(context,
644                                    dstColorInfo,
645                                    skPaint,
646                                    ctm,
647                                    std::move(shaderFP),
648                                    /*primColorBlender=*/nullptr,
649                                    surfaceProps,
650                                    grPaint);
651 }
652 
653 /** Blends the SkPaint's shader (or color if no shader) with a per-primitive color which must
654     be setup as a vertex attribute using the specified SkBlender. */
SkPaintToGrPaintWithBlend(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & ctm,SkBlender * primColorBlender,const SkSurfaceProps & surfaceProps,GrPaint * grPaint)655 bool SkPaintToGrPaintWithBlend(GrRecordingContext* context,
656                                const GrColorInfo& dstColorInfo,
657                                const SkPaint& skPaint,
658                                const SkMatrix& ctm,
659                                SkBlender* primColorBlender,
660                                const SkSurfaceProps& surfaceProps,
661                                GrPaint* grPaint) {
662     return skpaint_to_grpaint_impl(context,
663                                    dstColorInfo,
664                                    skPaint,
665                                    ctm,
666                                    /*shaderFP=*/std::nullopt,
667                                    primColorBlender,
668                                    surfaceProps,
669                                    grPaint);
670 }
671