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