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