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