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

Side by Side Diff: src/core/SkLightingShader.cpp

Issue 1304673002: Revert "Update SkLightingShader to support rotation" (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: 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 | « src/core/SkLightingShader.h ('k') | src/core/SkPoint3.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1
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
9 #include "SkBitmapProcState.h"
10 #include "SkColor.h"
11 #include "SkEmptyShader.h"
12 #include "SkErrorInternals.h"
13 #include "SkLightingShader.h"
14 #include "SkMathPriv.h"
15 #include "SkPoint3.h"
16 #include "SkReadBuffer.h"
17 #include "SkWriteBuffer.h"
18
19 ////////////////////////////////////////////////////////////////////////////
20
21 /*
22 SkLightingShader TODOs:
23 support other than clamp mode
24 allow 'diffuse' & 'normal' to be of different dimensions?
25 support different light types
26 support multiple lights
27 enforce normal map is 4 channel
28 use SkImages instead if SkBitmaps
29
30 To Test:
31 non-opaque diffuse textures
32 A8 diffuse textures
33 down & upsampled draws
34 */
35
36
37
38 /** \class SkLightingShaderImpl
39 This subclass of shader applies lighting.
40 */
41 class SK_API SkLightingShaderImpl : public SkShader {
42 public:
43
44 /** Create a new lighting shader that uses the provided normal map and
45 lights to light the diffuse bitmap.
46 @param diffuse the diffuse bitmap
47 @param normal the normal map
48 @param lights the lights applied to the normal map
49 @param invNormRotation rotation applied to the normal map's normals
50 @param diffLocalM the local matrix for the diffuse coordinates
51 @param normLocalM the local matrix for the normal coordinates
52 */
53 SkLightingShaderImpl(const SkBitmap& diffuse, const SkBitmap& normal,
54 const SkLightingShader::Lights* lights,
55 const SkVector& invNormRotation,
56 const SkMatrix* diffLocalM, const SkMatrix* normLocalM)
57 : INHERITED(diffLocalM)
58 , fDiffuseMap(diffuse)
59 , fNormalMap(normal)
60 , fLights(SkRef(lights))
61 , fInvNormRotation(invNormRotation) {
62
63 if (normLocalM) {
64 fNormLocalMatrix = *normLocalM;
65 } else {
66 fNormLocalMatrix.reset();
67 }
68 // Pre-cache so future calls to fNormLocalMatrix.getType() are threadsaf e.
69 (void)fNormLocalMatrix.getType();
70
71 }
72
73 bool isOpaque() const override;
74
75 bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& v iewM,
76 const SkMatrix* localMatrix, GrColor* color,
77 GrProcessorDataManager*, GrFragmentProcessor** fp) const override;
78
79 size_t contextSize() const override;
80
81 class LightingShaderContext : public SkShader::Context {
82 public:
83 // The context takes ownership of the states. It will call their destruc tors
84 // but will NOT free the memory.
85 LightingShaderContext(const SkLightingShaderImpl&, const ContextRec&,
86 SkBitmapProcState* diffuseState, SkBitmapProcState * normalState);
87 ~LightingShaderContext() override;
88
89 void shadeSpan(int x, int y, SkPMColor[], int count) override;
90
91 uint32_t getFlags() const override { return fFlags; }
92
93 private:
94 SkBitmapProcState* fDiffuseState;
95 SkBitmapProcState* fNormalState;
96 uint32_t fFlags;
97
98 typedef SkShader::Context INHERITED;
99 };
100
101 SK_TO_STRING_OVERRIDE()
102 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkLightingShaderImpl)
103
104 protected:
105 void flatten(SkWriteBuffer&) const override;
106 Context* onCreateContext(const ContextRec&, void*) const override;
107 bool computeNormTotalInverse(const ContextRec& rec, SkMatrix* normTotalInver se) const;
108
109 private:
110 SkBitmap fDiffuseMap;
111 SkBitmap fNormalMap;
112
113 SkAutoTUnref<const SkLightingShader::Lights> fLights;
114
115 SkMatrix fNormLocalMatrix;
116 SkVector fInvNormRotation;
117
118 friend class SkLightingShader;
119
120 typedef SkShader INHERITED;
121 };
122
123 ////////////////////////////////////////////////////////////////////////////
124
125 #if SK_SUPPORT_GPU
126
127 #include "GrCoordTransform.h"
128 #include "GrFragmentProcessor.h"
129 #include "GrTextureAccess.h"
130 #include "gl/GrGLProcessor.h"
131 #include "gl/builders/GrGLProgramBuilder.h"
132 #include "SkGr.h"
133
134 class LightingFP : public GrFragmentProcessor {
135 public:
136 LightingFP(GrProcessorDataManager* pdm, GrTexture* diffuse, GrTexture* norma l,
137 const SkMatrix& diffMatrix, const SkMatrix& normMatrix,
138 const GrTextureParams& diffParams, const GrTextureParams& normPar ams,
139 const SkLightingShader::Lights* lights, const SkVector& invNormRo tation)
140 : fDiffDeviceTransform(kLocal_GrCoordSet, diffMatrix, diffuse, diffParam s.filterMode())
141 , fNormDeviceTransform(kLocal_GrCoordSet, normMatrix, normal, normParams .filterMode())
142 , fDiffuseTextureAccess(diffuse, diffParams)
143 , fNormalTextureAccess(normal, normParams)
144 , fInvNormRotation(invNormRotation) {
145 this->addCoordTransform(&fDiffDeviceTransform);
146 this->addCoordTransform(&fNormDeviceTransform);
147 this->addTextureAccess(&fDiffuseTextureAccess);
148 this->addTextureAccess(&fNormalTextureAccess);
149
150 // fuse all ambient lights into a single one
151 fAmbientColor.set(0.0f, 0.0f, 0.0f);
152 for (int i = 0; i < lights->numLights(); ++i) {
153 if (SkLight::kAmbient_LightType == lights->light(i).type()) {
154 fAmbientColor += lights->light(i).color();
155 } else {
156 // TODO: handle more than one of these
157 fLightColor = lights->light(i).color();
158 fLightDir = lights->light(i).dir();
159 }
160 }
161
162 this->initClassID<LightingFP>();
163 }
164
165 class LightingGLFP : public GrGLFragmentProcessor {
166 public:
167 LightingGLFP() {
168 fLightDir.fX = 10000.0f;
169 fLightColor.fX = 0.0f;
170 fAmbientColor.fX = 0.0f;
171 fInvNormRotation.fX = 0.0f;
172 }
173
174 void emitCode(EmitArgs& args) override {
175
176 GrGLFragmentBuilder* fpb = args.fBuilder->getFragmentShaderBuilder() ;
177
178 // add uniforms
179 const char* lightDirUniName = NULL;
180 fLightDirUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragme nt_Visibility,
181 kVec3f_GrSLType, kDefault_G rSLPrecision,
182 "LightDir", &lightDirUniNam e);
183
184 const char* lightColorUniName = NULL;
185 fLightColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFrag ment_Visibility,
186 kVec3f_GrSLType, kDefault _GrSLPrecision,
187 "LightColor", &lightColor UniName);
188
189 const char* ambientColorUniName = NULL;
190 fAmbientColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFr agment_Visibility,
191 kVec3f_GrSLType, kDefau lt_GrSLPrecision,
192 "AmbientColor", &ambien tColorUniName);
193
194 const char* xformUniName = NULL;
195 fXformUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragment_ Visibility,
196 kVec2f_GrSLType, kDefault_GrSL Precision,
197 "Xform", &xformUniName);
198
199 fpb->codeAppend("vec4 diffuseColor = ");
200 fpb->appendTextureLookupAndModulate(args.fInputColor, args.fSamplers [0],
201 args.fCoords[0].c_str(),
202 args.fCoords[0].getType());
203 fpb->codeAppend(";");
204
205 fpb->codeAppend("vec4 normalColor = ");
206 fpb->appendTextureLookup(args.fSamplers[1],
207 args.fCoords[1].c_str(),
208 args.fCoords[1].getType());
209 fpb->codeAppend(";");
210
211 fpb->codeAppend("vec3 normal = normalColor.rgb - vec3(0.5);");
212
213 fpb->codeAppendf("mat3 m = mat3(%s.x, -%s.y, 0.0, %s.y, %s.x, 0.0, 0 .0, 0.0, 1.0);",
214 xformUniName, xformUniName, xformUniName, xformUniN ame);
215
216 // TODO: inverse map the light direction vectors in the vertex shade r rather than
217 // transforming all the normals here!
218 fpb->codeAppend("normal = normalize(m*normal);");
219
220 fpb->codeAppendf("float NdotL = clamp(dot(normal, %s), 0.0, 1.0);", lightDirUniName);
221 // diffuse light
222 fpb->codeAppendf("vec3 result = %s*diffuseColor.rgb*NdotL;", lightCo lorUniName);
223 // ambient light
224 fpb->codeAppendf("result += %s;", ambientColorUniName);
225 fpb->codeAppendf("%s = vec4(result.rgb, diffuseColor.a);", args.fOut putColor);
226 }
227
228 static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
229 GrProcessorKeyBuilder* b) {
230 // const LightingFP& lightingFP = proc.cast<LightingFP>();
231 // only one shader generated currently
232 b->add32(0x0);
233 }
234
235 protected:
236 void onSetData(const GrGLProgramDataManager& pdman, const GrProcessor& p roc) override {
237 const LightingFP& lightingFP = proc.cast<LightingFP>();
238
239 const SkVector3& lightDir = lightingFP.lightDir();
240 if (lightDir != fLightDir) {
241 pdman.set3fv(fLightDirUni, 1, &lightDir.fX);
242 fLightDir = lightDir;
243 }
244
245 const SkColor3f& lightColor = lightingFP.lightColor();
246 if (lightColor != fLightColor) {
247 pdman.set3fv(fLightColorUni, 1, &lightColor.fX);
248 fLightColor = lightColor;
249 }
250
251 const SkColor3f& ambientColor = lightingFP.ambientColor();
252 if (ambientColor != fAmbientColor) {
253 pdman.set3fv(fAmbientColorUni, 1, &ambientColor.fX);
254 fAmbientColor = ambientColor;
255 }
256
257 const SkVector& invNormRotation = lightingFP.invNormRotation();
258 if (invNormRotation != fInvNormRotation) {
259 pdman.set2fv(fXformUni, 1, &invNormRotation.fX);
260 fInvNormRotation = invNormRotation;
261 }
262 }
263
264 private:
265 SkVector3 fLightDir;
266 GrGLProgramDataManager::UniformHandle fLightDirUni;
267
268 SkColor3f fLightColor;
269 GrGLProgramDataManager::UniformHandle fLightColorUni;
270
271 SkColor3f fAmbientColor;
272 GrGLProgramDataManager::UniformHandle fAmbientColorUni;
273
274 SkVector fInvNormRotation;
275 GrGLProgramDataManager::UniformHandle fXformUni;
276 };
277
278 void onGetGLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) c onst override {
279 LightingGLFP::GenKey(*this, caps, b);
280 }
281
282 const char* name() const override { return "LightingFP"; }
283
284 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
285 inout->mulByUnknownFourComponents();
286 }
287
288 const SkVector3& lightDir() const { return fLightDir; }
289 const SkColor3f& lightColor() const { return fLightColor; }
290 const SkColor3f& ambientColor() const { return fAmbientColor; }
291 const SkVector& invNormRotation() const { return fInvNormRotation; }
292
293 private:
294 GrGLFragmentProcessor* onCreateGLInstance() const override { return SkNEW(Li ghtingGLFP); }
295
296 bool onIsEqual(const GrFragmentProcessor& proc) const override {
297 const LightingFP& lightingFP = proc.cast<LightingFP>();
298 return fDiffDeviceTransform == lightingFP.fDiffDeviceTransform &&
299 fNormDeviceTransform == lightingFP.fNormDeviceTransform &&
300 fDiffuseTextureAccess == lightingFP.fDiffuseTextureAccess &&
301 fNormalTextureAccess == lightingFP.fNormalTextureAccess &&
302 fLightDir == lightingFP.fLightDir &&
303 fLightColor == lightingFP.fLightColor &&
304 fAmbientColor == lightingFP.fAmbientColor &&
305 fInvNormRotation == lightingFP.fInvNormRotation;
306 }
307
308 GrCoordTransform fDiffDeviceTransform;
309 GrCoordTransform fNormDeviceTransform;
310 GrTextureAccess fDiffuseTextureAccess;
311 GrTextureAccess fNormalTextureAccess;
312 SkVector3 fLightDir;
313 SkColor3f fLightColor;
314 SkColor3f fAmbientColor;
315
316 SkVector fInvNormRotation;
317 };
318
319 ////////////////////////////////////////////////////////////////////////////
320
321 static bool make_mat(const SkBitmap& bm,
322 const SkMatrix& localMatrix1,
323 const SkMatrix* localMatrix2,
324 SkMatrix* result) {
325
326 result->setIDiv(bm.width(), bm.height());
327
328 SkMatrix lmInverse;
329 if (!localMatrix1.invert(&lmInverse)) {
330 return false;
331 }
332 if (localMatrix2) {
333 SkMatrix inv;
334 if (!localMatrix2->invert(&inv)) {
335 return false;
336 }
337 lmInverse.postConcat(inv);
338 }
339 result->preConcat(lmInverse);
340
341 return true;
342 }
343
344 bool SkLightingShaderImpl::asFragmentProcessor(GrContext* context, const SkPaint & paint,
345 const SkMatrix& viewM, const SkMa trix* localMatrix,
346 GrColor* color, GrProcessorDataMa nager* pdm,
347 GrFragmentProcessor** fp) const {
348 // we assume diffuse and normal maps have same width and height
349 // TODO: support different sizes
350 SkASSERT(fDiffuseMap.width() == fNormalMap.width() &&
351 fDiffuseMap.height() == fNormalMap.height());
352 SkMatrix diffM, normM;
353
354 if (!make_mat(fDiffuseMap, this->getLocalMatrix(), localMatrix, &diffM)) {
355 return false;
356 }
357
358 if (!make_mat(fNormalMap, fNormLocalMatrix, localMatrix, &normM)) {
359 return false;
360 }
361
362 bool doBicubic;
363 GrTextureParams::FilterMode diffFilterMode = GrSkFilterQualityToGrFilterMode (
364 SkTMin(paint.getFilterQuality(), kMedium _SkFilterQuality),
365 viewM,
366 this->getLocalMatrix(),
367 &doBicubic);
368 SkASSERT(!doBicubic);
369
370 GrTextureParams::FilterMode normFilterMode = GrSkFilterQualityToGrFilterMode (
371 SkTMin(paint.getFilterQuality(), kMedium _SkFilterQuality),
372 viewM,
373 fNormLocalMatrix,
374 &doBicubic);
375 SkASSERT(!doBicubic);
376
377 // TODO: support other tile modes
378 GrTextureParams diffParams(kClamp_TileMode, diffFilterMode);
379 SkAutoTUnref<GrTexture> diffuseTexture(GrRefCachedBitmapTexture(context,
380 fDiffuseMap, &diffParams));
381 if (!diffuseTexture) {
382 SkErrorInternals::SetError(kInternalError_SkError,
383 "Couldn't convert bitmap to texture.");
384 return false;
385 }
386
387 GrTextureParams normParams(kClamp_TileMode, normFilterMode);
388 SkAutoTUnref<GrTexture> normalTexture(GrRefCachedBitmapTexture(context,
389 fNormalMap, & normParams));
390 if (!normalTexture) {
391 SkErrorInternals::SetError(kInternalError_SkError,
392 "Couldn't convert bitmap to texture.");
393 return false;
394 }
395
396
397 *fp = SkNEW_ARGS(LightingFP, (pdm, diffuseTexture, normalTexture,
398 diffM, normM, diffParams, normParams, fLights,
399 fInvNormRotation));
400
401 *color = GrColorPackA4(paint.getAlpha());
402 return true;
403 }
404 #else
405
406 bool SkLightingShaderImpl::asFragmentProcessor(GrContext* context, const SkPaint & paint,
407 const SkMatrix& viewM, const SkMa trix* localMatrix,
408 GrColor* color, GrProcessorDataMa nager*,
409 GrFragmentProcessor** fp) const {
410 SkDEBUGFAIL("Should not call in GPU-less build");
411 return false;
412 }
413
414 #endif
415
416 ////////////////////////////////////////////////////////////////////////////
417
418 bool SkLightingShaderImpl::isOpaque() const {
419 return fDiffuseMap.isOpaque();
420 }
421
422 size_t SkLightingShaderImpl::contextSize() const {
423 return 2 * sizeof(SkBitmapProcState) + sizeof(LightingShaderContext);
424 }
425
426 SkLightingShaderImpl::LightingShaderContext::LightingShaderContext(const SkLight ingShaderImpl& shader,
427 const Context Rec& rec,
428 SkBitmapProcS tate* diffuseState,
429 SkBitmapProcS tate* normalState)
430 : INHERITED(shader, rec)
431 , fDiffuseState(diffuseState)
432 , fNormalState(normalState)
433 {
434 const SkPixmap& pixmap = fDiffuseState->fPixmap;
435 bool isOpaque = pixmap.isOpaque();
436
437 // update fFlags
438 uint32_t flags = 0;
439 if (isOpaque && (255 == this->getPaintAlpha())) {
440 flags |= kOpaqueAlpha_Flag;
441 }
442
443 fFlags = flags;
444 }
445
446 SkLightingShaderImpl::LightingShaderContext::~LightingShaderContext() {
447 // The bitmap proc states have been created outside of the context on memory that will be freed
448 // elsewhere. Call the destructors but leave the freeing of the memory to th e caller.
449 fDiffuseState->~SkBitmapProcState();
450 fNormalState->~SkBitmapProcState();
451 }
452
453 static inline SkPMColor convert(SkColor3f color, U8CPU a) {
454 if (color.fX <= 0.0f) {
455 color.fX = 0.0f;
456 } else if (color.fX >= 255.0f) {
457 color.fX = 255.0f;
458 }
459
460 if (color.fY <= 0.0f) {
461 color.fY = 0.0f;
462 } else if (color.fY >= 255.0f) {
463 color.fY = 255.0f;
464 }
465
466 if (color.fZ <= 0.0f) {
467 color.fZ = 0.0f;
468 } else if (color.fZ >= 255.0f) {
469 color.fZ = 255.0f;
470 }
471
472 return SkPreMultiplyARGB(a, (int) color.fX, (int) color.fY, (int) color.fZ) ;
473 }
474
475 // larger is better (fewer times we have to loop), but we shouldn't
476 // take up too much stack-space (each one here costs 16 bytes)
477 #define TMP_COUNT 16
478
479 void SkLightingShaderImpl::LightingShaderContext::shadeSpan(int x, int y,
480 SkPMColor result[], int count) {
481 const SkLightingShaderImpl& lightShader = static_cast<const SkLightingShader Impl&>(fShader);
482
483 uint32_t tmpColor[TMP_COUNT], tmpNormal[TMP_COUNT];
484 SkPMColor tmpColor2[2*TMP_COUNT], tmpNormal2[2*TMP_COUNT];
485
486 SkBitmapProcState::MatrixProc diffMProc = fDiffuseState->getMatrixProc();
487 SkBitmapProcState::SampleProc32 diffSProc = fDiffuseState->getSampleProc32() ;
488
489 SkBitmapProcState::MatrixProc normalMProc = fNormalState->getMatrixProc();
490 SkBitmapProcState::SampleProc32 normalSProc = fNormalState->getSampleProc32( );
491
492 int diffMax = fDiffuseState->maxCountForBufferSize(sizeof(tmpColor[0]) * TMP _COUNT);
493 int normMax = fNormalState->maxCountForBufferSize(sizeof(tmpNormal[0]) * TMP _COUNT);
494 int max = SkTMin(diffMax, normMax);
495
496 SkASSERT(fDiffuseState->fPixmap.addr());
497 SkASSERT(fNormalState->fPixmap.addr());
498
499 SkPoint3 norm, xformedNorm;
500
501 do {
502 int n = count;
503 if (n > max) {
504 n = max;
505 }
506
507 diffMProc(*fDiffuseState, tmpColor, n, x, y);
508 diffSProc(*fDiffuseState, tmpColor, n, tmpColor2);
509
510 normalMProc(*fNormalState, tmpNormal, n, x, y);
511 normalSProc(*fNormalState, tmpNormal, n, tmpNormal2);
512
513 for (int i = 0; i < n; ++i) {
514 SkASSERT(0xFF == SkColorGetA(tmpNormal2[i])); // opaque -> unpremul
515 norm.set(SkIntToScalar(SkGetPackedR32(tmpNormal2[i]))-127.0f,
516 SkIntToScalar(SkGetPackedG32(tmpNormal2[i]))-127.0f,
517 SkIntToScalar(SkGetPackedB32(tmpNormal2[i]))-127.0f);
518 norm.normalize();
519
520 xformedNorm.fX = lightShader.fInvNormRotation.fX * norm.fX +
521 lightShader.fInvNormRotation.fY * norm.fY;
522 xformedNorm.fY = lightShader.fInvNormRotation.fX * norm.fX -
523 lightShader.fInvNormRotation.fY * norm.fY;
524 xformedNorm.fZ = norm.fZ;
525
526 SkColor diffColor = SkUnPreMultiply::PMColorToColor(tmpColor2[i]);
527
528 SkColor3f accum = SkColor3f::Make(0.0f, 0.0f, 0.0f);
529 // This is all done in linear unpremul color space (each component 0 ..255.0f though)
530 for (int l = 0; l < lightShader.fLights->numLights(); ++l) {
531 const SkLight& light = lightShader.fLights->light(l);
532
533 if (SkLight::kAmbient_LightType == light.type()) {
534 accum += light.color().makeScale(255.0f);
535 } else {
536 SkScalar NdotL = xformedNorm.dot(light.dir());
537 if (NdotL < 0.0f) {
538 NdotL = 0.0f;
539 }
540
541 accum.fX += light.color().fX * SkColorGetR(diffColor) * Ndot L;
542 accum.fY += light.color().fY * SkColorGetG(diffColor) * Ndot L;
543 accum.fZ += light.color().fZ * SkColorGetB(diffColor) * Ndot L;
544 }
545 }
546
547 result[i] = convert(accum, SkColorGetA(diffColor));
548 }
549
550 result += n;
551 x += n;
552 count -= n;
553 } while (count > 0);
554 }
555
556 ////////////////////////////////////////////////////////////////////////////
557
558 #ifndef SK_IGNORE_TO_STRING
559 void SkLightingShaderImpl::toString(SkString* str) const {
560 str->appendf("LightingShader: ()");
561 }
562 #endif
563
564 SkFlattenable* SkLightingShaderImpl::CreateProc(SkReadBuffer& buf) {
565 SkMatrix diffLocalM;
566 bool hasDiffLocalM = buf.readBool();
567 if (hasDiffLocalM) {
568 buf.readMatrix(&diffLocalM);
569 } else {
570 diffLocalM.reset();
571 }
572
573 SkMatrix normLocalM;
574 bool hasNormLocalM = buf.readBool();
575 if (hasNormLocalM) {
576 buf.readMatrix(&normLocalM);
577 } else {
578 normLocalM.reset();
579 }
580
581 SkBitmap diffuse;
582 if (!buf.readBitmap(&diffuse)) {
583 return NULL;
584 }
585 diffuse.setImmutable();
586
587 SkBitmap normal;
588 if (!buf.readBitmap(&normal)) {
589 return NULL;
590 }
591 normal.setImmutable();
592
593 int numLights = buf.readInt();
594
595 SkLightingShader::Lights::Builder builder;
596
597 for (int l = 0; l < numLights; ++l) {
598 bool isAmbient = buf.readBool();
599
600 SkColor3f color;
601 if (!buf.readScalarArray(&color.fX, 3)) {
602 return NULL;
603 }
604
605 if (isAmbient) {
606 builder.add(SkLight(color));
607 } else {
608 SkVector3 dir;
609 if (!buf.readScalarArray(&dir.fX, 3)) {
610 return NULL;
611 }
612 builder.add(SkLight(color, dir));
613 }
614 }
615
616 SkAutoTUnref<const SkLightingShader::Lights> lights(builder.finish());
617
618 return SkNEW_ARGS(SkLightingShaderImpl, (diffuse, normal, lights,
619 SkVector::Make(1.0f, 0.0f),
620 &diffLocalM, &normLocalM));
621 }
622
623 void SkLightingShaderImpl::flatten(SkWriteBuffer& buf) const {
624 this->INHERITED::flatten(buf);
625
626 bool hasNormLocalM = !fNormLocalMatrix.isIdentity();
627 buf.writeBool(hasNormLocalM);
628 if (hasNormLocalM) {
629 buf.writeMatrix(fNormLocalMatrix);
630 }
631
632 buf.writeBitmap(fDiffuseMap);
633 buf.writeBitmap(fNormalMap);
634
635 buf.writeInt(fLights->numLights());
636 for (int l = 0; l < fLights->numLights(); ++l) {
637 const SkLight& light = fLights->light(l);
638
639 bool isAmbient = SkLight::kAmbient_LightType == light.type();
640
641 buf.writeBool(isAmbient);
642 buf.writeScalarArray(&light.color().fX, 3);
643 if (!isAmbient) {
644 buf.writeScalarArray(&light.dir().fX, 3);
645 }
646 }
647 }
648
649 bool SkLightingShaderImpl::computeNormTotalInverse(const ContextRec& rec,
650 SkMatrix* normTotalInverse) c onst {
651 SkMatrix total;
652 total.setConcat(*rec.fMatrix, fNormLocalMatrix);
653
654 const SkMatrix* m = &total;
655 if (rec.fLocalMatrix) {
656 total.setConcat(*m, *rec.fLocalMatrix);
657 m = &total;
658 }
659 return m->invert(normTotalInverse);
660 }
661
662 SkShader::Context* SkLightingShaderImpl::onCreateContext(const ContextRec& rec,
663 void* storage) const {
664
665 SkMatrix diffTotalInv;
666 // computeTotalInverse was called in SkShader::createContext so we know it w ill succeed
667 SkAssertResult(this->computeTotalInverse(rec, &diffTotalInv));
668
669 SkMatrix normTotalInv;
670 if (!this->computeNormTotalInverse(rec, &normTotalInv)) {
671 return NULL;
672 }
673
674 void* diffuseStateStorage = (char*)storage + sizeof(LightingShaderContext);
675 SkBitmapProcState* diffuseState = SkNEW_PLACEMENT(diffuseStateStorage, SkBit mapProcState);
676 SkASSERT(diffuseState);
677
678 diffuseState->fTileModeX = SkShader::kClamp_TileMode;
679 diffuseState->fTileModeY = SkShader::kClamp_TileMode;
680 diffuseState->fOrigBitmap = fDiffuseMap;
681 if (!diffuseState->chooseProcs(diffTotalInv, *rec.fPaint)) {
682 diffuseState->~SkBitmapProcState();
683 return NULL;
684 }
685
686 void* normalStateStorage = (char*)storage + sizeof(LightingShaderContext) + sizeof(SkBitmapProcState);
687 SkBitmapProcState* normalState = SkNEW_PLACEMENT(normalStateStorage, SkBitma pProcState);
688 SkASSERT(normalState);
689
690 normalState->fTileModeX = SkShader::kClamp_TileMode;
691 normalState->fTileModeY = SkShader::kClamp_TileMode;
692 normalState->fOrigBitmap = fNormalMap;
693 if (!normalState->chooseProcs(normTotalInv, *rec.fPaint)) {
694 diffuseState->~SkBitmapProcState();
695 normalState->~SkBitmapProcState();
696 return NULL;
697 }
698
699 return SkNEW_PLACEMENT_ARGS(storage, LightingShaderContext, (*this, rec,
700 diffuseState, n ormalState));
701 }
702
703 ///////////////////////////////////////////////////////////////////////////////
704
705 static bool bitmap_is_too_big(const SkBitmap& bm) {
706 // SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
707 // communicates between its matrix-proc and its sampler-proc. Until we can
708 // widen that, we have to reject bitmaps that are larger.
709 //
710 static const int kMaxSize = 65535;
711
712 return bm.width() > kMaxSize || bm.height() > kMaxSize;
713 }
714
715 SkShader* SkLightingShader::Create(const SkBitmap& diffuse, const SkBitmap& norm al,
716 const Lights* lights,
717 const SkVector& invNormRotation,
718 const SkMatrix* diffLocalM, const SkMatrix* n ormLocalM) {
719 if (diffuse.isNull() || bitmap_is_too_big(diffuse) ||
720 normal.isNull() || bitmap_is_too_big(normal) ||
721 diffuse.width() != normal.width() ||
722 diffuse.height() != normal.height()) {
723 return nullptr;
724 }
725
726 SkASSERT(SkScalarNearlyEqual(invNormRotation.lengthSqd(), SK_Scalar1));
727
728 return SkNEW_ARGS(SkLightingShaderImpl, (diffuse, normal, lights,
729 invNormRotation, diffLocalM, normLo calM));
730 }
731
732 ///////////////////////////////////////////////////////////////////////////////
733
734 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkLightingShader)
735 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLightingShaderImpl)
736 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
737
738 ///////////////////////////////////////////////////////////////////////////////
OLDNEW
« no previous file with comments | « src/core/SkLightingShader.h ('k') | src/core/SkPoint3.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698