Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(162)

Side by Side Diff: samplecode/SampleLighting.cpp

Issue 1245883003: Move LightingShader to effects (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Address 64b gcc memory issues (seems to require more space than others) Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « gyp/effects.gypi ('k') | src/core/SkBitmapProcShader.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 1
2 /* 2 /*
3 * Copyright 2015 Google Inc. 3 * Copyright 2015 Google Inc.
4 * 4 *
5 * Use of this source code is governed by a BSD-style license that can be 5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file. 6 * found in the LICENSE file.
7 */ 7 */
8 #include "SampleCode.h" 8 #include "SampleCode.h"
9 #include "Resources.h" 9 #include "Resources.h"
10 10
11 #include "SkCanvas.h" 11 #include "SkCanvas.h"
12 #include "SkErrorInternals.h" 12 #include "SkImageDecoder.h"
13 #include "SkGr.h" 13 #include "SkLightingShader.h"
14 #include "SkPoint3.h"
15 #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
25 class LightingShader : public SkShader {
26 public:
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& v iewM,
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
76 private:
77 SkBitmap fDiffuseMap;
78 SkBitmap fNormalMap;
79 Light fLight;
80 SkColor fAmbientColor;
81 };
82
83 SkFlattenable* 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
109 class LightingFP : public GrFragmentProcessor {
110 public:
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(EmitArgs& args) override {
133
134 GrGLFragmentBuilder* fpb = args.fBuilder->getFragmentShaderBuilder() ;
135
136 // add uniforms
137 const char* lightDirUniName = NULL;
138 fLightDirUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragme nt_Visibility,
139 kVec3f_GrSLType, kDefault_GrSLPre cision,
140 "LightDir", &lightDirUniName);
141
142 const char* lightColorUniName = NULL;
143 fLightColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFrag ment_Visibility,
144 kVec4f_GrSLType, kDefault_GrSLP recision,
145 "LightColor", &lightColorUniNam e);
146
147 const char* ambientColorUniName = NULL;
148 fAmbientColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFr agment_Visibility,
149 kVec4f_GrSLType, kDefault_GrS LPrecision,
150 "AmbientColor", &ambientColor UniName);
151
152 fpb->codeAppend("vec4 diffuseColor = ");
153 fpb->appendTextureLookupAndModulate(args.fInputColor, args.fSamplers [0],
154 args.fCoords[0].c_str(), args.fC oords[0].getType());
155 fpb->codeAppend(";");
156
157 fpb->codeAppend("vec4 normalColor = ");
158 fpb->appendTextureLookup(args.fSamplers[1], args.fCoords[0].c_str(),
159 args.fCoords[0].getType());
160 fpb->codeAppend(";");
161
162 fpb->codeAppend("vec3 normal = normalize(2.0*(normalColor.rgb - vec3 (0.5)));");
163 fpb->codeAppendf("vec3 lightDir = normalize(%s);", lightDirUniName);
164 fpb->codeAppend("float NdotL = dot(normal, lightDir);");
165 // diffuse light
166 fpb->codeAppendf("vec3 result = %s.rgb*diffuseColor.rgb*NdotL;", lig htColorUniName);
167 // ambient light
168 fpb->codeAppendf("result += %s.rgb;", ambientColorUniName);
169 fpb->codeAppendf("%s = vec4(result.rgb, diffuseColor.a);", args.fOut putColor);
170 }
171
172 void setData(const GrGLProgramDataManager& pdman, const GrProcessor& pro c) override {
173 const LightingFP& lightingFP = proc.cast<LightingFP>();
174
175 SkVector3 lightDir = lightingFP.lightDir();
176 if (lightDir != fLightDir) {
177 pdman.set3fv(fLightDirUni, 1, &lightDir.fX);
178 fLightDir = lightDir;
179 }
180
181 GrColor lightColor = lightingFP.lightColor();
182 if (lightColor != fLightColor) {
183 GrGLfloat c[4];
184 GrColorToRGBAFloat(lightColor, c);
185 pdman.set4fv(fLightColorUni, 1, c);
186 fLightColor = lightColor;
187 }
188
189 GrColor ambientColor = lightingFP.ambientColor();
190 if (ambientColor != fAmbientColor) {
191 GrGLfloat c[4];
192 GrColorToRGBAFloat(ambientColor, c);
193 pdman.set4fv(fAmbientColorUni, 1, c);
194 fAmbientColor = ambientColor;
195 }
196 }
197
198 static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
199 GrProcessorKeyBuilder* b) {
200 // const LightingFP& lightingFP = proc.cast<LightingFP>();
201 // only one shader generated currently
202 b->add32(0x0);
203 }
204
205 private:
206 SkVector3 fLightDir;
207 GrGLProgramDataManager::UniformHandle fLightDirUni;
208
209 GrColor fLightColor;
210 GrGLProgramDataManager::UniformHandle fLightColorUni;
211
212 GrColor fAmbientColor;
213 GrGLProgramDataManager::UniformHandle fAmbientColorUni;
214 };
215
216 GrGLFragmentProcessor* createGLInstance() const override { return SkNEW(Ligh tingGLFP); }
217
218 void getGLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) con st override {
219 LightingGLFP::GenKey(*this, caps, b);
220 }
221
222 const char* name() const override { return "LightingFP"; }
223
224 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
225 inout->mulByUnknownFourComponents();
226 }
227
228 SkVector3 lightDir() const { return fLightDir; }
229 GrColor lightColor() const { return fLightColor; }
230 GrColor ambientColor() const { return fAmbientColor; }
231
232 private:
233 bool onIsEqual(const GrFragmentProcessor& proc) const override {
234 const LightingFP& lightingFP = proc.cast<LightingFP>();
235 return fDeviceTransform == lightingFP.fDeviceTransform &&
236 fDiffuseTextureAccess == lightingFP.fDiffuseTextureAccess &&
237 fNormalTextureAccess == lightingFP.fNormalTextureAccess &&
238 fLightDir == lightingFP.fLightDir &&
239 fLightColor == lightingFP.fLightColor &&
240 fAmbientColor == lightingFP.fAmbientColor;
241 }
242
243 GrCoordTransform fDeviceTransform;
244 GrTextureAccess fDiffuseTextureAccess;
245 GrTextureAccess fNormalTextureAccess;
246 SkVector3 fLightDir;
247 GrColor fLightColor;
248 GrColor fAmbientColor;
249 };
250
251 bool LightingShader::asFragmentProcessor(GrContext* context, const SkPaint& pain t,
252 const SkMatrix& viewM, const SkMatrix* localMatrix,
253 GrColor* color, GrProcessorDataManager* ,
254 GrFragmentProcessor** fp) const {
255 // we assume diffuse and normal maps have same width and height
256 // TODO: support different sizes
257 SkASSERT(fDiffuseMap.width() == fNormalMap.width() &&
258 fDiffuseMap.height() == fNormalMap.height());
259 SkMatrix matrix;
260 matrix.setIDiv(fDiffuseMap.width(), fDiffuseMap.height());
261
262 SkMatrix lmInverse;
263 if (!this->getLocalMatrix().invert(&lmInverse)) {
264 return false;
265 }
266 if (localMatrix) {
267 SkMatrix inv;
268 if (!localMatrix->invert(&inv)) {
269 return false;
270 }
271 lmInverse.postConcat(inv);
272 }
273 matrix.preConcat(lmInverse);
274
275 // Must set wrap and filter on the sampler before requesting a texture. In t wo places below
276 // we check the matrix scale factors to determine how to interpret the filte r quality setting.
277 // This completely ignores the complexity of the drawVertices case where exp licit local coords
278 // are provided by the caller.
279 GrTextureParams::FilterMode textureFilterMode = GrTextureParams::kBilerp_Fil terMode;
280 switch (paint.getFilterQuality()) {
281 case kNone_SkFilterQuality:
282 textureFilterMode = GrTextureParams::kNone_FilterMode;
283 break;
284 case kLow_SkFilterQuality:
285 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
286 break;
287 case kMedium_SkFilterQuality:{
288 SkMatrix matrix;
289 matrix.setConcat(viewM, this->getLocalMatrix());
290 if (matrix.getMinScale() < SK_Scalar1) {
291 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
292 } else {
293 // Don't trigger MIP level generation unnecessarily.
294 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
295 }
296 break;
297 }
298 case kHigh_SkFilterQuality:
299 default:
300 SkErrorInternals::SetError(kInvalidPaint_SkError,
301 "Sorry, I don't understand the filtering "
302 "mode you asked for. Falling back to "
303 "MIPMaps.");
304 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
305 break;
306
307 }
308
309 // TODO: support other tile modes
310 GrTextureParams params(kClamp_TileMode, textureFilterMode);
311 SkAutoTUnref<GrTexture> diffuseTexture(GrRefCachedBitmapTexture(context, fDi ffuseMap, &params));
312 if (!diffuseTexture) {
313 SkErrorInternals::SetError(kInternalError_SkError,
314 "Couldn't convert bitmap to texture.");
315 return false;
316 }
317
318 SkAutoTUnref<GrTexture> normalTexture(GrRefCachedBitmapTexture(context, fNor malMap, &params));
319 if (!normalTexture) {
320 SkErrorInternals::SetError(kInternalError_SkError,
321 "Couldn't convert bitmap to texture.");
322 return false;
323 }
324
325 GrColor lightColor = GrColorPackRGBA(SkColorGetR(fLight.fColor), SkColorGetG (fLight.fColor),
326 SkColorGetB(fLight.fColor), SkColorGetA (fLight.fColor));
327 GrColor ambientColor = GrColorPackRGBA(SkColorGetR(fAmbientColor), SkColorGe tG(fAmbientColor),
328 SkColorGetB(fAmbientColor), SkColorGe tA(fAmbientColor));
329
330 *fp = SkNEW_ARGS(LightingFP, (diffuseTexture, normalTexture, matrix,
331 fLight.fDirection, lightColor, ambientColor));
332 *color = GrColorPackA4(paint.getAlpha());
333 return true;
334 }
335 14
336 //////////////////////////////////////////////////////////////////////////// 15 ////////////////////////////////////////////////////////////////////////////
337 16
338 class LightingView : public SampleView { 17 class LightingView : public SampleView {
339 public: 18 public:
340 SkAutoTUnref<LightingShader> fShader; 19 SkAutoTUnref<SkShader> fShader;
341 SkBitmap fDiffuseBitmap; 20 SkBitmap fDiffuseBitmap;
342 SkBitmap fNormalBitmap; 21 SkBitmap fNormalBitmap;
343 SkScalar fLightAngle; 22 SkScalar fLightAngle;
344 int fColorFactor; 23 int fColorFactor;
24 SkColor fAmbientColor;
345 25
346 LightingView() { 26 LightingView() {
347 SkString diffusePath = GetResourcePath("brickwork-texture.jpg"); 27 SkString diffusePath = GetResourcePath("brickwork-texture.jpg");
348 SkImageDecoder::DecodeFile(diffusePath.c_str(), &fDiffuseBitmap); 28 SkImageDecoder::DecodeFile(diffusePath.c_str(), &fDiffuseBitmap);
349 SkString normalPath = GetResourcePath("brickwork_normal-map.jpg"); 29 SkString normalPath = GetResourcePath("brickwork_normal-map.jpg");
350 SkImageDecoder::DecodeFile(normalPath.c_str(), &fNormalBitmap); 30 SkImageDecoder::DecodeFile(normalPath.c_str(), &fNormalBitmap);
351 31
352 fLightAngle = 0.0f; 32 fLightAngle = 0.0f;
353 fColorFactor = 0; 33 fColorFactor = 0;
354 34
355 LightingShader::Light light; 35 SkLightingShader::Light light;
356 light.fColor = SkColorSetRGB(0xff, 0xff, 0xff); 36 light.fColor = SkColorSetRGB(0xff, 0xff, 0xff);
357 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f); 37 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f);
358 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f); 38 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f);
359 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f); 39 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f);
360 40
361 SkColor ambient = SkColorSetRGB(0x1f, 0x1f, 0x1f); 41 fAmbientColor = SkColorSetRGB(0x1f, 0x1f, 0x1f);
362 42
363 fShader.reset(SkNEW_ARGS(LightingShader, (fDiffuseBitmap, fNormalBitmap, light, ambient))); 43 fShader.reset(SkLightingShader::Create(fDiffuseBitmap, fNormalBitmap,
44 light, fAmbientColor));
364 } 45 }
365 46
366 virtual ~LightingView() {} 47 virtual ~LightingView() {}
367 48
368 protected: 49 protected:
369 // overrides from SkEventSink 50 // overrides from SkEventSink
370 bool onQuery(SkEvent* evt) override { 51 bool onQuery(SkEvent* evt) override {
371 if (SampleCode::TitleQ(*evt)) { 52 if (SampleCode::TitleQ(*evt)) {
372 SampleCode::TitleR(evt, "Lighting"); 53 SampleCode::TitleR(evt, "Lighting");
373 return true; 54 return true;
374 } 55 }
375 return this->INHERITED::onQuery(evt); 56 return this->INHERITED::onQuery(evt);
376 } 57 }
377 58
378 void onDrawContent(SkCanvas* canvas) override { 59 void onDrawContent(SkCanvas* canvas) override {
379 fLightAngle += 0.015f; 60 fLightAngle += 0.015f;
380 fColorFactor++; 61 fColorFactor++;
381 62
382 LightingShader::Light light; 63 SkLightingShader::Light light;
383 light.fColor = SkColorSetRGB(0xff, 0xff, (fColorFactor >> 1) & 0xff); 64 light.fColor = SkColorSetRGB(0xff, 0xff, (fColorFactor >> 1) & 0xff);
384 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f); 65 light.fDirection.fX = SkScalarSin(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f);
385 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f); 66 light.fDirection.fY = SkScalarCos(fLightAngle)*SkScalarSin(SK_ScalarPI*0 .25f);
386 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f); 67 light.fDirection.fZ = SkScalarCos(SK_ScalarPI*0.25f);
387 68
388 fShader.get()->setLight(light); 69 fShader.reset(SkLightingShader::Create(fDiffuseBitmap, fNormalBitmap,
70 light, fAmbientColor));
389 71
390 SkPaint paint; 72 SkPaint paint;
391 paint.setShader(fShader); 73 paint.setShader(fShader);
392 paint.setColor(SK_ColorBLACK); 74 paint.setColor(SK_ColorBLACK);
393 75
394 SkRect r = SkRect::MakeWH((SkScalar)fDiffuseBitmap.width(), 76 SkRect r = SkRect::MakeWH((SkScalar)fDiffuseBitmap.width(),
395 (SkScalar)fDiffuseBitmap.height()); 77 (SkScalar)fDiffuseBitmap.height());
396 canvas->drawRect(r, paint); 78 canvas->drawRect(r, paint);
397 79
398 // so we're constantly updating 80 // so we're constantly updating
399 this->inval(NULL); 81 this->inval(NULL);
400 } 82 }
401 83
402 SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) ove rride { 84 SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) ove rride {
403 this->inval(NULL); 85 this->inval(NULL);
404 return this->INHERITED::onFindClickHandler(x, y, modi); 86 return this->INHERITED::onFindClickHandler(x, y, modi);
405 } 87 }
406 88
407 private: 89 private:
408 typedef SampleView INHERITED; 90 typedef SampleView INHERITED;
409 }; 91 };
410 92
411 ////////////////////////////////////////////////////////////////////////////// 93 //////////////////////////////////////////////////////////////////////////////
412 94
413 static SkView* MyFactory() { return new LightingView; } 95 static SkView* MyFactory() { return new LightingView; }
414 static SkViewRegister reg(MyFactory); 96 static SkViewRegister reg(MyFactory);
OLDNEW
« no previous file with comments | « gyp/effects.gypi ('k') | src/core/SkBitmapProcShader.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698