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