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

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

Issue 2118553002: adding new GM to demostrate new shadows (Closed) Base URL: https://skia.googlesource.com/skia@master
Patch Set: Made requested changes Created 4 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
« gm/shadowmaps.cpp ('K') | « src/core/SkShadowShader.h ('k') | no next file » | 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 * 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 "SkLights.h"
9 #include "SkReadBuffer.h"
10 #include "SkShadowShader.h"
11
12 ////////////////////////////////////////////////////////////////////////////
13 #define SK_MAX_NON_AMBIENT_LIGHTS 4
14
15 /** \class SkShadowShaderImpl
16 This subclass of shader applies shadowing
17 */
18 class SkShadowShaderImpl : public SkShader {
19 public:
20 /** Create a new shadowing shader that shadows
21 @param to do to do
22 */
23 SkShadowShaderImpl(sk_sp<SkShader> povDepthShader,
24 sk_sp<SkShader> diffuseShader,
25 sk_sp<SkLights> lights)
26 : povDepthShader(std::move(povDepthShader))
27 , diffuseShader(std::move(diffuseShader))
28 , fLights(std::move(lights)) { }
29
30 bool isOpaque() const override;
31
32 #if SK_SUPPORT_GPU
33 sk_sp<GrFragmentProcessor> asFragmentProcessor(const AsFPArgs&) const overri de;
34 #endif
35
36 class ShadowShaderContext : public SkShader::Context {
37 public:
38 // The context takes ownership of the states. It will call their destruc tors
39 // but will NOT free the memory.
40 ShadowShaderContext(const SkShadowShaderImpl&, const ContextRec&,
41 SkShader::Context* povDepthContext,
42 SkShader::Context* diffuseContext,
43 void* heapAllocated);
44
45 ~ShadowShaderContext() override;
46
47 void shadeSpan(int x, int y, SkPMColor[], int count) override;
48
49 uint32_t getFlags() const override { return fFlags; }
50
51 private:
52 SkShader::Context* fPovDepthContext;
53 SkShader::Context* fDiffuseContext;
54 uint32_t fFlags;
55
56 void* fHeapAllocated;
57
58 typedef SkShader::Context INHERITED;
59 };
60
61 SK_TO_STRING_OVERRIDE()
62 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkShadowShaderImpl)
63
64 protected:
65 void flatten(SkWriteBuffer&) const override;
66 size_t onContextSize(const ContextRec&) const override;
67 Context* onCreateContext(const ContextRec&, void*) const override;
68
69 private:
70 sk_sp<SkShader> povDepthShader;
71 sk_sp<SkShader> diffuseShader;
72 sk_sp<SkLights> fLights;
73
74 friend class SkShadowShader;
75
76 typedef SkShader INHERITED;
77 };
78
79 ////////////////////////////////////////////////////////////////////////////
80
81 #if SK_SUPPORT_GPU
82
83 #include "GrCoordTransform.h"
84 #include "GrFragmentProcessor.h"
85 #include "GrInvariantOutput.h"
86 #include "GrTextureAccess.h"
87 #include "glsl/GrGLSLFragmentProcessor.h"
88 #include "glsl/GrGLSLFragmentShaderBuilder.h"
89 #include "glsl/GrGLSLProgramDataManager.h"
90 #include "glsl/GrGLSLUniformHandler.h"
91 #include "SkGr.h"
92 #include "SkGrPriv.h"
93 #include "SkSpecialImage.h"
94 #include "SkImage_Base.h"
95 #include "SkImageInfo.h"
96 #include "GrContext.h"
97 #include "GrContextOptions.h"
98
99 class ShadowFP : public GrFragmentProcessor {
100 public:
101 ShadowFP(sk_sp<GrFragmentProcessor> povDepth,
102 sk_sp<GrFragmentProcessor> diffuse,
103 sk_sp<SkLights> lights,
104 GrContext* context) {
105
106 // fuse all ambient lights into a single one
107 fAmbientColor.set(0.0f, 0.0f, 0.0f);
108
109 fNumDirLights = 0; // refers to directional lights.
110 for (int i = 0; i < lights->numLights(); ++i) {
111 if (SkLights::Light::kAmbient_LightType == lights->light(i).type()) {
112 fAmbientColor += lights->light(i).color();
113 } else if (fNumDirLights < SK_MAX_NON_AMBIENT_LIGHTS){
114 fLightColor[fNumDirLights] = lights->light(i).color();
115 fLightDir[fNumDirLights] = lights->light(i).dir();
116 SkImage_Base* shadowMap = ((SkImage_Base*)lights->light(i).getSh adowMap().get());
117
118 // this sk_sp gets deleted when the ShadowFP is destroyed, and f rees the GrTexture*
119 fTexture[fNumDirLights] = sk_sp<GrTexture>(shadowMap->asTextureR ef(context,
120 GrTextureParams::Clam pNoFilter(),
121 SkSourceGammaTreatmen t::kIgnore));
122 fDepthMapAccess[fNumDirLights].reset(fTexture[fNumDirLights].get ());
123 this->addTextureAccess(&fDepthMapAccess[fNumDirLights]);
124
125 fNumDirLights++;
robertphillips 2016/07/28 19:47:25 extra '\n' here ?
vjiaoblack 2016/07/29 16:07:30 Done.
126
127 }
128 }
129
130 this->registerChildProcessor(std::move(povDepth));
131 this->registerChildProcessor(std::move(diffuse));
132 this->initClassID<ShadowFP>();
133 }
134
135 class GLSLShadowFP : public GrGLSLFragmentProcessor {
136 public:
137 GLSLShadowFP() { }
138
139 void emitCode(EmitArgs& args) override {
140
141 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
142 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
143
144 // add uniforms
145 int32_t numLights = args.fFp.cast<ShadowFP>().fNumDirLights;
146
147 const char* lightDirUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
148 const char* lightColorUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr} ;
149
150 for (int i = 0; i < numLights; i++) {
robertphillips 2016/07/28 19:47:25 do we still need this init ?
vjiaoblack 2016/07/29 16:07:30 Done.
151 lightDirUniName[i] = nullptr;
152 fLightDirUni[i] = uniformHandler->addUniform(kFragment_GrShaderF lag,
153 kVec3f_GrSLType,
154 kDefault_GrSLPrecis ion,
155 "LightDir" + (i+1),
156 &lightDirUniName[i] );
157
robertphillips 2016/07/28 19:47:25 here too ?
vjiaoblack 2016/07/29 16:07:30 Done.
158 lightColorUniName[i] = nullptr;
159 fLightColorUni[i] = uniformHandler->addUniform(kFragment_GrShade rFlag,
160 kVec3f_GrSLType,
161 kDefault_GrSLPrec ision,
162 "LightColor" + (i +1),
163 &lightColorUniNam e[i]);
164 }
165
166 SkString povDepth("povDepth");
167 this->emitChild(0, nullptr, &povDepth, args);
168
169 SkString diffuseColor("inDiffuseColor");
170 this->emitChild(1, nullptr, &diffuseColor, args);
171
172 SkString depthMaps[SK_MAX_NON_AMBIENT_LIGHTS];
173
174 for (int i = 0; i < numLights; i++) {
175 SkString povCoord("povCoord");
176 povCoord.appendf("%d", i);
177
178 // vMatrixCoord_0_1_Stage0 is the texture sampler coordinates.
179 // povDepth.b * 255 scales it to 0 - 255, bringing it to world s pace,
180 // and the / 400 brings it back to a sampler coordinate, 0 - 1
181 // The 400 comes from the shadowmaps GM.
182 SkString offset("lol");
183 offset.appendf("%d", i);
184
185 fragBuilder->codeAppendf("vec2 %s = (vec2(%s) * povDepth.b * 255 / 400);",
186 offset.c_str(), lightDirUniName[i]);
187
188
189 fragBuilder->codeAppendf("vec2 %s = vec2(vMatrixCoord_0_1_Stage0 .x, "
190 "vMatrixCoord_0_1_Stage0 .y) + "
191 "vec2(%s.x, 0 - %s.y);",
192 povCoord.c_str(), offset.c_str(), offse t.c_str());
193
194 fragBuilder->appendTextureLookup(&depthMaps[i], args.fTexSampler s[i],
robertphillips 2016/07/28 19:47:25 extra '\n' ?
vjiaoblack 2016/07/29 16:07:30 Done.
195
196 povCoord.c_str(),
197 kVec2f_GrSLType);
198 }
199
200 const char* ambientColorUniName = nullptr;
201 fAmbientColorUni = uniformHandler->addUniform(kFragment_GrShaderFlag ,
202 kVec3f_GrSLType, kDefa ult_GrSLPrecision,
203 "AmbientColor", &ambie ntColorUniName);
204
205 fragBuilder->codeAppendf("vec4 resultDiffuseColor = %s;", diffuseCol or.c_str());
206
robertphillips 2016/07/28 19:47:25 // Implement: diffColor * (ambientLightTot + forea
vjiaoblack 2016/07/29 16:07:30 Done.
207 // all the normal vectors point straight up
208 SkString totalLightColor("totalLightColor");
209 fragBuilder->codeAppendf("vec3 %s = vec3(0,0,0);", totalLightColor.c _str());
210
211 for (int i = 0; i < numLights ; i++) {
212 fragBuilder->codeAppendf("if (%s.b >= %s.b) {",
213 povDepth.c_str(), depthMaps[i].c_str()) ;
214 fragBuilder->codeAppendf("%s += dot(vec3(0,0,1), %s) * %s;",
215 totalLightColor.c_str(),
216 lightDirUniName[i],
217 lightColorUniName[i]);
218 fragBuilder->codeAppendf("}");
219 }
220
221 fragBuilder->codeAppendf("%s += %s;",
222 totalLightColor.c_str(),
223 ambientColorUniName);
224
225 fragBuilder->codeAppendf("resultDiffuseColor *= vec4(%s, 1);",
226 totalLightColor.c_str());
227
228 fragBuilder->codeAppendf("%s = resultDiffuseColor;", args.fOutputCol or);
229 }
230
231 static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
232 GrProcessorKeyBuilder* b) {
233 const ShadowFP& shadowFP = proc.cast<ShadowFP>();
234 b->add32(shadowFP.fNumDirLights);
235 }
236
237 protected:
238 void onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) override {
239 const ShadowFP &shadowFP = proc.cast<ShadowFP>();
240
241 fNumDirLights = shadowFP.numLights();
242
243 for (int i = 0; i < fNumDirLights; i++) {
244 const SkVector3 &lightDir = shadowFP.lightDir(i);
245 if (lightDir != fLightDir[i]) {
246 pdman.set3fv(fLightDirUni[i], 1, &lightDir.fX);
247 fLightDir[i] = lightDir;
248 }
249 const SkColor3f &lightColor = shadowFP.lightColor(i);
250 if (lightColor != fLightColor[i]) {
251 pdman.set3fv(fLightColorUni[i], 1, &lightColor.fX);
252 fLightColor[i] = lightColor;
253 }
254 }
255
256 const SkColor3f& ambientColor = shadowFP.ambientColor();
257 if (ambientColor != fAmbientColor) {
258 pdman.set3fv(fAmbientColorUni, 1, &ambientColor.fX);
259 fAmbientColor = ambientColor;
260 }
261 }
262
263 private:
264 SkVector3 fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
265 GrGLSLProgramDataManager::UniformHandle fLightDirUni[SK_MAX_NON_AMBIENT_ LIGHTS];
266 SkColor3f fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
267 GrGLSLProgramDataManager::UniformHandle fLightColorUni[SK_MAX_NON_AMBIEN T_LIGHTS];
268
269 SkColor3f fAmbientColor;
270 GrGLSLProgramDataManager::UniformHandle fAmbientColorUni;
271
272 int fNumDirLights;
273 };
274
275 void onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override {
276 GLSLShadowFP::GenKey(*this, caps, b);
277 }
278
279 const char* name() const override { return "shadowFP"; }
280
281 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
282 inout->mulByUnknownFourComponents();
283 }
284 int32_t numLights() const { return fNumDirLights; }
285 const SkColor3f& ambientColor() const { return fAmbientColor; }
286 const SkVector3& lightDir(int i) const {
287 SkASSERT(i < fNumDirLights);
288 return fLightDir[i];
289 }
290 const SkVector3& lightColor(int i) const {
291 SkASSERT(i < fNumDirLights);
292 return fLightColor[i];
293 }
294
295 private:
296 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLSLShadowFP; }
297
298 bool onIsEqual(const GrFragmentProcessor& proc) const override {
299 const ShadowFP& shadowFP = proc.cast<ShadowFP>();
robertphillips 2016/07/28 19:47:25 Can this entire if test fit on 1 line ?
vjiaoblack 2016/07/29 16:07:30 Done. The next can't tho.
300 if (fAmbientColor != shadowFP.fAmbientColor ||
301 fNumDirLights != shadowFP.fNumDirLights) {
302 return false;
303 }
304
305 for (int i = 0; i < fNumDirLights; i++) {
306 if (fLightDir[i] != shadowFP.fLightDir[i] ||
307 fLightColor[i] == shadowFP.fLightColor[i]) {
308 return false;
309 }
310 }
311
312 return true;
313 }
314
315 int fNumDirLights;
316
317 SkVector3 fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
318 SkColor3f fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
319 GrTextureAccess fDepthMapAccess[SK_MAX_NON_AMBIENT_LIGHTS];
320 sk_sp<GrTexture> fTexture[SK_MAX_NON_AMBIENT_LIGHTS];
321
322 SkColor3f fAmbientColor;
323 };
324
325 ////////////////////////////////////////////////////////////////////////////
326
327 sk_sp<GrFragmentProcessor> SkShadowShaderImpl::asFragmentProcessor(const AsFPArg s& fpargs) const {
328
329 sk_sp<GrFragmentProcessor> povDepthFP = povDepthShader->asFragmentProcessor( fpargs);
330
331 sk_sp<GrFragmentProcessor> diffuseFP = diffuseShader->asFragmentProcessor(fp args);
332
333 sk_sp<GrFragmentProcessor> shadowfp = sk_make_sp<ShadowFP>(std::move(povDept hFP),
334 std::move(diffuse FP),
335 std::move(fLights ),
336 fpargs.fContext);
337 return shadowfp;
338 }
339
340
341 #endif
342
343 ////////////////////////////////////////////////////////////////////////////
344
345 bool SkShadowShaderImpl::isOpaque() const {
robertphillips 2016/07/28 19:47:25 Does the povDepthShader's opacity actually matter?
vjiaoblack 2016/07/29 16:07:30 Done.
346 return povDepthShader->isOpaque() || diffuseShader->isOpaque();
347 }
348
349 SkShadowShaderImpl::ShadowShaderContext::ShadowShaderContext(
350 const SkShadowShaderImpl& shader, const ContextRec& rec,
351 SkShader::Context* povDepthContext,
352 SkShader::Context* diffuseContext,
353 void* heapAllocated)
354 : INHERITED(shader, rec)
355 , fPovDepthContext(povDepthContext)
356 , fDiffuseContext(diffuseContext)
357 , fHeapAllocated(heapAllocated) {
358 bool isOpaque = shader.isOpaque();
359
360 // update fFlags
361 uint32_t flags = 0;
362 if (isOpaque && (255 == this->getPaintAlpha())) {
363 flags |= kOpaqueAlpha_Flag;
364 }
365
366 fFlags = flags;
367 }
368
369 SkShadowShaderImpl::ShadowShaderContext::~ShadowShaderContext() {
370 // The dependencies have been created outside of the context on memory that was allocated by
371 // the onCreateContext() method. Call the destructors and free the memory.
372 fPovDepthContext->~Context();
373 fDiffuseContext->~Context();
374
375 sk_free(fHeapAllocated);
376 }
377
378 static inline SkPMColor convert(SkColor3f color, U8CPU a) {
379 if (color.fX <= 0.0f) {
380 color.fX = 0.0f;
381 } else if (color.fX >= 255.0f) {
382 color.fX = 255.0f;
383 }
384
385 if (color.fY <= 0.0f) {
386 color.fY = 0.0f;
387 } else if (color.fY >= 255.0f) {
388 color.fY = 255.0f;
389 }
390
391 if (color.fZ <= 0.0f) {
392 color.fZ = 0.0f;
393 } else if (color.fZ >= 255.0f) {
394 color.fZ = 255.0f;
395 }
396
397 return SkPreMultiplyARGB(a, (int) color.fX, (int) color.fY, (int) color.fZ) ;
398 }
399
400 // larger is better (fewer times we have to loop), but we shouldn't
401 // take up too much stack-space (each one here costs 16 bytes)
402 #define BUFFER_MAX 16
403 void SkShadowShaderImpl::ShadowShaderContext::shadeSpan(int x, int y,
404 SkPMColor result[], int count) {
405 const SkShadowShaderImpl& lightShader = static_cast<const SkShadowShaderImpl &>(fShader);
406
407 SkPMColor diffuse[BUFFER_MAX];
408
409 do {
410 int n = SkTMin(count, BUFFER_MAX);
411
412 fPovDepthContext->shadeSpan(x, y, diffuse, n);
413 fDiffuseContext->shadeSpan(x, y, diffuse, n);
414
415 for (int i = 0; i < n; ++i) {
416
417 SkColor diffColor = SkUnPreMultiply::PMColorToColor(diffuse[i]);
418
419 SkColor3f accum = SkColor3f::Make(0.0f, 0.0f, 0.0f);
420 // This is all done in linear unpremul color space (each component 0 ..255.0f though)
421 for (int l = 0; l < lightShader.fLights->numLights(); ++l) {
422 const SkLights::Light& light = lightShader.fLights->light(l);
423
robertphillips 2016/07/28 19:47:25 Is this implementing the same lighting model as th
vjiaoblack 2016/07/29 16:07:30 Fixing.
424 if (SkLights::Light::kAmbient_LightType == light.type()) {
425 accum += light.color().makeScale(255.0f);
426 } else {
427 accum.fX += light.color().fX * SkColorGetR(diffColor);
428 accum.fY += light.color().fY * SkColorGetG(diffColor);
429 accum.fZ += light.color().fZ * SkColorGetB(diffColor);
430 }
431 }
432
433 result[i] = convert(accum, SkColorGetA(diffColor));
434 }
435
436 result += n;
437 x += n;
438 count -= n;
439 } while (count > 0);
440 }
441
442 ////////////////////////////////////////////////////////////////////////////
443
444 #ifndef SK_IGNORE_TO_STRING
445 void SkShadowShaderImpl::toString(SkString* str) const {
446 str->appendf("ShadowShader: ()");
447 }
448 #endif
449
450 sk_sp<SkFlattenable> SkShadowShaderImpl::CreateProc(SkReadBuffer& buf) {
451
452 // Discarding SkShader flattenable params
453 bool hasLocalMatrix = buf.readBool();
454 SkAssertResult(!hasLocalMatrix);
455
456 int numLights = buf.readInt();
457
458 SkLights::Builder builder;
459
460 for (int l = 0; l < numLights; ++l) {
461 bool isAmbient = buf.readBool();
462
463 SkColor3f color;
464 if (!buf.readScalarArray(&color.fX, 3)) {
465 return nullptr;
466 }
467
468 if (isAmbient) {
469 builder.add(SkLights::Light(color));
470 } else {
471 SkVector3 dir;
472 if (!buf.readScalarArray(&dir.fX, 3)) {
473 return nullptr;
474 }
475 builder.add(SkLights::Light(color, dir));
476 }
477 }
478
479 sk_sp<SkLights> lights(builder.finish());
480
481 sk_sp<SkShader> povDepthShader(buf.readFlattenable<SkShader>());
482 sk_sp<SkShader> diffuseShader(buf.readFlattenable<SkShader>());
483
484 return sk_make_sp<SkShadowShaderImpl>(std::move(povDepthShader),
485 std::move(diffuseShader),
486 std::move(lights));
487 }
488
489 void SkShadowShaderImpl::flatten(SkWriteBuffer& buf) const {
490 this->INHERITED::flatten(buf);
491
492 buf.writeInt(fLights->numLights());
493 for (int l = 0; l < fLights->numLights(); ++l) {
494 const SkLights::Light& light = fLights->light(l);
495
496 bool isAmbient = SkLights::Light::kAmbient_LightType == light.type();
497
498 buf.writeBool(isAmbient);
499 buf.writeScalarArray(&light.color().fX, 3);
500 if (!isAmbient) {
501 buf.writeScalarArray(&light.dir().fX, 3);
502 }
503 }
504
505 buf.writeFlattenable(povDepthShader.get());
506 buf.writeFlattenable(diffuseShader.get());
507 }
508
509 size_t SkShadowShaderImpl::onContextSize(const ContextRec& rec) const {
510 return sizeof(ShadowShaderContext);
511 }
512
513 SkShader::Context* SkShadowShaderImpl::onCreateContext(const ContextRec& rec,
514 void* storage) const {
515 size_t heapRequired = povDepthShader->contextSize(rec) +
516 diffuseShader->contextSize(rec);
517
518 void* heapAllocated = sk_malloc_throw(heapRequired);
519
520 void* povDepthContextStorage = heapAllocated;
521
522 SkShader::Context* povDepthContext =
523 povDepthShader->createContext(rec, povDepthContextStorage);
524
525 if (!povDepthContext) {
526 sk_free(heapAllocated);
527 return nullptr;
528 }
529
530 void* diffuseContextStorage = (char*)heapAllocated + povDepthShader->context Size(rec);
531
532 SkShader::Context* diffuseContext = diffuseShader->createContext(rec, diffus eContextStorage);
533 if (!diffuseContext) {
534 sk_free(heapAllocated);
535 return nullptr;
536 }
537
538 return new (storage) ShadowShaderContext(*this, rec, povDepthContext, diffus eContext,
539 heapAllocated);
540 }
541
542 ///////////////////////////////////////////////////////////////////////////////
543
544 sk_sp<SkShader> SkShadowShader::Make(sk_sp<SkShader> povDepthShader,
545 sk_sp<SkShader> diffuseShader,
546 sk_sp<SkLights> lights) {
547 if (!povDepthShader || !diffuseShader) {
548 // TODO: Use paint's color in absence of a diffuseShader
549 // TODO: Use a default implementation of normalSource instead
550 return nullptr;
551 }
552
553 return sk_make_sp<SkShadowShaderImpl>(std::move(povDepthShader),
554 std::move(diffuseShader),
555 std::move(lights));
556 }
557
558 ///////////////////////////////////////////////////////////////////////////////
559
560 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkShadowShader)
561 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkShadowShaderImpl)
562 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
563
564 ///////////////////////////////////////////////////////////////////////////////
OLDNEW
« gm/shadowmaps.cpp ('K') | « src/core/SkShadowShader.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698