• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright 2017 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 "include/utils/SkShadowUtils.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColorFilter.h"
12 #include "include/core/SkMaskFilter.h"
13 #include "include/core/SkPath.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkVertices.h"
16 #include "include/private/SkColorData.h"
17 #include "include/private/SkIDChangeListener.h"
18 #include "include/private/SkTPin.h"
19 #include "include/utils/SkRandom.h"
20 #include "src/core/SkBlurMask.h"
21 #include "src/core/SkColorFilterBase.h"
22 #include "src/core/SkColorFilterPriv.h"
23 #include "src/core/SkDevice.h"
24 #include "src/core/SkDrawShadowInfo.h"
25 #include "src/core/SkEffectPriv.h"
26 #include "src/core/SkPathPriv.h"
27 #include "src/core/SkRasterPipeline.h"
28 #include "src/core/SkResourceCache.h"
29 #include "src/core/SkRuntimeEffectPriv.h"
30 #include "src/core/SkTLazy.h"
31 #include "src/core/SkVM.h"
32 #include "src/core/SkVerticesPriv.h"
33 #include "src/utils/SkShadowTessellator.h"
34 #include <new>
35 #if SK_SUPPORT_GPU
36 #include "src/gpu/effects/GrSkSLFP.h"
37 #include "src/gpu/geometry/GrStyledShape.h"
38 #endif
39 
40 /**
41 *  Gaussian color filter -- produces a Gaussian ramp based on the color's B value,
42 *                           then blends with the color's G value.
43 *                           Final result is black with alpha of Gaussian(B)*G.
44 *                           The assumption is that the original color's alpha is 1.
45 */
46 class SkGaussianColorFilter : public SkColorFilterBase {
47 public:
SkGaussianColorFilter()48     SkGaussianColorFilter() : INHERITED() {}
49 
50 #if SK_SUPPORT_GPU
51     GrFPResult asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> inputFP,
52                                    GrRecordingContext*, const GrColorInfo&) const override;
53 #endif
54 
55 protected:
flatten(SkWriteBuffer &) const56     void flatten(SkWriteBuffer&) const override {}
onAppendStages(const SkStageRec & rec,bool shaderIsOpaque) const57     bool onAppendStages(const SkStageRec& rec, bool shaderIsOpaque) const override {
58         rec.fPipeline->append(SkRasterPipeline::gauss_a_to_rgba);
59         return true;
60     }
61 
onProgram(skvm::Builder * p,skvm::Color c,const SkColorInfo & dst,skvm::Uniforms *,SkArenaAlloc *) const62     skvm::Color onProgram(skvm::Builder* p, skvm::Color c, const SkColorInfo& dst, skvm::Uniforms*,
63                           SkArenaAlloc*) const override {
64         // x = 1 - x;
65         // exp(-x * x * 4) - 0.018f;
66         // ... now approximate with quartic
67         //
68         skvm::F32 x = p->splat(-2.26661229133605957031f);
69                   x = c.a * x + 2.89795351028442382812f;
70                   x = c.a * x + 0.21345567703247070312f;
71                   x = c.a * x + 0.15489584207534790039f;
72                   x = c.a * x + 0.00030726194381713867f;
73         return {x, x, x, x};
74     }
75 
76 private:
77     SK_FLATTENABLE_HOOKS(SkGaussianColorFilter)
78 
79     using INHERITED = SkColorFilterBase;
80 };
81 
CreateProc(SkReadBuffer &)82 sk_sp<SkFlattenable> SkGaussianColorFilter::CreateProc(SkReadBuffer&) {
83     return SkColorFilterPriv::MakeGaussian();
84 }
85 
86 #if SK_SUPPORT_GPU
87 
asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> inputFP,GrRecordingContext *,const GrColorInfo &) const88 GrFPResult SkGaussianColorFilter::asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> inputFP,
89                                                       GrRecordingContext*,
90                                                       const GrColorInfo&) const {
91     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
92         half4 main(half4 inColor) {
93             half factor = 1 - inColor.a;
94             factor = exp(-factor * factor * 4) - 0.018;
95             return half4(factor);
96         }
97     )");
98     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
99     return GrFPSuccess(
100             GrSkSLFP::Make(effect, "gaussian_fp", std::move(inputFP), GrSkSLFP::OptFlags::kNone));
101 }
102 #endif
103 
MakeGaussian()104 sk_sp<SkColorFilter> SkColorFilterPriv::MakeGaussian() {
105     return sk_sp<SkColorFilter>(new SkGaussianColorFilter);
106 }
107 
108 ///////////////////////////////////////////////////////////////////////////////////////////////////
109 
110 namespace {
111 
resource_cache_shared_id()112 uint64_t resource_cache_shared_id() {
113     return 0x2020776f64616873llu;  // 'shadow  '
114 }
115 
116 /** Factory for an ambient shadow mesh with particular shadow properties. */
117 struct AmbientVerticesFactory {
118     SkScalar fOccluderHeight = SK_ScalarNaN;  // NaN so that isCompatible will fail until init'ed.
119     bool fTransparent;
120     SkVector fOffset;
121 
isCompatible__anon14c421030111::AmbientVerticesFactory122     bool isCompatible(const AmbientVerticesFactory& that, SkVector* translate) const {
123         if (fOccluderHeight != that.fOccluderHeight || fTransparent != that.fTransparent) {
124             return false;
125         }
126         *translate = that.fOffset;
127         return true;
128     }
129 
makeVertices__anon14c421030111::AmbientVerticesFactory130     sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
131                                    SkVector* translate) const {
132         SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
133         // pick a canonical place to generate shadow
134         SkMatrix noTrans(ctm);
135         if (!ctm.hasPerspective()) {
136             noTrans[SkMatrix::kMTransX] = 0;
137             noTrans[SkMatrix::kMTransY] = 0;
138         }
139         *translate = fOffset;
140         return SkShadowTessellator::MakeAmbient(path, noTrans, zParams, fTransparent);
141     }
142 };
143 
144 /** Factory for an spot shadow mesh with particular shadow properties. */
145 struct SpotVerticesFactory {
146     enum class OccluderType {
147         // The umbra cannot be dropped out because either the occluder is not opaque,
148         // or the center of the umbra is visible.
149         kTransparent,
150         // The umbra can be dropped where it is occluded.
151         kOpaquePartialUmbra,
152         // It is known that the entire umbra is occluded.
153         kOpaqueNoUmbra,
154         // The light is directional
155         kDirectional
156     };
157 
158     SkVector fOffset;
159     SkPoint  fLocalCenter;
160     SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
161     SkPoint3 fDevLightPos;
162     SkScalar fLightRadius;
163     OccluderType fOccluderType;
164 
isCompatible__anon14c421030111::SpotVerticesFactory165     bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const {
166         if (fOccluderHeight != that.fOccluderHeight || fDevLightPos.fZ != that.fDevLightPos.fZ ||
167             fLightRadius != that.fLightRadius || fOccluderType != that.fOccluderType) {
168             return false;
169         }
170         switch (fOccluderType) {
171             case OccluderType::kTransparent:
172             case OccluderType::kOpaqueNoUmbra:
173                 // 'this' and 'that' will either both have no umbra removed or both have all the
174                 // umbra removed.
175                 *translate = that.fOffset;
176                 return true;
177             case OccluderType::kOpaquePartialUmbra:
178                 // In this case we partially remove the umbra differently for 'this' and 'that'
179                 // if the offsets don't match.
180                 if (fOffset == that.fOffset) {
181                     translate->set(0, 0);
182                     return true;
183                 }
184                 return false;
185             case OccluderType::kDirectional:
186                 *translate = that.fOffset - fOffset;
187                 return true;
188         }
189         SK_ABORT("Uninitialized occluder type?");
190     }
191 
makeVertices__anon14c421030111::SpotVerticesFactory192     sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
193                                    SkVector* translate) const {
194         bool transparent = OccluderType::kTransparent == fOccluderType;
195         bool directional = OccluderType::kDirectional == fOccluderType;
196         SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
197         if (directional) {
198             translate->set(0, 0);
199             return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
200                                                  transparent, true);
201         } else if (ctm.hasPerspective() || OccluderType::kOpaquePartialUmbra == fOccluderType) {
202             translate->set(0, 0);
203             return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
204                                                  transparent, false);
205         } else {
206             // pick a canonical place to generate shadow, with light centered over path
207             SkMatrix noTrans(ctm);
208             noTrans[SkMatrix::kMTransX] = 0;
209             noTrans[SkMatrix::kMTransY] = 0;
210             SkPoint devCenter(fLocalCenter);
211             noTrans.mapPoints(&devCenter, 1);
212             SkPoint3 centerLightPos = SkPoint3::Make(devCenter.fX, devCenter.fY, fDevLightPos.fZ);
213             *translate = fOffset;
214             return SkShadowTessellator::MakeSpot(path, noTrans, zParams,
215                                                  centerLightPos, fLightRadius, transparent, false);
216         }
217     }
218 };
219 
220 /**
221  * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache
222  * records are immutable this is not itself a Rec. When we need to update it we return this on
223  * the FindVisitor and let the cache destroy the Rec. We'll update the tessellations and then add
224  * a new Rec with an adjusted size for any deletions/additions.
225  */
226 class CachedTessellations : public SkRefCnt {
227 public:
size() const228     size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
229 
find(const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate) const230     sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
231                            SkVector* translate) const {
232         return fAmbientSet.find(ambient, matrix, translate);
233     }
234 
add(const SkPath & devPath,const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate)235     sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient,
236                           const SkMatrix& matrix, SkVector* translate) {
237         return fAmbientSet.add(devPath, ambient, matrix, translate);
238     }
239 
find(const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate) const240     sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
241                            SkVector* translate) const {
242         return fSpotSet.find(spot, matrix, translate);
243     }
244 
add(const SkPath & devPath,const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate)245     sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot,
246                           const SkMatrix& matrix, SkVector* translate) {
247         return fSpotSet.add(devPath, spot, matrix, translate);
248     }
249 
250 private:
251     template <typename FACTORY, int MAX_ENTRIES>
252     class Set {
253     public:
size() const254         size_t size() const { return fSize; }
255 
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const256         sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
257                                SkVector* translate) const {
258             for (int i = 0; i < MAX_ENTRIES; ++i) {
259                 if (fEntries[i].fFactory.isCompatible(factory, translate)) {
260                     const SkMatrix& m = fEntries[i].fMatrix;
261                     if (matrix.hasPerspective() || m.hasPerspective()) {
262                         if (matrix != fEntries[i].fMatrix) {
263                             continue;
264                         }
265                     } else if (matrix.getScaleX() != m.getScaleX() ||
266                                matrix.getSkewX() != m.getSkewX() ||
267                                matrix.getScaleY() != m.getScaleY() ||
268                                matrix.getSkewY() != m.getSkewY()) {
269                         continue;
270                     }
271                     return fEntries[i].fVertices;
272                 }
273             }
274             return nullptr;
275         }
276 
add(const SkPath & path,const FACTORY & factory,const SkMatrix & matrix,SkVector * translate)277         sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix,
278                               SkVector* translate) {
279             sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix, translate);
280             if (!vertices) {
281                 return nullptr;
282             }
283             int i;
284             if (fCount < MAX_ENTRIES) {
285                 i = fCount++;
286             } else {
287                 i = fRandom.nextULessThan(MAX_ENTRIES);
288                 fSize -= fEntries[i].fVertices->approximateSize();
289             }
290             fEntries[i].fFactory = factory;
291             fEntries[i].fVertices = vertices;
292             fEntries[i].fMatrix = matrix;
293             fSize += vertices->approximateSize();
294             return vertices;
295         }
296 
297     private:
298         struct Entry {
299             FACTORY fFactory;
300             sk_sp<SkVertices> fVertices;
301             SkMatrix fMatrix;
302         };
303         Entry fEntries[MAX_ENTRIES];
304         int fCount = 0;
305         size_t fSize = 0;
306         SkRandom fRandom;
307     };
308 
309     Set<AmbientVerticesFactory, 4> fAmbientSet;
310     Set<SpotVerticesFactory, 4> fSpotSet;
311 };
312 
313 /**
314  * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular
315  * path. The key represents the path's geometry and not any shadow params.
316  */
317 class CachedTessellationsRec : public SkResourceCache::Rec {
318 public:
CachedTessellationsRec(const SkResourceCache::Key & key,sk_sp<CachedTessellations> tessellations)319     CachedTessellationsRec(const SkResourceCache::Key& key,
320                            sk_sp<CachedTessellations> tessellations)
321             : fTessellations(std::move(tessellations)) {
322         fKey.reset(new uint8_t[key.size()]);
323         memcpy(fKey.get(), &key, key.size());
324     }
325 
getKey() const326     const Key& getKey() const override {
327         return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
328     }
329 
bytesUsed() const330     size_t bytesUsed() const override { return fTessellations->size(); }
331 
getCategory() const332     const char* getCategory() const override { return "tessellated shadow masks"; }
333 
refTessellations() const334     sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
335 
336     template <typename FACTORY>
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const337     sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
338                            SkVector* translate) const {
339         return fTessellations->find(factory, matrix, translate);
340     }
341 
342 private:
343     std::unique_ptr<uint8_t[]> fKey;
344     sk_sp<CachedTessellations> fTessellations;
345 };
346 
347 /**
348  * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the
349  * vertices and a translation vector. If the CachedTessellations does not contain a suitable
350  * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations
351  * to the caller. The caller will update it and reinsert it back into the cache.
352  */
353 template <typename FACTORY>
354 struct FindContext {
FindContext__anon14c421030111::FindContext355     FindContext(const SkMatrix* viewMatrix, const FACTORY* factory)
356             : fViewMatrix(viewMatrix), fFactory(factory) {}
357     const SkMatrix* const fViewMatrix;
358     // If this is valid after Find is called then we found the vertices and they should be drawn
359     // with fTranslate applied.
360     sk_sp<SkVertices> fVertices;
361     SkVector fTranslate = {0, 0};
362 
363     // If this is valid after Find then the caller should add the vertices to the tessellation set
364     // and create a new CachedTessellationsRec and insert it into SkResourceCache.
365     sk_sp<CachedTessellations> fTessellationsOnFailure;
366 
367     const FACTORY* fFactory;
368 };
369 
370 /**
371  * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of
372  * the FindContext are used to determine if the vertices are reusable. If so the vertices and
373  * necessary translation vector are set on the FindContext.
374  */
375 template <typename FACTORY>
FindVisitor(const SkResourceCache::Rec & baseRec,void * ctx)376 bool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) {
377     FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx;
378     const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec);
379     findContext->fVertices =
380             rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate);
381     if (findContext->fVertices) {
382         return true;
383     }
384     // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been
385     // manipulated we will add a new Rec.
386     findContext->fTessellationsOnFailure = rec.refTessellations();
387     return false;
388 }
389 
390 class ShadowedPath {
391 public:
ShadowedPath(const SkPath * path,const SkMatrix * viewMatrix)392     ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix)
393             : fPath(path)
394             , fViewMatrix(viewMatrix)
395 #if SK_SUPPORT_GPU
396             , fShapeForKey(*path, GrStyle::SimpleFill())
397 #endif
398     {}
399 
path() const400     const SkPath& path() const { return *fPath; }
viewMatrix() const401     const SkMatrix& viewMatrix() const { return *fViewMatrix; }
402 #if SK_SUPPORT_GPU
403     /** Negative means the vertices should not be cached for this path. */
keyBytes() const404     int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); }
writeKey(void * key) const405     void writeKey(void* key) const {
406         fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
407     }
isRRect(SkRRect * rrect)408     bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr, nullptr, nullptr); }
409 #else
keyBytes() const410     int keyBytes() const { return -1; }
writeKey(void * key) const411     void writeKey(void* key) const { SK_ABORT("Should never be called"); }
isRRect(SkRRect * rrect)412     bool isRRect(SkRRect* rrect) { return false; }
413 #endif
414 
415 private:
416     const SkPath* fPath;
417     const SkMatrix* fViewMatrix;
418 #if SK_SUPPORT_GPU
419     GrStyledShape fShapeForKey;
420 #endif
421 };
422 
423 // This creates a domain of keys in SkResourceCache used by this file.
424 static void* kNamespace;
425 
426 // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
427 class ShadowInvalidator : public SkIDChangeListener {
428 public:
ShadowInvalidator(const SkResourceCache::Key & key)429     ShadowInvalidator(const SkResourceCache::Key& key) {
430         fKey.reset(new uint8_t[key.size()]);
431         memcpy(fKey.get(), &key, key.size());
432     }
433 
434 private:
getKey() const435     const SkResourceCache::Key& getKey() const {
436         return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
437     }
438 
439     // always purge
FindVisitor(const SkResourceCache::Rec &,void *)440     static bool FindVisitor(const SkResourceCache::Rec&, void*) {
441         return false;
442     }
443 
changed()444     void changed() override {
445         SkResourceCache::Find(this->getKey(), ShadowInvalidator::FindVisitor, nullptr);
446     }
447 
448     std::unique_ptr<uint8_t[]> fKey;
449 };
450 
451 /**
452  * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
453  * they are first found in SkResourceCache.
454  */
455 template <typename FACTORY>
draw_shadow(const FACTORY & factory,std::function<void (const SkVertices *,SkBlendMode,const SkPaint &,SkScalar tx,SkScalar ty,bool)> drawProc,ShadowedPath & path,SkColor color)456 bool draw_shadow(const FACTORY& factory,
457                  std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
458                  SkScalar tx, SkScalar ty, bool)> drawProc, ShadowedPath& path, SkColor color) {
459     FindContext<FACTORY> context(&path.viewMatrix(), &factory);
460 
461     SkResourceCache::Key* key = nullptr;
462     SkAutoSTArray<32 * 4, uint8_t> keyStorage;
463     int keyDataBytes = path.keyBytes();
464     if (keyDataBytes >= 0) {
465         keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
466         key = new (keyStorage.begin()) SkResourceCache::Key();
467         path.writeKey((uint32_t*)(keyStorage.begin() + sizeof(*key)));
468         key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
469         SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
470     }
471 
472     sk_sp<SkVertices> vertices;
473     bool foundInCache = SkToBool(context.fVertices);
474     if (foundInCache) {
475         vertices = std::move(context.fVertices);
476     } else {
477         // TODO: handle transforming the path as part of the tessellator
478         if (key) {
479             // Update or initialize a tessellation set and add it to the cache.
480             sk_sp<CachedTessellations> tessellations;
481             if (context.fTessellationsOnFailure) {
482                 tessellations = std::move(context.fTessellationsOnFailure);
483             } else {
484                 tessellations.reset(new CachedTessellations());
485             }
486             vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
487                                           &context.fTranslate);
488             if (!vertices) {
489                 return false;
490             }
491             auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
492             SkPathPriv::AddGenIDChangeListener(path.path(), sk_make_sp<ShadowInvalidator>(*key));
493             SkResourceCache::Add(rec);
494         } else {
495             vertices = factory.makeVertices(path.path(), path.viewMatrix(),
496                                             &context.fTranslate);
497             if (!vertices) {
498                 return false;
499             }
500         }
501     }
502 
503     SkPaint paint;
504     // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
505     // that against our 'color' param.
506     paint.setColorFilter(
507          SkColorFilters::Blend(color, SkBlendMode::kModulate)->makeComposed(
508                                                                 SkColorFilterPriv::MakeGaussian()));
509 
510     drawProc(vertices.get(), SkBlendMode::kModulate, paint,
511              context.fTranslate.fX, context.fTranslate.fY, path.viewMatrix().hasPerspective());
512 
513     return true;
514 }
515 }  // namespace
516 
tilted(const SkPoint3 & zPlaneParams)517 static bool tilted(const SkPoint3& zPlaneParams) {
518     return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
519 }
520 
ComputeTonalColors(SkColor inAmbientColor,SkColor inSpotColor,SkColor * outAmbientColor,SkColor * outSpotColor)521 void SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
522                                        SkColor* outAmbientColor, SkColor* outSpotColor) {
523     // For tonal color we only compute color values for the spot shadow.
524     // The ambient shadow is greyscale only.
525 
526     // Ambient
527     *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
528 
529     // Spot
530     int spotR = SkColorGetR(inSpotColor);
531     int spotG = SkColorGetG(inSpotColor);
532     int spotB = SkColorGetB(inSpotColor);
533     int max = std::max(std::max(spotR, spotG), spotB);
534     int min = std::min(std::min(spotR, spotG), spotB);
535     SkScalar luminance = 0.5f*(max + min)/255.f;
536     SkScalar origA = SkColorGetA(inSpotColor)/255.f;
537 
538     // We compute a color alpha value based on the luminance of the color, scaled by an
539     // adjusted alpha value. We want the following properties to match the UX examples
540     // (assuming a = 0.25) and to ensure that we have reasonable results when the color
541     // is black and/or the alpha is 0:
542     //     f(0, a) = 0
543     //     f(luminance, 0) = 0
544     //     f(1, 0.25) = .5
545     //     f(0.5, 0.25) = .4
546     //     f(1, 1) = 1
547     // The following functions match this as closely as possible.
548     SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
549     SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
550     colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
551 
552     // Similarly, we set the greyscale alpha based on luminance and alpha so that
553     //     f(0, a) = a
554     //     f(luminance, 0) = 0
555     //     f(1, 0.25) = 0.15
556     SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
557 
558     // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
559     // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
560     // which is an adjusted value of 'a'.  Assuming SrcOver, a background color of B_rgb, and
561     // ignoring edge falloff, this becomes
562     //
563     //      (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
564     //
565     // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
566     // set the alpha to (S_a + C_a - S_a*C_a).
567     SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
568     SkScalar tonalAlpha = colorScale + greyscaleAlpha;
569     SkScalar unPremulScale = colorScale / tonalAlpha;
570     *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
571                                    unPremulScale*spotR,
572                                    unPremulScale*spotG,
573                                    unPremulScale*spotB);
574 }
575 
fill_shadow_rec(const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags,const SkMatrix & ctm,SkDrawShadowRec * rec)576 static bool fill_shadow_rec(const SkPath& path, const SkPoint3& zPlaneParams,
577                             const SkPoint3& lightPos, SkScalar lightRadius,
578                             SkColor ambientColor, SkColor spotColor,
579                             uint32_t flags, const SkMatrix& ctm, SkDrawShadowRec* rec) {
580     SkPoint pt = { lightPos.fX, lightPos.fY };
581     if (!SkToBool(flags & kDirectionalLight_ShadowFlag)) {
582         // If light position is in device space, need to transform to local space
583         // before applying to SkCanvas.
584         SkMatrix inverse;
585         if (!ctm.invert(&inverse)) {
586             return false;
587         }
588         inverse.mapPoints(&pt, 1);
589     }
590 
591     rec->fZPlaneParams   = zPlaneParams;
592     rec->fLightPos       = { pt.fX, pt.fY, lightPos.fZ };
593     rec->fLightRadius    = lightRadius;
594     rec->fAmbientColor   = ambientColor;
595     rec->fSpotColor      = spotColor;
596     rec->fFlags          = flags;
597 
598     return true;
599 }
600 
601 // Draw an offset spot shadow and outlining ambient shadow for the given path.
DrawShadow(SkCanvas * canvas,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags)602 void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
603                                const SkPoint3& lightPos, SkScalar lightRadius,
604                                SkColor ambientColor, SkColor spotColor,
605                                uint32_t flags) {
606     DrawShadowStyle(canvas, path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags, false);
607 }
608 
DrawShadowStyle(SkCanvas * canvas,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags,bool isLimitElevation)609 void SkShadowUtils::DrawShadowStyle(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
610                                     const SkPoint3& lightPos, SkScalar lightRadius,
611                                     SkColor ambientColor, SkColor spotColor,
612                                     uint32_t flags, bool isLimitElevation) {
613     SkDrawShadowRec rec;
614     rec.isLimitElevation = isLimitElevation;
615     if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor,
616                          flags, canvas->getTotalMatrix(), &rec)) {
617         return;
618     }
619 
620     canvas->private_draw_shadow_rec(path, rec);
621 }
622 
GetLocalBounds(const SkMatrix & ctm,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,uint32_t flags,SkRect * bounds)623 bool SkShadowUtils::GetLocalBounds(const SkMatrix& ctm, const SkPath& path,
624                                    const SkPoint3& zPlaneParams, const SkPoint3& lightPos,
625                                    SkScalar lightRadius, uint32_t flags, SkRect* bounds) {
626     SkDrawShadowRec rec;
627     if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, SK_ColorBLACK, SK_ColorBLACK,
628                          flags, ctm, &rec)) {
629         return false;
630     }
631 
632     SkDrawShadowMetrics::GetLocalBounds(path, rec, ctm, bounds);
633 
634     return true;
635 }
636 
637 //////////////////////////////////////////////////////////////////////////////////////////////
638 
validate_rec(const SkDrawShadowRec & rec)639 static bool validate_rec(const SkDrawShadowRec& rec) {
640     return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
641            SkScalarIsFinite(rec.fLightRadius);
642 }
643 
drawShadow(const SkPath & path,const SkDrawShadowRec & rec)644 void SkBaseDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
645     auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
646                                 SkScalar tx, SkScalar ty, bool hasPerspective) {
647         if (vertices->priv().vertexCount()) {
648             // For perspective shadows we've already computed the shadow in world space,
649             // and we can't translate it without changing it. Otherwise we concat the
650             // change in translation from the cached version.
651             SkAutoDeviceTransformRestore adr(
652                     this,
653                     hasPerspective ? SkMatrix::I()
654                                    : this->localToDevice() * SkMatrix::Translate(tx, ty));
655             this->drawVertices(vertices, mode, paint);
656         }
657     };
658 
659     if (!validate_rec(rec)) {
660         return;
661     }
662 
663     SkMatrix viewMatrix = this->localToDevice();
664     SkAutoDeviceTransformRestore adr(this, SkMatrix::I());
665 
666     ShadowedPath shadowedPath(&path, &viewMatrix);
667 
668     bool tiltZPlane = tilted(rec.fZPlaneParams);
669     bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
670     bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);
671     bool uncached = tiltZPlane || path.isVolatile();
672 
673     SkPoint3 zPlaneParams = rec.fZPlaneParams;
674     SkPoint3 devLightPos = rec.fLightPos;
675     if (!directional) {
676         viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
677     }
678     float lightRadius = rec.fLightRadius;
679 
680     if (SkColorGetA(rec.fAmbientColor) > 0) {
681         bool success = false;
682         if (uncached) {
683             sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
684                                                                           zPlaneParams,
685                                                                           transparent);
686             if (vertices) {
687                 SkPaint paint;
688                 // Run the vertex color through a GaussianColorFilter and then modulate the
689                 // grayscale result of that against our 'color' param.
690                 paint.setColorFilter(
691                     SkColorFilters::Blend(rec.fAmbientColor,
692                                                   SkBlendMode::kModulate)->makeComposed(
693                                                                SkColorFilterPriv::MakeGaussian()));
694                 this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
695                 success = true;
696             }
697         }
698 
699         if (!success) {
700             AmbientVerticesFactory factory;
701             factory.fOccluderHeight = zPlaneParams.fZ;
702             factory.fTransparent = transparent;
703             if (viewMatrix.hasPerspective()) {
704                 factory.fOffset.set(0, 0);
705             } else {
706                 factory.fOffset.fX = viewMatrix.getTranslateX();
707                 factory.fOffset.fY = viewMatrix.getTranslateY();
708             }
709 
710             if (!draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor)) {
711                 // Pretransform the path to avoid transforming the stroke, below.
712                 SkPath devSpacePath;
713                 path.transform(viewMatrix, &devSpacePath);
714                 devSpacePath.setIsVolatile(true);
715 
716                 // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
717                 // the tesselation, and sets the alpha on the path to 1/AmbientRecipAlpha (or 'a').
718                 //
719                 // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
720                 // can be calculated by interpolating:
721                 //
722                 //            original edge        outer edge
723                 //         |       |<---------- r ------>|
724                 //         |<------|--- f -------------->|
725                 //         |       |                     |
726                 //    alpha = 1  alpha = a          alpha = 0
727                 //
728                 // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
729                 //
730                 // We now need to outset the path to place the new edge in the center of the
731                 // blur region:
732                 //
733                 //             original   new
734                 //         |       |<------|--- r ------>|
735                 //         |<------|--- f -|------------>|
736                 //         |       |<- o ->|<--- f/2 --->|
737                 //
738                 //     r = o + f/2, so o = r - f/2
739                 //
740                 // We outset by using the stroker, so the strokeWidth is o/2.
741                 //
742                 SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
743                 SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
744                 SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
745                 SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
746 
747                 // Now draw with blur
748                 SkPaint paint;
749                 paint.setColor(rec.fAmbientColor);
750                 paint.setStrokeWidth(strokeWidth);
751                 paint.setStyle(SkPaint::kStrokeAndFill_Style);
752                 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(blurRadius);
753                 bool respectCTM = false;
754                 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
755                 this->drawPath(devSpacePath, paint);
756             }
757         }
758     }
759 
760     if (SkColorGetA(rec.fSpotColor) > 0) {
761         bool success = false;
762         if (uncached) {
763             sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
764                                                                        zPlaneParams,
765                                                                        devLightPos, lightRadius,
766                                                                        transparent,
767                                                                        directional);
768             if (vertices) {
769                 SkPaint paint;
770                 // Run the vertex color through a GaussianColorFilter and then modulate the
771                 // grayscale result of that against our 'color' param.
772                 paint.setColorFilter(
773                     SkColorFilters::Blend(rec.fSpotColor,
774                                                   SkBlendMode::kModulate)->makeComposed(
775                                                       SkColorFilterPriv::MakeGaussian()));
776                 this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
777                 success = true;
778             }
779         }
780 
781         if (!success) {
782             SpotVerticesFactory factory;
783             factory.fOccluderHeight = zPlaneParams.fZ;
784             factory.fDevLightPos = devLightPos;
785             factory.fLightRadius = lightRadius;
786 
787             SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
788             factory.fLocalCenter = center;
789             viewMatrix.mapPoints(&center, 1);
790             SkScalar radius, scale;
791             if (SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag)) {
792                 SkDrawShadowMetrics::GetDirectionalParams(zPlaneParams.fZ, devLightPos.fX,
793                                                           devLightPos.fY, devLightPos.fZ,
794                                                           lightRadius, &radius, &scale,
795                                                           &factory.fOffset);
796             } else {
797                 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
798                                                    devLightPos.fY - center.fY, devLightPos.fZ, lightRadius,
799                                                    &radius, &scale, &factory.fOffset, rec.isLimitElevation);
800             }
801 
802             SkRect devBounds;
803             viewMatrix.mapRect(&devBounds, path.getBounds());
804             if (directional) {
805                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kDirectional;
806             } else if (transparent ||
807                        SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
808                        SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
809                 // if the translation of the shadow is big enough we're going to end up
810                 // filling the entire umbra, so we can treat these as all the same
811                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent;
812             } else if (factory.fOffset.length()*scale + scale < radius) {
813                 // if we don't translate more than the blur distance, can assume umbra is covered
814                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaqueNoUmbra;
815             } else if (path.isConvex()) {
816                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaquePartialUmbra;
817             } else {
818                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent;
819             }
820             // need to add this after we classify the shadow
821             factory.fOffset.fX += viewMatrix.getTranslateX();
822             factory.fOffset.fY += viewMatrix.getTranslateY();
823 
824             SkColor color = rec.fSpotColor;
825 #ifdef DEBUG_SHADOW_CHECKS
826             switch (factory.fOccluderType) {
827                 case SpotVerticesFactory::OccluderType::kTransparent:
828                     color = 0xFFD2B48C;  // tan for transparent
829                     break;
830                 case SpotVerticesFactory::OccluderType::kOpaquePartialUmbra:
831                     color = 0xFFFFA500;   // orange for opaque
832                     break;
833                 case SpotVerticesFactory::OccluderType::kOpaqueNoUmbra:
834                     color = 0xFFE5E500;  // corn yellow for covered
835                     break;
836                 case SpotVerticesFactory::OccluderType::kDirectional:
837                     color = 0xFF550000;  // dark red for directional
838                     break;
839             }
840 #endif
841             if (!draw_shadow(factory, drawVertsProc, shadowedPath, color)) {
842                 // draw with blur
843                 SkMatrix shadowMatrix;
844                 if (!SkDrawShadowMetrics::GetSpotShadowTransform(devLightPos, lightRadius,
845                                                                  viewMatrix, zPlaneParams,
846                                                                  path.getBounds(), directional,
847                                                                  &shadowMatrix, &radius)) {
848                     return;
849                 }
850                 SkAutoDeviceTransformRestore adr2(this, shadowMatrix);
851 
852                 SkPaint paint;
853                 paint.setColor(rec.fSpotColor);
854                 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
855                 bool respectCTM = false;
856                 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
857                 this->drawPath(path, paint);
858             }
859         }
860     }
861 }
862