GrGradientShader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Copyright 2018 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 "src/gpu/gradients/GrGradientShader.h"
  8. #include "src/gpu/gradients/generated/GrClampedGradientEffect.h"
  9. #include "src/gpu/gradients/generated/GrTiledGradientEffect.h"
  10. #include "src/gpu/gradients/generated/GrLinearGradientLayout.h"
  11. #include "src/gpu/gradients/generated/GrRadialGradientLayout.h"
  12. #include "src/gpu/gradients/generated/GrSweepGradientLayout.h"
  13. #include "src/gpu/gradients/generated/GrTwoPointConicalGradientLayout.h"
  14. #include "src/gpu/gradients/GrGradientBitmapCache.h"
  15. #include "src/gpu/gradients/generated/GrDualIntervalGradientColorizer.h"
  16. #include "src/gpu/gradients/generated/GrSingleIntervalGradientColorizer.h"
  17. #include "src/gpu/gradients/generated/GrTextureGradientColorizer.h"
  18. #include "src/gpu/gradients/generated/GrUnrolledBinaryGradientColorizer.h"
  19. #include "include/private/GrRecordingContext.h"
  20. #include "src/gpu/GrCaps.h"
  21. #include "src/gpu/GrColor.h"
  22. #include "src/gpu/GrColorSpaceInfo.h"
  23. #include "src/gpu/GrRecordingContextPriv.h"
  24. #include "src/gpu/SkGr.h"
  25. // Intervals smaller than this (that aren't hard stops) on low-precision-only devices force us to
  26. // use the textured gradient
  27. static const SkScalar kLowPrecisionIntervalLimit = 0.01f;
  28. // Each cache entry costs 1K or 2K of RAM. Each bitmap will be 1x256 at either 32bpp or 64bpp.
  29. static const int kMaxNumCachedGradientBitmaps = 32;
  30. static const int kGradientTextureSize = 256;
  31. // NOTE: signature takes raw pointers to the color/pos arrays and a count to make it easy for
  32. // MakeColorizer to transparently take care of hard stops at the end points of the gradient.
  33. static std::unique_ptr<GrFragmentProcessor> make_textured_colorizer(const SkPMColor4f* colors,
  34. const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
  35. static GrGradientBitmapCache gCache(kMaxNumCachedGradientBitmaps, kGradientTextureSize);
  36. // Use 8888 or F16, depending on the destination config.
  37. // TODO: Use 1010102 for opaque gradients, at least if destination is 1010102?
  38. SkColorType colorType = kRGBA_8888_SkColorType;
  39. if (GrColorTypeIsWiderThan(args.fDstColorSpaceInfo->colorType(), 8) &&
  40. args.fContext->priv().caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
  41. colorType = kRGBA_F16_SkColorType;
  42. }
  43. SkAlphaType alphaType = premul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
  44. SkBitmap bitmap;
  45. gCache.getGradient(colors, positions, count, colorType, alphaType, &bitmap);
  46. SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
  47. SkASSERT(bitmap.isImmutable());
  48. sk_sp<GrTextureProxy> proxy = GrMakeCachedBitmapProxy(
  49. args.fContext->priv().proxyProvider(), bitmap);
  50. if (proxy == nullptr) {
  51. SkDebugf("Gradient won't draw. Could not create texture.");
  52. return nullptr;
  53. }
  54. return GrTextureGradientColorizer::Make(std::move(proxy));
  55. }
  56. // Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
  57. // the gradient.
  58. static std::unique_ptr<GrFragmentProcessor> make_colorizer(const SkPMColor4f* colors,
  59. const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
  60. // If there are hard stops at the beginning or end, the first and/or last color should be
  61. // ignored by the colorizer since it should only be used in a clamped border color. By detecting
  62. // and removing these stops at the beginning, it makes optimizing the remaining color stops
  63. // simpler.
  64. // SkGradientShaderBase guarantees that pos[0] == 0 by adding a dummy
  65. bool bottomHardStop = SkScalarNearlyEqual(positions[0], positions[1]);
  66. // The same is true for pos[end] == 1
  67. bool topHardStop = SkScalarNearlyEqual(positions[count - 2], positions[count - 1]);
  68. int offset = 0;
  69. if (bottomHardStop) {
  70. offset += 1;
  71. count--;
  72. }
  73. if (topHardStop) {
  74. count--;
  75. }
  76. // Two remaining colors means a single interval from 0 to 1
  77. // (but it may have originally been a 3 or 4 color gradient with 1-2 hard stops at the ends)
  78. if (count == 2) {
  79. return GrSingleIntervalGradientColorizer::Make(colors[offset], colors[offset + 1]);
  80. }
  81. // Do an early test for the texture fallback to skip all of the other tests for specific
  82. // analytic support of the gradient (and compatibility with the hardware), when it's definitely
  83. // impossible to use an analytic solution.
  84. bool tryAnalyticColorizer = count <= GrUnrolledBinaryGradientColorizer::kMaxColorCount;
  85. // The remaining analytic colorizers use scale*t+bias, and the scale/bias values can become
  86. // quite large when thresholds are close (but still outside the hardstop limit). If float isn't
  87. // 32-bit, output can be incorrect if the thresholds are too close together. However, the
  88. // analytic shaders are higher quality, so they can be used with lower precision hardware when
  89. // the thresholds are not ill-conditioned.
  90. const GrShaderCaps* caps = args.fContext->priv().caps()->shaderCaps();
  91. if (!caps->floatIs32Bits() && tryAnalyticColorizer) {
  92. // Could run into problems, check if thresholds are close together (with a limit of .01, so
  93. // that scales will be less than 100, which leaves 4 decimals of precision on 16-bit).
  94. for (int i = offset; i < count - 1; i++) {
  95. SkScalar dt = SkScalarAbs(positions[i] - positions[i + 1]);
  96. if (dt <= kLowPrecisionIntervalLimit && dt > SK_ScalarNearlyZero) {
  97. tryAnalyticColorizer = false;
  98. break;
  99. }
  100. }
  101. }
  102. if (tryAnalyticColorizer) {
  103. if (count == 3) {
  104. // Must be a dual interval gradient, where the middle point is at offset+1 and the two
  105. // intervals share the middle color stop.
  106. return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
  107. colors[offset + 1], colors[offset + 2],
  108. positions[offset + 1]);
  109. } else if (count == 4 && SkScalarNearlyEqual(positions[offset + 1],
  110. positions[offset + 2])) {
  111. // Two separate intervals that join at the same threshold position
  112. return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
  113. colors[offset + 2], colors[offset + 3],
  114. positions[offset + 1]);
  115. }
  116. // The single and dual intervals are a specialized case of the unrolled binary search
  117. // colorizer which can analytically render gradients of up to 8 intervals (up to 9 or 16
  118. // colors depending on how many hard stops are inserted).
  119. std::unique_ptr<GrFragmentProcessor> unrolled = GrUnrolledBinaryGradientColorizer::Make(
  120. colors + offset, positions + offset, count);
  121. if (unrolled) {
  122. return unrolled;
  123. }
  124. }
  125. // Otherwise fall back to a rasterized gradient sampled by a texture, which can handle
  126. // arbitrary gradients (the only downside being sampling resolution).
  127. return make_textured_colorizer(colors + offset, positions + offset, count, premul, args);
  128. }
  129. // Combines the colorizer and layout with an appropriately configured master effect based on the
  130. // gradient's tile mode
  131. static std::unique_ptr<GrFragmentProcessor> make_gradient(const SkGradientShaderBase& shader,
  132. const GrFPArgs& args, std::unique_ptr<GrFragmentProcessor> layout) {
  133. // No shader is possible if a layout couldn't be created, e.g. a layout-specific Make() returned
  134. // null.
  135. if (layout == nullptr) {
  136. return nullptr;
  137. }
  138. // Convert all colors into destination space and into SkPMColor4fs, and handle
  139. // premul issues depending on the interpolation mode
  140. bool inputPremul = shader.getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag;
  141. bool allOpaque = true;
  142. SkAutoSTMalloc<4, SkPMColor4f> colors(shader.fColorCount);
  143. SkColor4fXformer xformedColors(shader.fOrigColors4f, shader.fColorCount,
  144. shader.fColorSpace.get(), args.fDstColorSpaceInfo->colorSpace());
  145. for (int i = 0; i < shader.fColorCount; i++) {
  146. const SkColor4f& upmColor = xformedColors.fColors[i];
  147. colors[i] = inputPremul ? upmColor.premul()
  148. : SkPMColor4f{ upmColor.fR, upmColor.fG, upmColor.fB, upmColor.fA };
  149. if (allOpaque && !SkScalarNearlyEqual(colors[i].fA, 1.0)) {
  150. allOpaque = false;
  151. }
  152. }
  153. // SkGradientShader stores positions implicitly when they are evenly spaced, but the getPos()
  154. // implementation performs a branch for every position index. Since the shader conversion
  155. // requires lots of position tests, calculate all of the positions up front if needed.
  156. SkTArray<SkScalar, true> implicitPos;
  157. SkScalar* positions;
  158. if (shader.fOrigPos) {
  159. positions = shader.fOrigPos;
  160. } else {
  161. implicitPos.reserve(shader.fColorCount);
  162. SkScalar posScale = SK_Scalar1 / (shader.fColorCount - 1);
  163. for (int i = 0 ; i < shader.fColorCount; i++) {
  164. implicitPos.push_back(SkIntToScalar(i) * posScale);
  165. }
  166. positions = implicitPos.begin();
  167. }
  168. // All gradients are colorized the same way, regardless of layout
  169. std::unique_ptr<GrFragmentProcessor> colorizer = make_colorizer(
  170. colors.get(), positions, shader.fColorCount, inputPremul, args);
  171. if (colorizer == nullptr) {
  172. return nullptr;
  173. }
  174. // The master effect has to export premul colors, but under certain conditions it doesn't need
  175. // to do anything to achieve that: i.e. its interpolating already premul colors (inputPremul)
  176. // or all the colors have a = 1, in which case premul is a no op. Note that this allOpaque
  177. // check is more permissive than SkGradientShaderBase's isOpaque(), since we can optimize away
  178. // the make-premul op for two point conical gradients (which report false for isOpaque).
  179. bool makePremul = !inputPremul && !allOpaque;
  180. // All tile modes are supported (unless something was added to SkShader)
  181. std::unique_ptr<GrFragmentProcessor> master;
  182. switch(shader.getTileMode()) {
  183. case SkTileMode::kRepeat:
  184. master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
  185. /* mirror */ false, makePremul, allOpaque);
  186. break;
  187. case SkTileMode::kMirror:
  188. master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
  189. /* mirror */ true, makePremul, allOpaque);
  190. break;
  191. case SkTileMode::kClamp:
  192. // For the clamped mode, the border colors are the first and last colors, corresponding
  193. // to t=0 and t=1, because SkGradientShaderBase enforces that by adding color stops as
  194. // appropriate. If there is a hard stop, this grabs the expected outer colors for the
  195. // border.
  196. master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
  197. colors[0], colors[shader.fColorCount - 1], makePremul, allOpaque);
  198. break;
  199. case SkTileMode::kDecal:
  200. // Even if the gradient colors are opaque, the decal borders are transparent so
  201. // disable that optimization
  202. master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
  203. SK_PMColor4fTRANSPARENT, SK_PMColor4fTRANSPARENT,
  204. makePremul, /* colorsAreOpaque */ false);
  205. break;
  206. }
  207. if (master == nullptr) {
  208. // Unexpected tile mode
  209. return nullptr;
  210. }
  211. if (args.fInputColorIsOpaque) {
  212. return GrFragmentProcessor::OverrideInput(std::move(master), SK_PMColor4fWHITE, false);
  213. }
  214. return GrFragmentProcessor::MulChildByInputAlpha(std::move(master));
  215. }
  216. namespace GrGradientShader {
  217. std::unique_ptr<GrFragmentProcessor> MakeLinear(const SkLinearGradient& shader,
  218. const GrFPArgs& args) {
  219. return make_gradient(shader, args, GrLinearGradientLayout::Make(shader, args));
  220. }
  221. std::unique_ptr<GrFragmentProcessor> MakeRadial(const SkRadialGradient& shader,
  222. const GrFPArgs& args) {
  223. return make_gradient(shader,args, GrRadialGradientLayout::Make(shader, args));
  224. }
  225. std::unique_ptr<GrFragmentProcessor> MakeSweep(const SkSweepGradient& shader,
  226. const GrFPArgs& args) {
  227. return make_gradient(shader,args, GrSweepGradientLayout::Make(shader, args));
  228. }
  229. std::unique_ptr<GrFragmentProcessor> MakeConical(const SkTwoPointConicalGradient& shader,
  230. const GrFPArgs& args) {
  231. return make_gradient(shader, args, GrTwoPointConicalGradientLayout::Make(shader, args));
  232. }
  233. #if GR_TEST_UTILS
  234. RandomParams::RandomParams(SkRandom* random) {
  235. // Set color count to min of 2 so that we don't trigger the const color optimization and make
  236. // a non-gradient processor.
  237. fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
  238. fUseColors4f = random->nextBool();
  239. // if one color, omit stops, otherwise randomly decide whether or not to
  240. if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
  241. fStops = nullptr;
  242. } else {
  243. fStops = fStopStorage;
  244. }
  245. // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
  246. if (fUseColors4f) {
  247. fColorSpace = GrTest::TestColorSpace(random);
  248. }
  249. SkScalar stop = 0.f;
  250. for (int i = 0; i < fColorCount; ++i) {
  251. if (fUseColors4f) {
  252. fColors4f[i].fR = random->nextUScalar1();
  253. fColors4f[i].fG = random->nextUScalar1();
  254. fColors4f[i].fB = random->nextUScalar1();
  255. fColors4f[i].fA = random->nextUScalar1();
  256. } else {
  257. fColors[i] = random->nextU();
  258. }
  259. if (fStops) {
  260. fStops[i] = stop;
  261. stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
  262. }
  263. }
  264. fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
  265. }
  266. #endif
  267. }