• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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 "src/gpu/ganesh/glsl/GrGLSLProgramBuilder.h"
9 
10 #include <memory>
11 
12 #include "src/gpu/ganesh/GrCaps.h"
13 #include "src/gpu/ganesh/GrFragmentProcessor.h"
14 #include "src/gpu/ganesh/GrGeometryProcessor.h"
15 #include "src/gpu/ganesh/GrPipeline.h"
16 #include "src/gpu/ganesh/GrRenderTarget.h"
17 #include "src/gpu/ganesh/GrShaderCaps.h"
18 #include "src/gpu/ganesh/GrTexture.h"
19 #include "src/gpu/ganesh/GrXferProcessor.h"
20 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
21 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
22 #include "src/sksl/SkSLCompiler.h"
23 
24 using namespace skia_private;
25 
26 const int GrGLSLProgramBuilder::kVarsPerBlock = 8;
27 
GrGLSLProgramBuilder(const GrProgramDesc & desc,const GrProgramInfo & programInfo)28 GrGLSLProgramBuilder::GrGLSLProgramBuilder(const GrProgramDesc& desc,
29                                            const GrProgramInfo& programInfo)
30         : fVS(this)
31         , fFS(this)
32         , fDesc(desc)
33         , fProgramInfo(programInfo)
34         , fNumFragmentSamplers(0) {}
35 
36 GrGLSLProgramBuilder::~GrGLSLProgramBuilder() = default;
37 
addFeature(GrShaderFlags shaders,uint32_t featureBit,const char * extensionName)38 void GrGLSLProgramBuilder::addFeature(GrShaderFlags shaders,
39                                       uint32_t featureBit,
40                                       const char* extensionName) {
41     if (shaders & kVertex_GrShaderFlag) {
42         fVS.addFeature(featureBit, extensionName);
43     }
44     if (shaders & kFragment_GrShaderFlag) {
45         fFS.addFeature(featureBit, extensionName);
46     }
47 }
48 
emitAndInstallProcs()49 bool GrGLSLProgramBuilder::emitAndInstallProcs() {
50     // First we loop over all of the installed processors and collect coord transforms.  These will
51     // be sent to the ProgramImpl in its emitCode function
52     SkString inputColor;
53     SkString inputCoverage;
54     if (!this->emitAndInstallPrimProc(&inputColor, &inputCoverage)) {
55         return false;
56     }
57     if (!this->emitAndInstallDstTexture()) {
58         return false;
59     }
60     if (!this->emitAndInstallFragProcs(&inputColor, &inputCoverage)) {
61         return false;
62     }
63     if (!this->emitAndInstallXferProc(inputColor, inputCoverage)) {
64         return false;
65     }
66     fGPImpl->emitTransformCode(&fVS, this->uniformHandler());
67 
68     return this->checkSamplerCounts();
69 }
70 
emitAndInstallPrimProc(SkString * outputColor,SkString * outputCoverage)71 bool GrGLSLProgramBuilder::emitAndInstallPrimProc(SkString* outputColor, SkString* outputCoverage) {
72     const GrGeometryProcessor& geomProc = this->geometryProcessor();
73 
74     // Program builders have a bit of state we need to clear with each effect
75     this->advanceStage();
76     this->nameExpression(outputColor, "outputColor");
77     this->nameExpression(outputCoverage, "outputCoverage");
78 
79     SkASSERT(!fUniformHandles.fRTAdjustmentUni.isValid());
80     fUniformHandles.fRTAdjustmentUni = this->uniformHandler()->addUniform(
81             nullptr, kVertex_GrShaderFlag, SkSLType::kFloat4, SkSL::Compiler::RTADJUST_NAME);
82 
83     fFS.codeAppendf("// Stage %d, %s\n", fStageIndex, geomProc.name());
84     fVS.codeAppendf("// Primitive Processor %s\n", geomProc.name());
85 
86     SkASSERT(!fGPImpl);
87     fGPImpl = geomProc.makeProgramImpl(*this->shaderCaps());
88 
89     AutoSTArray<4, SamplerHandle> texSamplers(geomProc.numTextureSamplers());
90     for (int i = 0; i < geomProc.numTextureSamplers(); ++i) {
91         SkString name;
92         name.printf("TextureSampler_%d", i);
93         const auto& sampler = geomProc.textureSampler(i);
94         texSamplers[i] = this->emitSampler(geomProc.textureSampler(i).backendFormat(),
95                                            sampler.samplerState(),
96                                            sampler.swizzle(),
97                                            name.c_str());
98         if (!texSamplers[i].isValid()) {
99             return false;
100         }
101     }
102 
103     GrGeometryProcessor::ProgramImpl::EmitArgs args(&fVS,
104                                                     &fFS,
105                                                     this->varyingHandler(),
106                                                     this->uniformHandler(),
107                                                     this->shaderCaps(),
108                                                     geomProc,
109                                                     outputColor->c_str(),
110                                                     outputCoverage->c_str(),
111                                                     texSamplers.get());
112     std::tie(fFPCoordsMap, fLocalCoordsVar) = fGPImpl->emitCode(args, this->pipeline());
113 
114     // We have to check that effects and the code they emit are consistent, ie if an effect
115     // asks for dst color, then the emit code needs to follow suit
116     SkDEBUGCODE(verify(geomProc);)
117 
118     return true;
119 }
120 
emitAndInstallFragProcs(SkString * color,SkString * coverage)121 bool GrGLSLProgramBuilder::emitAndInstallFragProcs(SkString* color, SkString* coverage) {
122     int fpCount = this->pipeline().numFragmentProcessors();
123     SkASSERT(fFPImpls.empty());
124     fFPImpls.reserve(fpCount);
125     for (int i = 0; i < fpCount; ++i) {
126         SkString* inOut = this->pipeline().isColorFragmentProcessor(i) ? color : coverage;
127         SkString output;
128         const GrFragmentProcessor& fp = this->pipeline().getFragmentProcessor(i);
129         fFPImpls.push_back(fp.makeProgramImpl());
130         output = this->emitRootFragProc(fp, *fFPImpls.back(), *inOut, output);
131         if (output.isEmpty()) {
132             return false;
133         }
134         *inOut = std::move(output);
135     }
136     return true;
137 }
138 
emitRootFragProc(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl,const SkString & input,SkString output)139 SkString GrGLSLProgramBuilder::emitRootFragProc(const GrFragmentProcessor& fp,
140                                                 GrFragmentProcessor::ProgramImpl& impl,
141                                                 const SkString& input,
142                                                 SkString output) {
143     SkASSERT(input.size());
144 
145     // Program builders have a bit of state we need to clear with each effect
146     this->advanceStage();
147     this->nameExpression(&output, "output");
148     fFS.codeAppendf("half4 %s;", output.c_str());
149     bool ok = true;
150     fp.visitWithImpls([&, samplerIdx = 0](const GrFragmentProcessor& fp,
151                                           GrFragmentProcessor::ProgramImpl& impl) mutable {
152         if (auto* te = fp.asTextureEffect()) {
153             SkString name;
154             name.printf("TextureSampler_%d", samplerIdx++);
155 
156             GrSamplerState samplerState = te->samplerState();
157             const GrBackendFormat& format = te->view().proxy()->backendFormat();
158             skgpu::Swizzle swizzle = te->view().swizzle();
159             SamplerHandle handle = this->emitSampler(format, samplerState, swizzle, name.c_str());
160             if (!handle.isValid()) {
161                 ok = false;
162                 return;
163             }
164             static_cast<GrTextureEffect::Impl&>(impl).setSamplerHandle(handle);
165         }
166     }, impl);
167     if (!ok) {
168         return {};
169     }
170 
171     this->writeFPFunction(fp, impl);
172 
173     if (fp.isBlendFunction()) {
174         if (this->fragmentProcessorHasCoordsParam(&fp)) {
175             fFS.codeAppendf("%s = %s(%s, half4(1), %s);",
176                             output.c_str(),
177                             impl.functionName(),
178                             input.c_str(),
179                             fLocalCoordsVar.c_str());
180         } else {
181             fFS.codeAppendf("%s = %s(%s, half4(1));",
182                             output.c_str(),
183                             impl.functionName(),
184                             input.c_str());
185         }
186     } else {
187         if (this->fragmentProcessorHasCoordsParam(&fp)) {
188             fFS.codeAppendf("%s = %s(%s, %s);",
189                             output.c_str(),
190                             impl.functionName(),
191                             input.c_str(),
192                             fLocalCoordsVar.c_str());
193         } else {
194             fFS.codeAppendf("%s = %s(%s);", output.c_str(), impl.functionName(), input.c_str());
195         }
196     }
197 
198     // We have to check that effects and the code they emit are consistent, ie if an effect asks
199     // for dst color, then the emit code needs to follow suit
200     SkDEBUGCODE(verify(fp);)
201 
202     return output;
203 }
204 
writeChildFPFunctions(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl)205 void GrGLSLProgramBuilder::writeChildFPFunctions(const GrFragmentProcessor& fp,
206                                                  GrFragmentProcessor::ProgramImpl& impl) {
207     fSubstageIndices.push_back(0);
208     for (int i = 0; i < impl.numChildProcessors(); ++i) {
209         GrFragmentProcessor::ProgramImpl* childImpl = impl.childProcessor(i);
210         if (!childImpl) {
211             continue;
212         }
213 
214         const GrFragmentProcessor* childFP = fp.childProcessor(i);
215         SkASSERT(childFP);
216 
217         this->writeFPFunction(*childFP, *childImpl);
218         ++fSubstageIndices.back();
219     }
220     fSubstageIndices.pop_back();
221 }
222 
writeFPFunction(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl)223 void GrGLSLProgramBuilder::writeFPFunction(const GrFragmentProcessor& fp,
224                                            GrFragmentProcessor::ProgramImpl& impl) {
225     constexpr const char*       kDstColor    = "_dst";
226               const char* const inputColor   = fp.isBlendFunction() ? "_src" : "_input";
227               const char*       sampleCoords = "_coords";
228     fFS.nextStage();
229     // Conceptually, an FP is always sampled at a particular coordinate. However, if it is only
230     // sampled by a chain of uniform matrix expressions (or legacy coord transforms), the value that
231     // would have been passed to _coords is lifted to the vertex shader and
232     // varying. In that case it uses that variable and we do not pass a second argument for _coords.
233     GrShaderVar params[3];
234     int numParams = 0;
235 
236     params[numParams++] = GrShaderVar(inputColor, SkSLType::kHalf4);
237 
238     if (fp.isBlendFunction()) {
239         // Blend functions take a dest color as input.
240         params[numParams++] = GrShaderVar(kDstColor, SkSLType::kHalf4);
241     }
242 
243     if (this->fragmentProcessorHasCoordsParam(&fp)) {
244         params[numParams++] = GrShaderVar(sampleCoords, SkSLType::kFloat2);
245     } else {
246         // Either doesn't use coords at all or sampled through a chain of passthrough/matrix
247         // samples usages. In the latter case the coords are emitted in the vertex shader as a
248         // varying, so this only has to access it. Add a float2 _coords variable that maps to the
249         // associated varying and replaces the absent 2nd argument to the fp's function.
250         GrShaderVar varying = fFPCoordsMap[&fp].coordsVarying;
251 
252         switch (varying.getType()) {
253             case SkSLType::kVoid:
254                 SkASSERT(!fp.usesSampleCoordsDirectly());
255                 break;
256             case SkSLType::kFloat2:
257                 // Just point the local coords to the varying
258                 sampleCoords = varying.getName().c_str();
259                 break;
260             case SkSLType::kFloat3:
261                 // Must perform the perspective divide in the frag shader based on the
262                 // varying, and since we won't actually have a function parameter for local
263                 // coords, add it as a local variable.
264                 fFS.codeAppendf("float2 %s = %s.xy / %s.z;\n",
265                                 sampleCoords,
266                                 varying.getName().c_str(),
267                                 varying.getName().c_str());
268                 break;
269             default:
270                 SkDEBUGFAILF("Unexpected varying type for coord: %s %d\n",
271                              varying.getName().c_str(),
272                              (int)varying.getType());
273                 break;
274         }
275     }
276 
277     SkASSERT(numParams <= (int)std::size(params));
278 
279     // First, emit every child's function. This needs to happen (even for children that aren't
280     // sampled), so that all of the expected uniforms are registered.
281     this->writeChildFPFunctions(fp, impl);
282     GrFragmentProcessor::ProgramImpl::EmitArgs args(&fFS,
283                                                     this->uniformHandler(),
284                                                     this->shaderCaps(),
285                                                     fp,
286                                                     inputColor,
287                                                     kDstColor,
288                                                     sampleCoords);
289 
290     impl.emitCode(args);
291     impl.setFunctionName(fFS.getMangledFunctionName(args.fFp.name()));
292 
293     fFS.emitFunction(SkSLType::kHalf4,
294                      impl.functionName(),
295                      SkSpan(params, numParams),
296                      fFS.code().c_str());
297     fFS.deleteStage();
298 }
299 
emitAndInstallDstTexture()300 bool GrGLSLProgramBuilder::emitAndInstallDstTexture() {
301     fDstTextureOrigin = kTopLeft_GrSurfaceOrigin;
302 
303     const GrSurfaceProxyView& dstView = this->pipeline().dstProxyView();
304     if (this->pipeline().usesDstTexture()) {
305         // Set up a sampler handle for the destination texture.
306         GrTextureProxy* dstTextureProxy = dstView.asTextureProxy();
307         SkASSERT(dstTextureProxy);
308         const skgpu::Swizzle& swizzle = dstView.swizzle();
309         fDstTextureSamplerHandle = this->emitSampler(dstTextureProxy->backendFormat(),
310                                                     GrSamplerState(), swizzle, "DstTextureSampler");
311         if (!fDstTextureSamplerHandle.isValid()) {
312             return false;
313         }
314         fDstTextureOrigin = dstView.origin();
315         SkASSERT(dstTextureProxy->textureType() != GrTextureType::kExternal);
316 
317         // Declare a _dstColor global variable which samples from the dest-texture sampler at the
318         // top of the fragment shader.
319         const char* dstTextureCoordsName;
320         fUniformHandles.fDstTextureCoordsUni = this->uniformHandler()->addUniform(
321                 /*owner=*/nullptr,
322                 kFragment_GrShaderFlag,
323                 SkSLType::kHalf4,
324                 "DstTextureCoords",
325                 &dstTextureCoordsName);
326         fFS.codeAppend("// Read color from copy of the destination\n");
327         if (dstTextureProxy->textureType() == GrTextureType::k2D) {
328             fFS.codeAppendf("half2 _dstTexCoord = (half2(sk_FragCoord.xy) - %s.xy) * %s.zw;\n",
329                     dstTextureCoordsName, dstTextureCoordsName);
330             if (fDstTextureOrigin == kBottomLeft_GrSurfaceOrigin) {
331                 fFS.codeAppend("_dstTexCoord.y = 1.0 - _dstTexCoord.y;\n");
332             }
333         } else {
334             SkASSERT(dstTextureProxy->textureType() == GrTextureType::kRectangle);
335             fFS.codeAppendf("half2 _dstTexCoord = (half2(sk_FragCoord.xy) - %s.xy);\n",
336                     dstTextureCoordsName);
337             if (fDstTextureOrigin == kBottomLeft_GrSurfaceOrigin) {
338                 // When the texture type is kRectangle, instead of a scale stored in the zw of the
339                 // uniform, we store the height in z so we can flip the coord here.
340                 fFS.codeAppendf("_dstTexCoord.y = %s.z - _dstTexCoord.y;\n", dstTextureCoordsName);
341             }
342         }
343         const char* dstColor = fFS.dstColor();
344         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
345         fFS.definitionAppend(dstColorDecl.c_str());
346         fFS.codeAppendf("%s = ", dstColor);
347         fFS.appendTextureLookup(fDstTextureSamplerHandle, "_dstTexCoord");
348         fFS.codeAppend(";\n");
349     } else if (this->pipeline().usesDstInputAttachment()) {
350         // Set up an input attachment for the destination texture.
351         const skgpu::Swizzle& swizzle = dstView.swizzle();
352         fDstTextureSamplerHandle = this->emitInputSampler(swizzle, "DstTextureInput");
353         if (!fDstTextureSamplerHandle.isValid()) {
354             return false;
355         }
356 
357         // Populate the _dstColor variable by loading from the input attachment at the top of the
358         // fragment shader.
359         fFS.codeAppend("// Read color from input attachment\n");
360         const char* dstColor = fFS.dstColor();
361         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
362         fFS.definitionAppend(dstColorDecl.c_str());
363         fFS.codeAppendf("%s = ", dstColor);
364         fFS.appendInputLoad(fDstTextureSamplerHandle);
365         fFS.codeAppend(";\n");
366     }
367 
368     return true;
369 }
370 
emitAndInstallXferProc(const SkString & colorIn,const SkString & coverageIn)371 bool GrGLSLProgramBuilder::emitAndInstallXferProc(const SkString& colorIn,
372                                                   const SkString& coverageIn) {
373     // Program builders have a bit of state we need to clear with each effect
374     this->advanceStage();
375 
376     SkASSERT(!fXPImpl);
377     const GrXferProcessor& xp = this->pipeline().getXferProcessor();
378     fXPImpl = xp.makeProgramImpl();
379 
380     // Enable dual source secondary output if we have one
381     if (xp.hasSecondaryOutput()) {
382         fFS.enableSecondaryOutput();
383     }
384 
385     SkString openBrace;
386     openBrace.printf("{ // Xfer Processor: %s\n", xp.name());
387     fFS.codeAppend(openBrace.c_str());
388 
389     SkString finalInColor = colorIn.size() ? colorIn : SkString("float4(1)");
390 
391     GrXferProcessor::ProgramImpl::EmitArgs args(
392             &fFS,
393             this->uniformHandler(),
394             this->shaderCaps(),
395             xp,
396             finalInColor.c_str(),
397             coverageIn.size() ? coverageIn.c_str() : "float4(1)",
398             fFS.getPrimaryColorOutputName(),
399             fFS.getSecondaryColorOutputName(),
400             fDstTextureSamplerHandle,
401             fDstTextureOrigin,
402             this->pipeline().writeSwizzle());
403     fXPImpl->emitCode(args);
404 
405     // We have to check that effects and the code they emit are consistent, ie if an effect
406     // asks for dst color, then the emit code needs to follow suit
407     SkDEBUGCODE(verify(xp);)
408     fFS.codeAppend("}");
409     return true;
410 }
411 
emitSampler(const GrBackendFormat & backendFormat,GrSamplerState state,const skgpu::Swizzle & swizzle,const char * name)412 GrGLSLProgramBuilder::SamplerHandle GrGLSLProgramBuilder::emitSampler(
413         const GrBackendFormat& backendFormat, GrSamplerState state, const skgpu::Swizzle& swizzle,
414         const char* name) {
415     ++fNumFragmentSamplers;
416     return this->uniformHandler()->addSampler(backendFormat, state, swizzle, name,
417                                               this->shaderCaps());
418 }
419 
emitInputSampler(const skgpu::Swizzle & swizzle,const char * name)420 GrGLSLProgramBuilder::SamplerHandle GrGLSLProgramBuilder::emitInputSampler(
421         const skgpu::Swizzle& swizzle, const char* name) {
422     return this->uniformHandler()->addInputSampler(swizzle, name);
423 }
424 
checkSamplerCounts()425 bool GrGLSLProgramBuilder::checkSamplerCounts() {
426     const GrShaderCaps& shaderCaps = *this->shaderCaps();
427     if (fNumFragmentSamplers > shaderCaps.fMaxFragmentSamplers) {
428         GrCapsDebugf(this->caps(), "Program would use too many fragment samplers\n");
429         return false;
430     }
431     return true;
432 }
433 
434 #ifdef SK_DEBUG
verify(const GrGeometryProcessor & geomProc)435 void GrGLSLProgramBuilder::verify(const GrGeometryProcessor& geomProc) {
436     SkASSERT(!fFS.fHasReadDstColorThisStage_DebugOnly);
437 }
438 
verify(const GrFragmentProcessor & fp)439 void GrGLSLProgramBuilder::verify(const GrFragmentProcessor& fp) {
440     SkASSERT(fp.willReadDstColor() == fFS.fHasReadDstColorThisStage_DebugOnly);
441 }
442 
verify(const GrXferProcessor & xp)443 void GrGLSLProgramBuilder::verify(const GrXferProcessor& xp) {
444     SkASSERT(xp.willReadDstColor() == fFS.fHasReadDstColorThisStage_DebugOnly);
445 }
446 #endif
447 
getMangleSuffix() const448 SkString GrGLSLProgramBuilder::getMangleSuffix() const {
449     SkASSERT(fStageIndex >= 0);
450     SkString suffix;
451     suffix.printf("_S%d", fStageIndex);
452     for (auto c : fSubstageIndices) {
453         suffix.appendf("_c%d", c);
454     }
455     return suffix;
456 }
457 
nameVariable(char prefix,const char * name,bool mangle)458 SkString GrGLSLProgramBuilder::nameVariable(char prefix, const char* name, bool mangle) {
459     SkString out;
460     if ('\0' == prefix) {
461         out = name;
462     } else {
463         out.printf("%c%s", prefix, name);
464     }
465     if (mangle) {
466         SkString suffix = this->getMangleSuffix();
467         // Names containing "__" are reserved; add "x" if needed to avoid consecutive underscores.
468         const char *underscoreSplitter = out.endsWith('_') ? "x" : "";
469         out.appendf("%s%s", underscoreSplitter, suffix.c_str());
470     }
471     return out;
472 }
473 
nameExpression(SkString * output,const char * baseName)474 void GrGLSLProgramBuilder::nameExpression(SkString* output, const char* baseName) {
475     // Name a variable to hold stage result. If we already have a valid output name, use that as-is;
476     // otherwise, create a new mangled one.
477     if (output->isEmpty()) {
478         *output = this->nameVariable(/*prefix=*/'\0', baseName);
479     }
480 }
481 
appendUniformDecls(GrShaderFlags visibility,SkString * out) const482 void GrGLSLProgramBuilder::appendUniformDecls(GrShaderFlags visibility, SkString* out) const {
483     this->uniformHandler()->appendUniformDecls(visibility, out);
484 }
485 
addRTFlipUniform(const char * name)486 void GrGLSLProgramBuilder::addRTFlipUniform(const char* name) {
487     SkASSERT(!fUniformHandles.fRTFlipUni.isValid());
488     GrGLSLUniformHandler* uniformHandler = this->uniformHandler();
489     fUniformHandles.fRTFlipUni =
490             uniformHandler->internalAddUniformArray(nullptr,
491                                                     kFragment_GrShaderFlag,
492                                                     SkSLType::kFloat2,
493                                                     name,
494                                                     false,
495                                                     0,
496                                                     nullptr);
497 }
498 
fragmentProcessorHasCoordsParam(const GrFragmentProcessor * fp)499 bool GrGLSLProgramBuilder::fragmentProcessorHasCoordsParam(const GrFragmentProcessor* fp) {
500     return fFPCoordsMap[fp].hasCoordsParam;
501 }
502 
finalizeShaders()503 void GrGLSLProgramBuilder::finalizeShaders() {
504     this->varyingHandler()->finalize();
505     fVS.finalize(kVertex_GrShaderFlag);
506     fFS.finalize(kFragment_GrShaderFlag);
507 }
508