SkNormalMapSource.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /*
  2. * Copyright 2016 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/core/SkNormalMapSource.h"
  8. #include "include/core/SkMatrix.h"
  9. #include "src/core/SkArenaAlloc.h"
  10. #include "src/core/SkNormalSource.h"
  11. #include "src/core/SkReadBuffer.h"
  12. #include "src/core/SkWriteBuffer.h"
  13. #include "src/shaders/SkLightingShader.h"
  14. #if SK_SUPPORT_GPU
  15. #include "src/gpu/GrCoordTransform.h"
  16. #include "src/gpu/SkGr.h"
  17. #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
  18. #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
  19. class NormalMapFP : public GrFragmentProcessor {
  20. public:
  21. static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> mapFP,
  22. const SkMatrix& invCTM) {
  23. return std::unique_ptr<GrFragmentProcessor>(new NormalMapFP(std::move(mapFP), invCTM));
  24. }
  25. const char* name() const override { return "NormalMapFP"; }
  26. const SkMatrix& invCTM() const { return fInvCTM; }
  27. std::unique_ptr<GrFragmentProcessor> clone() const override {
  28. return Make(this->childProcessor(0).clone(), fInvCTM);
  29. }
  30. private:
  31. class GLSLNormalMapFP : public GrGLSLFragmentProcessor {
  32. public:
  33. GLSLNormalMapFP() : fColumnMajorInvCTM22{0.0f} {}
  34. void emitCode(EmitArgs& args) override {
  35. GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
  36. GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
  37. // add uniform
  38. const char* xformUniName = nullptr;
  39. fXformUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat2x2_GrSLType,
  40. "Xform", &xformUniName);
  41. SkString dstNormalColorName("dstNormalColor");
  42. this->emitChild(0, &dstNormalColorName, args);
  43. fragBuilder->codeAppendf("float3 normal = normalize(%s.rgb - float3(0.5));",
  44. dstNormalColorName.c_str());
  45. // If there's no x & y components, return (0, 0, +/- 1) instead to avoid division by 0
  46. fragBuilder->codeAppend( "if (abs(normal.z) > 0.999) {");
  47. fragBuilder->codeAppendf(" %s = normalize(half4(0.0, 0.0, half(normal.z), 0.0));",
  48. args.fOutputColor);
  49. // Else, Normalizing the transformed X and Y, while keeping constant both Z and the
  50. // vector's angle in the XY plane. This maintains the "slope" for the surface while
  51. // appropriately rotating the normal regardless of any anisotropic scaling that occurs.
  52. // Here, we call 'scaling factor' the number that must divide the transformed X and Y so
  53. // that the normal's length remains equal to 1.
  54. fragBuilder->codeAppend( "} else {");
  55. fragBuilder->codeAppendf(" float2 transformed = %s * normal.xy;",
  56. xformUniName);
  57. fragBuilder->codeAppend( " float scalingFactorSquared = "
  58. "( (transformed.x * transformed.x) "
  59. "+ (transformed.y * transformed.y) )"
  60. "/(1.0 - (normal.z * normal.z));");
  61. fragBuilder->codeAppendf(" %s = half4(half2(transformed * "
  62. "inversesqrt(scalingFactorSquared)),"
  63. "half(normal.z), 0.0);",
  64. args.fOutputColor);
  65. fragBuilder->codeAppend( "}");
  66. }
  67. static void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder* b) {
  68. b->add32(0x0);
  69. }
  70. private:
  71. void onSetData(const GrGLSLProgramDataManager& pdman,
  72. const GrFragmentProcessor& proc) override {
  73. const NormalMapFP& normalMapFP = proc.cast<NormalMapFP>();
  74. const SkMatrix& invCTM = normalMapFP.invCTM();
  75. fColumnMajorInvCTM22[0] = invCTM.get(SkMatrix::kMScaleX);
  76. fColumnMajorInvCTM22[1] = invCTM.get(SkMatrix::kMSkewY);
  77. fColumnMajorInvCTM22[2] = invCTM.get(SkMatrix::kMSkewX);
  78. fColumnMajorInvCTM22[3] = invCTM.get(SkMatrix::kMScaleY);
  79. pdman.setMatrix2f(fXformUni, fColumnMajorInvCTM22);
  80. }
  81. private:
  82. // Upper-right 2x2 corner of the inverse of the CTM in column-major form
  83. float fColumnMajorInvCTM22[4];
  84. GrGLSLProgramDataManager::UniformHandle fXformUni;
  85. };
  86. void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override {
  87. GLSLNormalMapFP::GenKey(*this, caps, b);
  88. }
  89. NormalMapFP(std::unique_ptr<GrFragmentProcessor> mapFP, const SkMatrix& invCTM)
  90. : INHERITED(kMappedNormalsFP_ClassID, kNone_OptimizationFlags)
  91. , fInvCTM(invCTM) {
  92. this->registerChildProcessor(std::move(mapFP));
  93. }
  94. GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLSLNormalMapFP; }
  95. bool onIsEqual(const GrFragmentProcessor& proc) const override {
  96. const NormalMapFP& normalMapFP = proc.cast<NormalMapFP>();
  97. return fInvCTM == normalMapFP.fInvCTM;
  98. }
  99. SkMatrix fInvCTM;
  100. typedef GrFragmentProcessor INHERITED;
  101. };
  102. std::unique_ptr<GrFragmentProcessor> SkNormalMapSourceImpl::asFragmentProcessor(
  103. const GrFPArgs& args) const {
  104. std::unique_ptr<GrFragmentProcessor> mapFP = as_SB(fMapShader)->asFragmentProcessor(args);
  105. if (!mapFP) {
  106. return nullptr;
  107. }
  108. return NormalMapFP::Make(std::move(mapFP), fInvCTM);
  109. }
  110. #endif // SK_SUPPORT_GPU
  111. ////////////////////////////////////////////////////////////////////////////
  112. SkNormalMapSourceImpl::Provider::Provider(const SkNormalMapSourceImpl& source,
  113. SkShaderBase::Context* mapContext)
  114. : fSource(source)
  115. , fMapContext(mapContext) {}
  116. SkNormalSource::Provider* SkNormalMapSourceImpl::asProvider(const SkShaderBase::ContextRec &rec,
  117. SkArenaAlloc* alloc) const {
  118. SkMatrix normTotalInv;
  119. if (!this->computeNormTotalInverse(rec, &normTotalInv)) {
  120. return nullptr;
  121. }
  122. // Normals really aren't colors, so to ensure we can always make the context, we ignore
  123. // the rec's colorspace
  124. SkColorSpace* dstColorSpace = nullptr;
  125. // Overriding paint's alpha because we need the normal map's RGB channels to be unpremul'd
  126. SkPaint overridePaint {*(rec.fPaint)};
  127. overridePaint.setAlpha(0xFF);
  128. SkShaderBase::ContextRec overrideRec(overridePaint, *(rec.fMatrix), rec.fLocalMatrix,
  129. rec.fDstColorType, dstColorSpace);
  130. auto* context = as_SB(fMapShader)->makeContext(overrideRec, alloc);
  131. if (!context) {
  132. return nullptr;
  133. }
  134. return alloc->make<Provider>(*this, context);
  135. }
  136. bool SkNormalMapSourceImpl::computeNormTotalInverse(const SkShaderBase::ContextRec& rec,
  137. SkMatrix* normTotalInverse) const {
  138. SkMatrix total = SkMatrix::Concat(*rec.fMatrix, as_SB(fMapShader)->getLocalMatrix());
  139. if (rec.fLocalMatrix) {
  140. total.preConcat(*rec.fLocalMatrix);
  141. }
  142. return total.invert(normTotalInverse);
  143. }
  144. #define BUFFER_MAX 16
  145. void SkNormalMapSourceImpl::Provider::fillScanLine(int x, int y, SkPoint3 output[],
  146. int count) const {
  147. SkPMColor tmpNormalColors[BUFFER_MAX];
  148. do {
  149. int n = SkTMin(count, BUFFER_MAX);
  150. fMapContext->shadeSpan(x, y, tmpNormalColors, n);
  151. for (int i = 0; i < n; i++) {
  152. SkPoint3 tempNorm;
  153. tempNorm.set(SkIntToScalar(SkGetPackedR32(tmpNormalColors[i])) - 127.0f,
  154. SkIntToScalar(SkGetPackedG32(tmpNormalColors[i])) - 127.0f,
  155. SkIntToScalar(SkGetPackedB32(tmpNormalColors[i])) - 127.0f);
  156. tempNorm.normalize();
  157. if (!SkScalarNearlyEqual(SkScalarAbs(tempNorm.fZ), 1.0f)) {
  158. SkVector transformed = fSource.fInvCTM.mapVector(tempNorm.fX, tempNorm.fY);
  159. // Normalizing the transformed X and Y, while keeping constant both Z and the
  160. // vector's angle in the XY plane. This maintains the "slope" for the surface while
  161. // appropriately rotating the normal for any anisotropic scaling that occurs.
  162. // Here, we call scaling factor the number that must divide the transformed X and Y
  163. // so that the normal's length remains equal to 1.
  164. SkScalar scalingFactorSquared =
  165. (SkScalarSquare(transformed.fX) + SkScalarSquare(transformed.fY))
  166. / (1.0f - SkScalarSquare(tempNorm.fZ));
  167. SkScalar invScalingFactor = SkScalarInvert(SkScalarSqrt(scalingFactorSquared));
  168. output[i].fX = transformed.fX * invScalingFactor;
  169. output[i].fY = transformed.fY * invScalingFactor;
  170. output[i].fZ = tempNorm.fZ;
  171. } else {
  172. output[i] = {0.0f, 0.0f, tempNorm.fZ};
  173. output[i].normalize();
  174. }
  175. SkASSERT(SkScalarNearlyEqual(output[i].length(), 1.0f));
  176. }
  177. output += n;
  178. x += n;
  179. count -= n;
  180. } while (count > 0);
  181. }
  182. ////////////////////////////////////////////////////////////////////////////////
  183. sk_sp<SkFlattenable> SkNormalMapSourceImpl::CreateProc(SkReadBuffer& buf) {
  184. sk_sp<SkShader> mapShader = buf.readFlattenable<SkShaderBase>();
  185. SkMatrix invCTM;
  186. buf.readMatrix(&invCTM);
  187. return sk_make_sp<SkNormalMapSourceImpl>(std::move(mapShader), invCTM);
  188. }
  189. void SkNormalMapSourceImpl::flatten(SkWriteBuffer& buf) const {
  190. this->INHERITED::flatten(buf);
  191. buf.writeFlattenable(fMapShader.get());
  192. buf.writeMatrix(fInvCTM);
  193. }
  194. ////////////////////////////////////////////////////////////////////////////
  195. sk_sp<SkNormalSource> SkNormalSource::MakeFromNormalMap(sk_sp<SkShader> map, const SkMatrix& ctm) {
  196. SkMatrix invCTM;
  197. if (!ctm.invert(&invCTM) || !map) {
  198. return nullptr;
  199. }
  200. return sk_make_sp<SkNormalMapSourceImpl>(std::move(map), invCTM);
  201. }