• 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__anondfce38310111::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__anondfce38310111::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. Uses point light.
149         kPointTransparent,
150         // The umbra can be dropped where it is occluded. Uses point light.
151         kPointOpaquePartialUmbra,
152         // It is known that the entire umbra is occluded. Uses point light.
153         kPointOpaqueNoUmbra,
154         // Uses directional light.
155         kDirectional,
156         // The umbra can't be dropped out. Uses directional light.
157         kDirectionalTransparent,
158     };
159 
160     SkVector fOffset;
161     SkPoint  fLocalCenter;
162     SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
163     SkPoint3 fDevLightPos;
164     SkScalar fLightRadius;
165     OccluderType fOccluderType;
166 
isCompatible__anondfce38310111::SpotVerticesFactory167     bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const {
168         if (fOccluderHeight != that.fOccluderHeight || fDevLightPos.fZ != that.fDevLightPos.fZ ||
169             fLightRadius != that.fLightRadius || fOccluderType != that.fOccluderType) {
170             return false;
171         }
172         switch (fOccluderType) {
173             case OccluderType::kPointTransparent:
174             case OccluderType::kPointOpaqueNoUmbra:
175                 // 'this' and 'that' will either both have no umbra removed or both have all the
176                 // umbra removed.
177                 *translate = that.fOffset;
178                 return true;
179             case OccluderType::kPointOpaquePartialUmbra:
180                 // In this case we partially remove the umbra differently for 'this' and 'that'
181                 // if the offsets don't match.
182                 if (fOffset == that.fOffset) {
183                     translate->set(0, 0);
184                     return true;
185                 }
186                 return false;
187             case OccluderType::kDirectional:
188             case OccluderType::kDirectionalTransparent:
189                 *translate = that.fOffset - fOffset;
190                 return true;
191         }
192         SK_ABORT("Uninitialized occluder type?");
193     }
194 
makeVertices__anondfce38310111::SpotVerticesFactory195     sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
196                                    SkVector* translate) const {
197         bool transparent = fOccluderType == OccluderType::kPointTransparent ||
198                            fOccluderType == OccluderType::kDirectionalTransparent;
199         bool directional = fOccluderType == OccluderType::kDirectional ||
200                            fOccluderType == OccluderType::kDirectionalTransparent;
201         SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
202         if (directional) {
203             translate->set(0, 0);
204             return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
205                                                  transparent, true);
206         } else if (ctm.hasPerspective() || OccluderType::kPointOpaquePartialUmbra == fOccluderType) {
207             translate->set(0, 0);
208             return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
209                                                  transparent, false);
210         } else {
211             // pick a canonical place to generate shadow, with light centered over path
212             SkMatrix noTrans(ctm);
213             noTrans[SkMatrix::kMTransX] = 0;
214             noTrans[SkMatrix::kMTransY] = 0;
215             SkPoint devCenter(fLocalCenter);
216             noTrans.mapPoints(&devCenter, 1);
217             SkPoint3 centerLightPos = SkPoint3::Make(devCenter.fX, devCenter.fY, fDevLightPos.fZ);
218             *translate = fOffset;
219             return SkShadowTessellator::MakeSpot(path, noTrans, zParams,
220                                                  centerLightPos, fLightRadius, transparent, false);
221         }
222     }
223 };
224 
225 /**
226  * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache
227  * records are immutable this is not itself a Rec. When we need to update it we return this on
228  * the FindVisitor and let the cache destroy the Rec. We'll update the tessellations and then add
229  * a new Rec with an adjusted size for any deletions/additions.
230  */
231 class CachedTessellations : public SkRefCnt {
232 public:
size() const233     size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
234 
find(const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate) const235     sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
236                            SkVector* translate) const {
237         return fAmbientSet.find(ambient, matrix, translate);
238     }
239 
add(const SkPath & devPath,const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate)240     sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient,
241                           const SkMatrix& matrix, SkVector* translate) {
242         return fAmbientSet.add(devPath, ambient, matrix, translate);
243     }
244 
find(const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate) const245     sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
246                            SkVector* translate) const {
247         return fSpotSet.find(spot, matrix, translate);
248     }
249 
add(const SkPath & devPath,const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate)250     sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot,
251                           const SkMatrix& matrix, SkVector* translate) {
252         return fSpotSet.add(devPath, spot, matrix, translate);
253     }
254 
255 private:
256     template <typename FACTORY, int MAX_ENTRIES>
257     class Set {
258     public:
size() const259         size_t size() const { return fSize; }
260 
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const261         sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
262                                SkVector* translate) const {
263             for (int i = 0; i < MAX_ENTRIES; ++i) {
264                 if (fEntries[i].fFactory.isCompatible(factory, translate)) {
265                     const SkMatrix& m = fEntries[i].fMatrix;
266                     if (matrix.hasPerspective() || m.hasPerspective()) {
267                         if (matrix != fEntries[i].fMatrix) {
268                             continue;
269                         }
270                     } else if (matrix.getScaleX() != m.getScaleX() ||
271                                matrix.getSkewX() != m.getSkewX() ||
272                                matrix.getScaleY() != m.getScaleY() ||
273                                matrix.getSkewY() != m.getSkewY()) {
274                         continue;
275                     }
276                     return fEntries[i].fVertices;
277                 }
278             }
279             return nullptr;
280         }
281 
add(const SkPath & path,const FACTORY & factory,const SkMatrix & matrix,SkVector * translate)282         sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix,
283                               SkVector* translate) {
284             sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix, translate);
285             if (!vertices) {
286                 return nullptr;
287             }
288             int i;
289             if (fCount < MAX_ENTRIES) {
290                 i = fCount++;
291             } else {
292                 i = fRandom.nextULessThan(MAX_ENTRIES);
293                 fSize -= fEntries[i].fVertices->approximateSize();
294             }
295             fEntries[i].fFactory = factory;
296             fEntries[i].fVertices = vertices;
297             fEntries[i].fMatrix = matrix;
298             fSize += vertices->approximateSize();
299             return vertices;
300         }
301 
302     private:
303         struct Entry {
304             FACTORY fFactory;
305             sk_sp<SkVertices> fVertices;
306             SkMatrix fMatrix;
307         };
308         Entry fEntries[MAX_ENTRIES];
309         int fCount = 0;
310         size_t fSize = 0;
311         SkRandom fRandom;
312     };
313 
314     Set<AmbientVerticesFactory, 4> fAmbientSet;
315     Set<SpotVerticesFactory, 4> fSpotSet;
316 };
317 
318 /**
319  * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular
320  * path. The key represents the path's geometry and not any shadow params.
321  */
322 class CachedTessellationsRec : public SkResourceCache::Rec {
323 public:
CachedTessellationsRec(const SkResourceCache::Key & key,sk_sp<CachedTessellations> tessellations)324     CachedTessellationsRec(const SkResourceCache::Key& key,
325                            sk_sp<CachedTessellations> tessellations)
326             : fTessellations(std::move(tessellations)) {
327         fKey.reset(new uint8_t[key.size()]);
328         memcpy(fKey.get(), &key, key.size());
329     }
330 
getKey() const331     const Key& getKey() const override {
332         return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
333     }
334 
bytesUsed() const335     size_t bytesUsed() const override { return fTessellations->size(); }
336 
getCategory() const337     const char* getCategory() const override { return "tessellated shadow masks"; }
338 
refTessellations() const339     sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
340 
341     template <typename FACTORY>
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const342     sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
343                            SkVector* translate) const {
344         return fTessellations->find(factory, matrix, translate);
345     }
346 
347 private:
348     std::unique_ptr<uint8_t[]> fKey;
349     sk_sp<CachedTessellations> fTessellations;
350 };
351 
352 /**
353  * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the
354  * vertices and a translation vector. If the CachedTessellations does not contain a suitable
355  * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations
356  * to the caller. The caller will update it and reinsert it back into the cache.
357  */
358 template <typename FACTORY>
359 struct FindContext {
FindContext__anondfce38310111::FindContext360     FindContext(const SkMatrix* viewMatrix, const FACTORY* factory)
361             : fViewMatrix(viewMatrix), fFactory(factory) {}
362     const SkMatrix* const fViewMatrix;
363     // If this is valid after Find is called then we found the vertices and they should be drawn
364     // with fTranslate applied.
365     sk_sp<SkVertices> fVertices;
366     SkVector fTranslate = {0, 0};
367 
368     // If this is valid after Find then the caller should add the vertices to the tessellation set
369     // and create a new CachedTessellationsRec and insert it into SkResourceCache.
370     sk_sp<CachedTessellations> fTessellationsOnFailure;
371 
372     const FACTORY* fFactory;
373 };
374 
375 /**
376  * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of
377  * the FindContext are used to determine if the vertices are reusable. If so the vertices and
378  * necessary translation vector are set on the FindContext.
379  */
380 template <typename FACTORY>
FindVisitor(const SkResourceCache::Rec & baseRec,void * ctx)381 bool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) {
382     FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx;
383     const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec);
384     findContext->fVertices =
385             rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate);
386     if (findContext->fVertices) {
387         return true;
388     }
389     // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been
390     // manipulated we will add a new Rec.
391     findContext->fTessellationsOnFailure = rec.refTessellations();
392     return false;
393 }
394 
395 class ShadowedPath {
396 public:
ShadowedPath(const SkPath * path,const SkMatrix * viewMatrix)397     ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix)
398             : fPath(path)
399             , fViewMatrix(viewMatrix)
400 #if SK_SUPPORT_GPU
401             , fShapeForKey(*path, GrStyle::SimpleFill())
402 #endif
403     {}
404 
path() const405     const SkPath& path() const { return *fPath; }
viewMatrix() const406     const SkMatrix& viewMatrix() const { return *fViewMatrix; }
407 #if SK_SUPPORT_GPU
408     /** Negative means the vertices should not be cached for this path. */
keyBytes() const409     int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); }
writeKey(void * key) const410     void writeKey(void* key) const {
411         fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
412     }
isRRect(SkRRect * rrect)413     bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr, nullptr, nullptr); }
414 #else
keyBytes() const415     int keyBytes() const { return -1; }
writeKey(void * key) const416     void writeKey(void* key) const { SK_ABORT("Should never be called"); }
isRRect(SkRRect * rrect)417     bool isRRect(SkRRect* rrect) { return false; }
418 #endif
419 
420 private:
421     const SkPath* fPath;
422     const SkMatrix* fViewMatrix;
423 #if SK_SUPPORT_GPU
424     GrStyledShape fShapeForKey;
425 #endif
426 };
427 
428 // This creates a domain of keys in SkResourceCache used by this file.
429 static void* kNamespace;
430 
431 // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
432 class ShadowInvalidator : public SkIDChangeListener {
433 public:
ShadowInvalidator(const SkResourceCache::Key & key)434     ShadowInvalidator(const SkResourceCache::Key& key) {
435         fKey.reset(new uint8_t[key.size()]);
436         memcpy(fKey.get(), &key, key.size());
437     }
438 
439 private:
getKey() const440     const SkResourceCache::Key& getKey() const {
441         return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
442     }
443 
444     // always purge
FindVisitor(const SkResourceCache::Rec &,void *)445     static bool FindVisitor(const SkResourceCache::Rec&, void*) {
446         return false;
447     }
448 
changed()449     void changed() override {
450         SkResourceCache::Find(this->getKey(), ShadowInvalidator::FindVisitor, nullptr);
451     }
452 
453     std::unique_ptr<uint8_t[]> fKey;
454 };
455 
456 /**
457  * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
458  * they are first found in SkResourceCache.
459  */
460 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)461 bool draw_shadow(const FACTORY& factory,
462                  std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
463                  SkScalar tx, SkScalar ty, bool)> drawProc, ShadowedPath& path, SkColor color) {
464     FindContext<FACTORY> context(&path.viewMatrix(), &factory);
465 
466     SkResourceCache::Key* key = nullptr;
467     SkAutoSTArray<32 * 4, uint8_t> keyStorage;
468     int keyDataBytes = path.keyBytes();
469     if (keyDataBytes >= 0) {
470         keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
471         key = new (keyStorage.begin()) SkResourceCache::Key();
472         path.writeKey((uint32_t*)(keyStorage.begin() + sizeof(*key)));
473         key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
474         SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
475     }
476 
477     sk_sp<SkVertices> vertices;
478     bool foundInCache = SkToBool(context.fVertices);
479     if (foundInCache) {
480         vertices = std::move(context.fVertices);
481     } else {
482         // TODO: handle transforming the path as part of the tessellator
483         if (key) {
484             // Update or initialize a tessellation set and add it to the cache.
485             sk_sp<CachedTessellations> tessellations;
486             if (context.fTessellationsOnFailure) {
487                 tessellations = std::move(context.fTessellationsOnFailure);
488             } else {
489                 tessellations.reset(new CachedTessellations());
490             }
491             vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
492                                           &context.fTranslate);
493             if (!vertices) {
494                 return false;
495             }
496             auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
497             SkPathPriv::AddGenIDChangeListener(path.path(), sk_make_sp<ShadowInvalidator>(*key));
498             SkResourceCache::Add(rec);
499         } else {
500             vertices = factory.makeVertices(path.path(), path.viewMatrix(),
501                                             &context.fTranslate);
502             if (!vertices) {
503                 return false;
504             }
505         }
506     }
507 
508     SkPaint paint;
509     // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
510     // that against our 'color' param.
511     paint.setColorFilter(
512          SkColorFilters::Blend(color, SkBlendMode::kModulate)->makeComposed(
513                                                                 SkColorFilterPriv::MakeGaussian()));
514 
515     drawProc(vertices.get(), SkBlendMode::kModulate, paint,
516              context.fTranslate.fX, context.fTranslate.fY, path.viewMatrix().hasPerspective());
517 
518     return true;
519 }
520 }  // namespace
521 
tilted(const SkPoint3 & zPlaneParams)522 static bool tilted(const SkPoint3& zPlaneParams) {
523     return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
524 }
525 
ComputeTonalColors(SkColor inAmbientColor,SkColor inSpotColor,SkColor * outAmbientColor,SkColor * outSpotColor)526 void SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
527                                        SkColor* outAmbientColor, SkColor* outSpotColor) {
528     // For tonal color we only compute color values for the spot shadow.
529     // The ambient shadow is greyscale only.
530 
531     // Ambient
532     *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
533 
534     // Spot
535     int spotR = SkColorGetR(inSpotColor);
536     int spotG = SkColorGetG(inSpotColor);
537     int spotB = SkColorGetB(inSpotColor);
538     int max = std::max(std::max(spotR, spotG), spotB);
539     int min = std::min(std::min(spotR, spotG), spotB);
540     SkScalar luminance = 0.5f*(max + min)/255.f;
541     SkScalar origA = SkColorGetA(inSpotColor)/255.f;
542 
543     // We compute a color alpha value based on the luminance of the color, scaled by an
544     // adjusted alpha value. We want the following properties to match the UX examples
545     // (assuming a = 0.25) and to ensure that we have reasonable results when the color
546     // is black and/or the alpha is 0:
547     //     f(0, a) = 0
548     //     f(luminance, 0) = 0
549     //     f(1, 0.25) = .5
550     //     f(0.5, 0.25) = .4
551     //     f(1, 1) = 1
552     // The following functions match this as closely as possible.
553     SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
554     SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
555     colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
556 
557     // Similarly, we set the greyscale alpha based on luminance and alpha so that
558     //     f(0, a) = a
559     //     f(luminance, 0) = 0
560     //     f(1, 0.25) = 0.15
561     SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
562 
563     // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
564     // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
565     // which is an adjusted value of 'a'.  Assuming SrcOver, a background color of B_rgb, and
566     // ignoring edge falloff, this becomes
567     //
568     //      (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
569     //
570     // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
571     // set the alpha to (S_a + C_a - S_a*C_a).
572     SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
573     SkScalar tonalAlpha = colorScale + greyscaleAlpha;
574     SkScalar unPremulScale = colorScale / tonalAlpha;
575     *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
576                                    unPremulScale*spotR,
577                                    unPremulScale*spotG,
578                                    unPremulScale*spotB);
579 }
580 
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)581 static bool fill_shadow_rec(const SkPath& path, const SkPoint3& zPlaneParams,
582                             const SkPoint3& lightPos, SkScalar lightRadius,
583                             SkColor ambientColor, SkColor spotColor,
584                             uint32_t flags, const SkMatrix& ctm, SkDrawShadowRec* rec) {
585     SkPoint pt = { lightPos.fX, lightPos.fY };
586     if (!SkToBool(flags & kDirectionalLight_ShadowFlag)) {
587         // If light position is in device space, need to transform to local space
588         // before applying to SkCanvas.
589         SkMatrix inverse;
590         if (!ctm.invert(&inverse)) {
591             return false;
592         }
593         inverse.mapPoints(&pt, 1);
594     }
595 
596     rec->fZPlaneParams   = zPlaneParams;
597     rec->fLightPos       = { pt.fX, pt.fY, lightPos.fZ };
598     rec->fLightRadius    = lightRadius;
599     rec->fAmbientColor   = ambientColor;
600     rec->fSpotColor      = spotColor;
601     rec->fFlags          = flags;
602 
603     return true;
604 }
605 
606 // 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)607 void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
608                                const SkPoint3& lightPos, SkScalar lightRadius,
609                                SkColor ambientColor, SkColor spotColor,
610                                uint32_t flags) {
611     SkDrawShadowRec rec;
612     if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor,
613                          flags, canvas->getTotalMatrix(), &rec)) {
614         return;
615     }
616 
617     canvas->private_draw_shadow_rec(path, rec);
618 }
619 
GetLocalBounds(const SkMatrix & ctm,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,uint32_t flags,SkRect * bounds)620 bool SkShadowUtils::GetLocalBounds(const SkMatrix& ctm, const SkPath& path,
621                                    const SkPoint3& zPlaneParams, const SkPoint3& lightPos,
622                                    SkScalar lightRadius, uint32_t flags, SkRect* bounds) {
623     SkDrawShadowRec rec;
624     if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, SK_ColorBLACK, SK_ColorBLACK,
625                          flags, ctm, &rec)) {
626         return false;
627     }
628 
629     SkDrawShadowMetrics::GetLocalBounds(path, rec, ctm, bounds);
630 
631     return true;
632 }
633 
634 //////////////////////////////////////////////////////////////////////////////////////////////
635 
validate_rec(const SkDrawShadowRec & rec)636 static bool validate_rec(const SkDrawShadowRec& rec) {
637     return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
638            SkScalarIsFinite(rec.fLightRadius);
639 }
640 
drawShadow(const SkPath & path,const SkDrawShadowRec & rec)641 void SkBaseDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
642     auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
643                                 SkScalar tx, SkScalar ty, bool hasPerspective) {
644         if (vertices->priv().vertexCount()) {
645             // For perspective shadows we've already computed the shadow in world space,
646             // and we can't translate it without changing it. Otherwise we concat the
647             // change in translation from the cached version.
648             SkAutoDeviceTransformRestore adr(
649                     this,
650                     hasPerspective ? SkMatrix::I()
651                                    : this->localToDevice() * SkMatrix::Translate(tx, ty));
652             this->drawVertices(vertices, SkBlender::Mode(mode), paint);
653         }
654     };
655 
656     if (!validate_rec(rec)) {
657         return;
658     }
659 
660     SkMatrix viewMatrix = this->localToDevice();
661     SkAutoDeviceTransformRestore adr(this, SkMatrix::I());
662 
663     ShadowedPath shadowedPath(&path, &viewMatrix);
664 
665     bool tiltZPlane = tilted(rec.fZPlaneParams);
666     bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
667     bool directional = SkToBool(rec.fFlags & SkShadowFlags::kDirectionalLight_ShadowFlag);
668     bool uncached = tiltZPlane || path.isVolatile();
669 
670     SkPoint3 zPlaneParams = rec.fZPlaneParams;
671     SkPoint3 devLightPos = rec.fLightPos;
672     if (!directional) {
673         viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
674     }
675     float lightRadius = rec.fLightRadius;
676 
677     if (SkColorGetA(rec.fAmbientColor) > 0) {
678         bool success = false;
679         if (uncached) {
680             sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
681                                                                           zPlaneParams,
682                                                                           transparent);
683             if (vertices) {
684                 SkPaint paint;
685                 // Run the vertex color through a GaussianColorFilter and then modulate the
686                 // grayscale result of that against our 'color' param.
687                 paint.setColorFilter(
688                     SkColorFilters::Blend(rec.fAmbientColor,
689                                                   SkBlendMode::kModulate)->makeComposed(
690                                                                SkColorFilterPriv::MakeGaussian()));
691                 this->drawVertices(vertices.get(), SkBlender::Mode(SkBlendMode::kModulate), paint);
692                 success = true;
693             }
694         }
695 
696         if (!success) {
697             AmbientVerticesFactory factory;
698             factory.fOccluderHeight = zPlaneParams.fZ;
699             factory.fTransparent = transparent;
700             if (viewMatrix.hasPerspective()) {
701                 factory.fOffset.set(0, 0);
702             } else {
703                 factory.fOffset.fX = viewMatrix.getTranslateX();
704                 factory.fOffset.fY = viewMatrix.getTranslateY();
705             }
706 
707             if (!draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor)) {
708                 // Pretransform the path to avoid transforming the stroke, below.
709                 SkPath devSpacePath;
710                 path.transform(viewMatrix, &devSpacePath);
711                 devSpacePath.setIsVolatile(true);
712 
713                 // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
714                 // the tesselation, and sets the alpha on the path to 1/AmbientRecipAlpha (or 'a').
715                 //
716                 // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
717                 // can be calculated by interpolating:
718                 //
719                 //            original edge        outer edge
720                 //         |       |<---------- r ------>|
721                 //         |<------|--- f -------------->|
722                 //         |       |                     |
723                 //    alpha = 1  alpha = a          alpha = 0
724                 //
725                 // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
726                 //
727                 // We now need to outset the path to place the new edge in the center of the
728                 // blur region:
729                 //
730                 //             original   new
731                 //         |       |<------|--- r ------>|
732                 //         |<------|--- f -|------------>|
733                 //         |       |<- o ->|<--- f/2 --->|
734                 //
735                 //     r = o + f/2, so o = r - f/2
736                 //
737                 // We outset by using the stroker, so the strokeWidth is o/2.
738                 //
739                 SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
740                 SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
741                 SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
742                 SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
743 
744                 // Now draw with blur
745                 SkPaint paint;
746                 paint.setColor(rec.fAmbientColor);
747                 paint.setStrokeWidth(strokeWidth);
748                 paint.setStyle(SkPaint::kStrokeAndFill_Style);
749                 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(blurRadius);
750                 bool respectCTM = false;
751                 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
752                 this->drawPath(devSpacePath, paint);
753             }
754         }
755     }
756 
757     if (SkColorGetA(rec.fSpotColor) > 0) {
758         bool success = false;
759         if (uncached) {
760             sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
761                                                                        zPlaneParams,
762                                                                        devLightPos, lightRadius,
763                                                                        transparent,
764                                                                        directional);
765             if (vertices) {
766                 SkPaint paint;
767                 // Run the vertex color through a GaussianColorFilter and then modulate the
768                 // grayscale result of that against our 'color' param.
769                 paint.setColorFilter(
770                     SkColorFilters::Blend(rec.fSpotColor,
771                                                   SkBlendMode::kModulate)->makeComposed(
772                                                       SkColorFilterPriv::MakeGaussian()));
773                 this->drawVertices(vertices.get(), SkBlender::Mode(SkBlendMode::kModulate), paint);
774                 success = true;
775             }
776         }
777 
778         if (!success) {
779             SpotVerticesFactory factory;
780             factory.fOccluderHeight = zPlaneParams.fZ;
781             factory.fDevLightPos = devLightPos;
782             factory.fLightRadius = lightRadius;
783 
784             SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
785             factory.fLocalCenter = center;
786             viewMatrix.mapPoints(&center, 1);
787             SkScalar radius, scale;
788             if (SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag)) {
789                 SkDrawShadowMetrics::GetDirectionalParams(zPlaneParams.fZ, devLightPos.fX,
790                                                           devLightPos.fY, devLightPos.fZ,
791                                                           lightRadius, &radius, &scale,
792                                                           &factory.fOffset);
793             } else {
794                 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
795                                                    devLightPos.fY - center.fY, devLightPos.fZ,
796                                                    lightRadius, &radius, &scale, &factory.fOffset);
797             }
798 
799             SkRect devBounds;
800             viewMatrix.mapRect(&devBounds, path.getBounds());
801             if (transparent ||
802                 SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
803                 SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
804                 // if the translation of the shadow is big enough we're going to end up
805                 // filling the entire umbra, we can treat these as all the same
806                 if (directional) {
807                     factory.fOccluderType =
808                             SpotVerticesFactory::OccluderType::kDirectionalTransparent;
809                 } else {
810                     factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
811                 }
812             } else if (directional) {
813                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kDirectional;
814             } else if (factory.fOffset.length()*scale + scale < radius) {
815                 // if we don't translate more than the blur distance, can assume umbra is covered
816                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra;
817             } else if (path.isConvex()) {
818                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra;
819             } else {
820                 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
821             }
822             // need to add this after we classify the shadow
823             factory.fOffset.fX += viewMatrix.getTranslateX();
824             factory.fOffset.fY += viewMatrix.getTranslateY();
825 
826             SkColor color = rec.fSpotColor;
827 #ifdef DEBUG_SHADOW_CHECKS
828             switch (factory.fOccluderType) {
829                 case SpotVerticesFactory::OccluderType::kPointTransparent:
830                     color = 0xFFD2B48C;  // tan for transparent
831                     break;
832                 case SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra:
833                     color = 0xFFFFA500;   // orange for opaque
834                     break;
835                 case SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra:
836                     color = 0xFFE5E500;  // corn yellow for covered
837                     break;
838                 case SpotVerticesFactory::OccluderType::kDirectional:
839                 case SpotVerticesFactory::OccluderType::kDirectionalTransparent:
840                     color = 0xFF550000;  // dark red for directional
841                     break;
842             }
843 #endif
844             if (!draw_shadow(factory, drawVertsProc, shadowedPath, color)) {
845                 // draw with blur
846                 SkMatrix shadowMatrix;
847                 if (!SkDrawShadowMetrics::GetSpotShadowTransform(devLightPos, lightRadius,
848                                                                  viewMatrix, zPlaneParams,
849                                                                  path.getBounds(), directional,
850                                                                  &shadowMatrix, &radius)) {
851                     return;
852                 }
853                 SkAutoDeviceTransformRestore adr2(this, shadowMatrix);
854 
855                 SkPaint paint;
856                 paint.setColor(rec.fSpotColor);
857                 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
858                 bool respectCTM = false;
859                 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
860                 this->drawPath(path, paint);
861             }
862         }
863     }
864 }
865