blob: a002a9320f9843762dae1a492ad84a391ab10d31 [file] [log] [blame]
jvanverthd17a3292015-07-09 09:04:16 -07001
2/*
3 * Copyright 2015 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8#include "SampleCode.h"
9#include "Resources.h"
10
11#include "SkCanvas.h"
12#include "SkErrorInternals.h"
13#include "SkGr.h"
robertphillips3d32d762015-07-13 13:16:44 -070014#include "SkPoint3.h"
jvanverthd17a3292015-07-09 09:04:16 -070015#include "SkReadBuffer.h"
16#include "SkShader.h"
17#include "SkWriteBuffer.h"
18#include "GrFragmentProcessor.h"
19#include "GrCoordTransform.h"
20#include "gl/GrGLProcessor.h"
21#include "gl/builders/GrGLProgramBuilder.h"
22
23///////////////////////////////////////////////////////////////////////////////
24
jvanverthd17a3292015-07-09 09:04:16 -070025class LightingShader : public SkShader {
26public:
27 struct Light {
28 SkVector3 fDirection;
29 SkColor fColor; // assumed to be linear color
30 };
31
32 LightingShader(const SkBitmap& diffuse, const SkBitmap& normal, const Light& light,
33 const SkColor ambient)
34 : fDiffuseMap(diffuse)
35 , fNormalMap(normal)
36 , fLight(light)
37 , fAmbientColor(ambient) {}
38
39 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(LightingShader);
40
41 void flatten(SkWriteBuffer& buf) const override {
42 buf.writeBitmap(fDiffuseMap);
43 buf.writeBitmap(fNormalMap);
44 buf.writeScalarArray(&fLight.fDirection.fX, 3);
45 buf.writeColor(fLight.fColor);
46 buf.writeColor(fAmbientColor);
47 }
48
49 bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
50 const SkMatrix* localMatrix, GrColor* color,
51 GrProcessorDataManager*, GrFragmentProcessor** fp) const override;
52
53 SkShader::BitmapType asABitmap(SkBitmap* bitmap, SkMatrix* matrix,
54 SkShader::TileMode* xy) const override {
55 if (bitmap) {
56 *bitmap = fDiffuseMap;
57 }
58 if (matrix) {
59 matrix->reset();
60 }
61 if (xy) {
62 xy[0] = kClamp_TileMode;
63 xy[1] = kClamp_TileMode;
64 }
65 return kDefault_BitmapType;
66 }
67
68#ifndef SK_IGNORE_TO_STRING
69 void toString(SkString* str) const override {
70 str->appendf("LightingShader: ()");
71 }
72#endif
73
74 void setLight(const Light& light) { fLight = light; }
75
76private:
77 SkBitmap fDiffuseMap;
78 SkBitmap fNormalMap;
79 Light fLight;
80 SkColor fAmbientColor;
81};
82
83SkFlattenable* LightingShader::CreateProc(SkReadBuffer& buf) {
84 SkBitmap diffuse;
85 if (!buf.readBitmap(&diffuse)) {
86 return NULL;
87 }
88 diffuse.setImmutable();
89
90 SkBitmap normal;
91 if (!buf.readBitmap(&normal)) {
92 return NULL;
93 }
94 normal.setImmutable();
95
96 Light light;
97 if (!buf.readScalarArray(&light.fDirection.fX, 3)) {
98 return NULL;
99 }
100 light.fColor = buf.readColor();
101
102 SkColor ambient = buf.readColor();
103
104 return SkNEW_ARGS(LightingShader, (diffuse, normal, light, ambient));
105}
106
107////////////////////////////////////////////////////////////////////////////
108
109class LightingFP : public GrFragmentProcessor {
110public:
111 LightingFP(GrTexture* diffuse, GrTexture* normal, const SkMatrix& matrix,
112 SkVector3 lightDir, GrColor lightColor, GrColor ambientColor)
113 : fDeviceTransform(kDevice_GrCoordSet, matrix)
114 , fDiffuseTextureAccess(diffuse)
115 , fNormalTextureAccess(normal)
116 , fLightDir(lightDir)
117 , fLightColor(lightColor)
118 , fAmbientColor(ambientColor) {
119 this->addCoordTransform(&fDeviceTransform);
120 this->addTextureAccess(&fDiffuseTextureAccess);
121 this->addTextureAccess(&fNormalTextureAccess);
122
123 this->initClassID<LightingFP>();
124 }
125
126 class LightingGLFP : public GrGLFragmentProcessor {
127 public:
128 LightingGLFP() : fLightColor(GrColor_ILLEGAL) {
129 fLightDir.fX = 10000.0f;
130 }
131
132 void emitCode(GrGLFPBuilder* builder,
133 const GrFragmentProcessor& fp,
134 const char* outputColor,
135 const char* inputColor,
136 const TransformedCoordsArray& coords,
137 const TextureSamplerArray& samplers) override {
138
139 GrGLFragmentBuilder* fpb = builder->getFragmentShaderBuilder();
140
141 // add uniforms
142 const char* lightDirUniName = NULL;
143 fLightDirUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
144 kVec3f_GrSLType, kDefault_GrSLPrecision,
145 "LightDir", &lightDirUniName);
146
147 const char* lightColorUniName = NULL;
148 fLightColorUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
149 kVec4f_GrSLType, kDefault_GrSLPrecision,
150 "LightColor", &lightColorUniName);
151
152 const char* ambientColorUniName = NULL;
153 fAmbientColorUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
154 kVec4f_GrSLType, kDefault_GrSLPrecision,
155 "AmbientColor", &ambientColorUniName);
156
157 fpb->codeAppend("vec4 diffuseColor = ");
158 fpb->appendTextureLookupAndModulate(inputColor, samplers[0],
159 coords[0].c_str(), coords[0].getType());
160 fpb->codeAppend(";");
161
162 fpb->codeAppend("vec4 normalColor = ");
163 fpb->appendTextureLookup(samplers[1], coords[0].c_str(), coords[0].getType());
164 fpb->codeAppend(";");
165
166 fpb->codeAppend("vec3 normal = normalize(2.0*(normalColor.rgb - vec3(0.5)));");
167 fpb->codeAppendf("vec3 lightDir = normalize(%s);", lightDirUniName);
168 fpb->codeAppend("float NdotL = dot(normal, lightDir);");
169 // diffuse light
170 fpb->codeAppendf("vec3 result = %s.rgb*diffuseColor.rgb*NdotL;", lightColorUniName);
171 // ambient light
172 fpb->codeAppendf("result += %s.rgb;", ambientColorUniName);
173 fpb->codeAppendf("%s = vec4(result.rgb, diffuseColor.a);", outputColor);
174 }
175
176 void setData(const GrGLProgramDataManager& pdman, const GrProcessor& proc) override {
177 const LightingFP& lightingFP = proc.cast<LightingFP>();
178
179 SkVector3 lightDir = lightingFP.lightDir();
180 if (lightDir != fLightDir) {
181 pdman.set3fv(fLightDirUni, 1, &lightDir.fX);
182 fLightDir = lightDir;
183 }
184
185 GrColor lightColor = lightingFP.lightColor();
186 if (lightColor != fLightColor) {
187 GrGLfloat c[4];
188 GrColorToRGBAFloat(lightColor, c);
189 pdman.set4fv(fLightColorUni, 1, c);
190 fLightColor = lightColor;
191 }
192
193 GrColor ambientColor = lightingFP.ambientColor();
194 if (ambientColor != fAmbientColor) {
195 GrGLfloat c[4];
196 GrColorToRGBAFloat(ambientColor, c);
197 pdman.set4fv(fAmbientColorUni, 1, c);
198 fAmbientColor = ambientColor;
199 }
200 }
201
202 static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
203 GrProcessorKeyBuilder* b) {
204// const LightingFP& lightingFP = proc.cast<LightingFP>();
205 // only one shader generated currently
206 b->add32(0x0);
207 }
208
209 private:
210 SkVector3 fLightDir;
211 GrGLProgramDataManager::UniformHandle fLightDirUni;
212
213 GrColor fLightColor;
214 GrGLProgramDataManager::UniformHandle fLightColorUni;
215
216 GrColor fAmbientColor;
217 GrGLProgramDataManager::UniformHandle fAmbientColorUni;
218 };
219
220 GrGLFragmentProcessor* createGLInstance() const override { return SkNEW(LightingGLFP); }
221
222 void getGLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override {
223 LightingGLFP::GenKey(*this, caps, b);
224 }
225
226 const char* name() const override { return "LightingFP"; }
227
228 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
229 inout->mulByUnknownFourComponents();
230 }
231
232 SkVector3 lightDir() const { return fLightDir; }
233 GrColor lightColor() const { return fLightColor; }
234 GrColor ambientColor() const { return fAmbientColor; }
235
236private:
237 bool onIsEqual(const GrFragmentProcessor& proc) const override {
238 const LightingFP& lightingFP = proc.cast<LightingFP>();
239 return fDeviceTransform == lightingFP.fDeviceTransform &&
240 fDiffuseTextureAccess == lightingFP.fDiffuseTextureAccess &&
241 fNormalTextureAccess == lightingFP.fNormalTextureAccess &&
242 fLightDir == lightingFP.fLightDir &&
243 fLightColor == lightingFP.fLightColor &&
244 fAmbientColor == lightingFP.fAmbientColor;
245 }
246
247 GrCoordTransform fDeviceTransform;
248 GrTextureAccess fDiffuseTextureAccess;
249 GrTextureAccess fNormalTextureAccess;
250 SkVector3 fLightDir;
251 GrColor fLightColor;
252 GrColor fAmbientColor;
253};
254
255bool LightingShader::asFragmentProcessor(GrContext* context, const SkPaint& paint,
256 const SkMatrix& viewM, const SkMatrix* localMatrix,
257 GrColor* color, GrProcessorDataManager*,
258 GrFragmentProcessor** fp) const {
259 // we assume diffuse and normal maps have same width and height
260 // TODO: support different sizes
261 SkASSERT(fDiffuseMap.width() == fNormalMap.width() &&
262 fDiffuseMap.height() == fNormalMap.height());
263 SkMatrix matrix;
264 matrix.setIDiv(fDiffuseMap.width(), fDiffuseMap.height());
265
266 SkMatrix lmInverse;
267 if (!this->getLocalMatrix().invert(&lmInverse)) {
268 return false;
269 }
270 if (localMatrix) {
271 SkMatrix inv;
272 if (!localMatrix->invert(&inv)) {
273 return false;
274 }
275 lmInverse.postConcat(inv);
276 }
277 matrix.preConcat(lmInverse);
278
279 // Must set wrap and filter on the sampler before requesting a texture. In two places below
280 // we check the matrix scale factors to determine how to interpret the filter quality setting.
281 // This completely ignores the complexity of the drawVertices case where explicit local coords
282 // are provided by the caller.
283 GrTextureParams::FilterMode textureFilterMode = GrTextureParams::kBilerp_FilterMode;
284 switch (paint.getFilterQuality()) {
285 case kNone_SkFilterQuality:
286 textureFilterMode = GrTextureParams::kNone_FilterMode;
287 break;
288 case kLow_SkFilterQuality:
289 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
290 break;
291 case kMedium_SkFilterQuality:{
292 SkMatrix matrix;
293 matrix.setConcat(viewM, this->getLocalMatrix());
294 if (matrix.getMinScale() < SK_Scalar1) {
295 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
296 } else {
297 // Don't trigger MIP level generation unnecessarily.
298 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
299 }
300 break;
301 }
302 case kHigh_SkFilterQuality:
303 default:
304 SkErrorInternals::SetError(kInvalidPaint_SkError,
305 "Sorry, I don't understand the filtering "
306 "mode you asked for. Falling back to "
307 "MIPMaps.");
308 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
309 break;
310
311 }
312
313 // TODO: support other tile modes
314 GrTextureParams params(kClamp_TileMode, textureFilterMode);
315 SkAutoTUnref<GrTexture> diffuseTexture(GrRefCachedBitmapTexture(context, fDiffuseMap, &params));
316 if (!diffuseTexture) {
317 SkErrorInternals::SetError(kInternalError_SkError,
318 "Couldn't convert bitmap to texture.");
319 return false;
320 }
321
322 SkAutoTUnref<GrTexture> normalTexture(GrRefCachedBitmapTexture(context, fNormalMap, &params));
323 if (!normalTexture) {
324 SkErrorInternals::SetError(kInternalError_SkError,
325 "Couldn't convert bitmap to texture.");
326 return false;
327 }
328
329 GrColor lightColor = GrColorPackRGBA(SkColorGetR(fLight.fColor), SkColorGetG(fLight.fColor),
330 SkColorGetB(fLight.fColor), SkColorGetA(fLight.fColor));
331 GrColor ambientColor = GrColorPackRGBA(SkColorGetR(fAmbientColor), SkColorGetG(fAmbientColor),
332 SkColorGetB(fAmbientColor), SkColorGetA(fAmbientColor));
333
334 *fp = SkNEW_ARGS(LightingFP, (diffuseTexture, normalTexture, matrix,
335 fLight.fDirection, lightColor, ambientColor));
336 *color = GrColorPackA4(paint.getAlpha());
337 return true;
338}
339
340////////////////////////////////////////////////////////////////////////////
341
342class LightingView : public SampleView {
343public:
344 SkAutoTUnref<LightingShader> fShader;
345 SkBitmap fDiffuseBitmap;
346 SkBitmap fNormalBitmap;
347 SkScalar fLightAngle;
348 int fColorFactor;
349
350 LightingView() {
351 SkString diffusePath = GetResourcePath("brickwork-texture.jpg");
352 SkImageDecoder::DecodeFile(diffusePath.c_str(), &fDiffuseBitmap);
353 SkString normalPath = GetResourcePath("brickwork_normal-map.jpg");
354 SkImageDecoder::DecodeFile(normalPath.c_str(), &fNormalBitmap);
355
356 fLightAngle = 0.0f;
357 fColorFactor = 0;
358
359 LightingShader::Light light;
360 light.fColor = SkColorSetRGB(0xff, 0xff, 0xff);
361 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0.25f);
362 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0.25f);
363 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f);
364
365 SkColor ambient = SkColorSetRGB(0x1f, 0x1f, 0x1f);
366
367 fShader.reset(SkNEW_ARGS(LightingShader, (fDiffuseBitmap, fNormalBitmap, light, ambient)));
368 }
369
370 virtual ~LightingView() {}
371
372protected:
373 // overrides from SkEventSink
374 bool onQuery(SkEvent* evt) override {
375 if (SampleCode::TitleQ(*evt)) {
376 SampleCode::TitleR(evt, "Lighting");
377 return true;
378 }
379 return this->INHERITED::onQuery(evt);
380 }
381
382 void onDrawContent(SkCanvas* canvas) override {
383 fLightAngle += 0.015f;
384 fColorFactor++;
385
386 LightingShader::Light light;
387 light.fColor = SkColorSetRGB(0xff, 0xff, (fColorFactor >> 1) & 0xff);
388 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0.25f);
389 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0.25f);
390 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f);
391
392 fShader.get()->setLight(light);
393
394 SkPaint paint;
395 paint.setShader(fShader);
396 paint.setColor(SK_ColorBLACK);
397
398 SkRect r = SkRect::MakeWH((SkScalar)fDiffuseBitmap.width(),
399 (SkScalar)fDiffuseBitmap.height());
400 canvas->drawRect(r, paint);
401
402 // so we're constantly updating
403 this->inval(NULL);
404 }
405
406 SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) override {
407 this->inval(NULL);
408 return this->INHERITED::onFindClickHandler(x, y, modi);
409 }
410
411private:
412 typedef SampleView INHERITED;
413};
414
415//////////////////////////////////////////////////////////////////////////////
416
417static SkView* MyFactory() { return new LightingView; }
418static SkViewRegister reg(MyFactory);