SkShadowUtils.cpp 32 KB

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