• 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/glsl/GrGLSLProgramBuilder.h"
9 
10 #include <memory>
11 
12 #include "src/gpu/GrCaps.h"
13 #include "src/gpu/GrFragmentProcessor.h"
14 #include "src/gpu/GrGeometryProcessor.h"
15 #include "src/gpu/GrPipeline.h"
16 #include "src/gpu/GrRenderTarget.h"
17 #include "src/gpu/GrShaderCaps.h"
18 #include "src/gpu/GrTexture.h"
19 #include "src/gpu/GrXferProcessor.h"
20 #include "src/gpu/effects/GrTextureEffect.h"
21 #include "src/gpu/glsl/GrGLSLVarying.h"
22 #include "src/sksl/SkSLCompiler.h"
23 #include "src/sksl/dsl/priv/DSLFPs.h"
24 
25 const int GrGLSLProgramBuilder::kVarsPerBlock = 8;
26 
GrGLSLProgramBuilder(const GrProgramDesc & desc,const GrProgramInfo & programInfo)27 GrGLSLProgramBuilder::GrGLSLProgramBuilder(const GrProgramDesc& desc,
28                                            const GrProgramInfo& programInfo)
29         : fVS(this)
30         , fFS(this)
31         , fDesc(desc)
32         , fProgramInfo(programInfo)
33         , fNumFragmentSamplers(0) {}
34 
35 GrGLSLProgramBuilder::~GrGLSLProgramBuilder() = default;
36 
addFeature(GrShaderFlags shaders,uint32_t featureBit,const char * extensionName)37 void GrGLSLProgramBuilder::addFeature(GrShaderFlags shaders,
38                                       uint32_t featureBit,
39                                       const char* extensionName) {
40     if (shaders & kVertex_GrShaderFlag) {
41         fVS.addFeature(featureBit, extensionName);
42     }
43     if (shaders & kFragment_GrShaderFlag) {
44         fFS.addFeature(featureBit, extensionName);
45     }
46 }
47 
emitAndInstallProcs()48 bool GrGLSLProgramBuilder::emitAndInstallProcs() {
49     // First we loop over all of the installed processors and collect coord transforms.  These will
50     // be sent to the ProgramImpl in its emitCode function
51     SkSL::dsl::Start(this->shaderCompiler());
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     SkSL::dsl::End();
68 
69     return this->checkSamplerCounts();
70 }
71 
emitAndInstallPrimProc(SkString * outputColor,SkString * outputCoverage)72 bool GrGLSLProgramBuilder::emitAndInstallPrimProc(SkString* outputColor, SkString* outputCoverage) {
73     const GrGeometryProcessor& geomProc = this->geometryProcessor();
74 
75     // Program builders have a bit of state we need to clear with each effect
76     this->advanceStage();
77     this->nameExpression(outputColor, "outputColor");
78     this->nameExpression(outputCoverage, "outputCoverage");
79 
80     SkASSERT(!fUniformHandles.fRTAdjustmentUni.isValid());
81     GrShaderFlags rtAdjustVisibility;
82     if (geomProc.willUseTessellationShaders()) {
83         rtAdjustVisibility = kTessEvaluation_GrShaderFlag;
84     } else {
85         rtAdjustVisibility = kVertex_GrShaderFlag;
86     }
87     fUniformHandles.fRTAdjustmentUni = this->uniformHandler()->addUniform(
88             nullptr, rtAdjustVisibility, SkSLType::kFloat4, SkSL::Compiler::RTADJUST_NAME);
89 
90     fFS.codeAppendf("// Stage %d, %s\n", fStageIndex, geomProc.name());
91     fVS.codeAppendf("// Primitive Processor %s\n", geomProc.name());
92 
93     SkASSERT(!fGPImpl);
94     fGPImpl = geomProc.makeProgramImpl(*this->shaderCaps());
95 
96     SkAutoSTArray<4, SamplerHandle> texSamplers(geomProc.numTextureSamplers());
97     for (int i = 0; i < geomProc.numTextureSamplers(); ++i) {
98         SkString name;
99         name.printf("TextureSampler_%d", i);
100         const auto& sampler = geomProc.textureSampler(i);
101         texSamplers[i] = this->emitSampler(geomProc.textureSampler(i).backendFormat(),
102                                            sampler.samplerState(),
103                                            sampler.swizzle(),
104                                            name.c_str());
105         if (!texSamplers[i].isValid()) {
106             return false;
107         }
108     }
109 
110     GrGeometryProcessor::ProgramImpl::EmitArgs args(&fVS,
111                                                     &fFS,
112                                                     this->varyingHandler(),
113                                                     this->uniformHandler(),
114                                                     this->shaderCaps(),
115                                                     geomProc,
116                                                     outputColor->c_str(),
117                                                     outputCoverage->c_str(),
118                                                     texSamplers.get());
119     std::tie(fFPCoordsMap, fLocalCoordsVar) = fGPImpl->emitCode(args, this->pipeline());
120 
121     // We have to check that effects and the code they emit are consistent, ie if an effect
122     // asks for dst color, then the emit code needs to follow suit
123     SkDEBUGCODE(verify(geomProc);)
124 
125     return true;
126 }
127 
emitAndInstallFragProcs(SkString * color,SkString * coverage)128 bool GrGLSLProgramBuilder::emitAndInstallFragProcs(SkString* color, SkString* coverage) {
129     int fpCount = this->pipeline().numFragmentProcessors();
130     SkASSERT(fFPImpls.empty());
131     fFPImpls.reserve(fpCount);
132     for (int i = 0; i < fpCount; ++i) {
133         SkString* inOut = this->pipeline().isColorFragmentProcessor(i) ? color : coverage;
134         SkString output;
135         const GrFragmentProcessor& fp = this->pipeline().getFragmentProcessor(i);
136         fFPImpls.push_back(fp.makeProgramImpl());
137         output = this->emitRootFragProc(fp, *fFPImpls.back(), *inOut, output);
138         if (output.isEmpty()) {
139             return false;
140         }
141         *inOut = std::move(output);
142     }
143     return true;
144 }
145 
emitRootFragProc(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl,const SkString & input,SkString output)146 SkString GrGLSLProgramBuilder::emitRootFragProc(const GrFragmentProcessor& fp,
147                                                 GrFragmentProcessor::ProgramImpl& impl,
148                                                 const SkString& input,
149                                                 SkString output) {
150     SkASSERT(input.size());
151 
152     // Program builders have a bit of state we need to clear with each effect
153     this->advanceStage();
154     this->nameExpression(&output, "output");
155     fFS.codeAppendf("half4 %s;", output.c_str());
156     bool ok = true;
157     fp.visitWithImpls([&, samplerIdx = 0](const GrFragmentProcessor& fp,
158                                           GrFragmentProcessor::ProgramImpl& impl) mutable {
159         if (auto* te = fp.asTextureEffect()) {
160             SkString name;
161             name.printf("TextureSampler_%d", samplerIdx++);
162 
163             GrSamplerState samplerState = te->samplerState();
164             const GrBackendFormat& format = te->view().proxy()->backendFormat();
165             skgpu::Swizzle swizzle = te->view().swizzle();
166             SamplerHandle handle = this->emitSampler(format, samplerState, swizzle, name.c_str());
167             if (!handle.isValid()) {
168                 ok = false;
169                 return;
170             }
171             static_cast<GrTextureEffect::Impl&>(impl).setSamplerHandle(handle);
172         }
173     }, impl);
174     if (!ok) {
175         return {};
176     }
177 
178     this->writeFPFunction(fp, impl);
179 
180     if (fp.isBlendFunction()) {
181         if (this->fragmentProcessorHasCoordsParam(&fp)) {
182             fFS.codeAppendf("%s = %s(%s, half4(1), %s);",
183                             output.c_str(),
184                             impl.functionName(),
185                             input.c_str(),
186                             fLocalCoordsVar.c_str());
187         } else {
188             fFS.codeAppendf("%s = %s(%s, half4(1));",
189                             output.c_str(),
190                             impl.functionName(),
191                             input.c_str());
192         }
193     } else {
194         if (this->fragmentProcessorHasCoordsParam(&fp)) {
195             fFS.codeAppendf("%s = %s(%s, %s);",
196                             output.c_str(),
197                             impl.functionName(),
198                             input.c_str(),
199                             fLocalCoordsVar.c_str());
200         } else {
201             fFS.codeAppendf("%s = %s(%s);", output.c_str(), impl.functionName(), input.c_str());
202         }
203     }
204 
205     // We have to check that effects and the code they emit are consistent, ie if an effect asks
206     // for dst color, then the emit code needs to follow suit
207     SkDEBUGCODE(verify(fp);)
208 
209     return output;
210 }
211 
writeChildFPFunctions(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl)212 void GrGLSLProgramBuilder::writeChildFPFunctions(const GrFragmentProcessor& fp,
213                                                  GrFragmentProcessor::ProgramImpl& impl) {
214     fSubstageIndices.push_back(0);
215     for (int i = 0; i < impl.numChildProcessors(); ++i) {
216         GrFragmentProcessor::ProgramImpl* childImpl = impl.childProcessor(i);
217         if (!childImpl) {
218             continue;
219         }
220 
221         const GrFragmentProcessor* childFP = fp.childProcessor(i);
222         SkASSERT(childFP);
223 
224         this->writeFPFunction(*childFP, *childImpl);
225         ++fSubstageIndices.back();
226     }
227     fSubstageIndices.pop_back();
228 }
229 
writeFPFunction(const GrFragmentProcessor & fp,GrFragmentProcessor::ProgramImpl & impl)230 void GrGLSLProgramBuilder::writeFPFunction(const GrFragmentProcessor& fp,
231                                            GrFragmentProcessor::ProgramImpl& impl) {
232     constexpr const char*       kDstColor    = "_dst";
233               const char* const inputColor   = fp.isBlendFunction() ? "_src" : "_input";
234               const char*       sampleCoords = "_coords";
235     fFS.nextStage();
236     // Conceptually, an FP is always sampled at a particular coordinate. However, if it is only
237     // sampled by a chain of uniform matrix expressions (or legacy coord transforms), the value that
238     // would have been passed to _coords is lifted to the vertex shader and
239     // varying. In that case it uses that variable and we do not pass a second argument for _coords.
240     GrShaderVar params[3];
241     int numParams = 0;
242 
243     params[numParams++] = GrShaderVar(inputColor, SkSLType::kHalf4);
244 
245     if (fp.isBlendFunction()) {
246         // Blend functions take a dest color as input.
247         params[numParams++] = GrShaderVar(kDstColor, SkSLType::kHalf4);
248     }
249 
250     if (this->fragmentProcessorHasCoordsParam(&fp)) {
251         params[numParams++] = GrShaderVar(sampleCoords, SkSLType::kFloat2);
252     } else {
253         // Either doesn't use coords at all or sampled through a chain of passthrough/matrix
254         // samples usages. In the latter case the coords are emitted in the vertex shader as a
255         // varying, so this only has to access it. Add a float2 _coords variable that maps to the
256         // associated varying and replaces the absent 2nd argument to the fp's function.
257         GrShaderVar varying = fFPCoordsMap[&fp].coordsVarying;
258 
259         switch (varying.getType()) {
260             case SkSLType::kVoid:
261                 SkASSERT(!fp.usesSampleCoordsDirectly());
262                 break;
263             case SkSLType::kFloat2:
264                 // Just point the local coords to the varying
265                 sampleCoords = varying.getName().c_str();
266                 break;
267             case SkSLType::kFloat3:
268                 // Must perform the perspective divide in the frag shader based on the
269                 // varying, and since we won't actually have a function parameter for local
270                 // coords, add it as a local variable.
271                 fFS.codeAppendf("float2 %s = %s.xy / %s.z;\n",
272                                 sampleCoords,
273                                 varying.getName().c_str(),
274                                 varying.getName().c_str());
275                 break;
276             default:
277                 SkDEBUGFAILF("Unexpected varying type for coord: %s %d\n",
278                              varying.getName().c_str(),
279                              (int)varying.getType());
280                 break;
281         }
282     }
283 
284     SkASSERT(numParams <= (int)SK_ARRAY_COUNT(params));
285 
286     // First, emit every child's function. This needs to happen (even for children that aren't
287     // sampled), so that all of the expected uniforms are registered.
288     this->writeChildFPFunctions(fp, impl);
289     GrFragmentProcessor::ProgramImpl::EmitArgs args(&fFS,
290                                                     this->uniformHandler(),
291                                                     this->shaderCaps(),
292                                                     fp,
293                                                     inputColor,
294                                                     kDstColor,
295                                                     sampleCoords);
296 
297     impl.emitCode(args);
298     impl.setFunctionName(fFS.getMangledFunctionName(args.fFp.name()));
299 
300     fFS.emitFunction(SkSLType::kHalf4,
301                      impl.functionName(),
302                      SkMakeSpan(params, numParams),
303                      fFS.code().c_str());
304     fFS.deleteStage();
305 }
306 
emitAndInstallDstTexture()307 bool GrGLSLProgramBuilder::emitAndInstallDstTexture() {
308     fDstTextureOrigin = kTopLeft_GrSurfaceOrigin;
309 
310     const GrSurfaceProxyView& dstView = this->pipeline().dstProxyView();
311     if (this->pipeline().usesDstTexture()) {
312         // Set up a sampler handle for the destination texture.
313         GrTextureProxy* dstTextureProxy = dstView.asTextureProxy();
314         SkASSERT(dstTextureProxy);
315         const skgpu::Swizzle& swizzle = dstView.swizzle();
316         fDstTextureSamplerHandle = this->emitSampler(dstTextureProxy->backendFormat(),
317                                                     GrSamplerState(), swizzle, "DstTextureSampler");
318         if (!fDstTextureSamplerHandle.isValid()) {
319             return false;
320         }
321         fDstTextureOrigin = dstView.origin();
322         SkASSERT(dstTextureProxy->textureType() != GrTextureType::kExternal);
323 
324         // Declare a _dstColor global variable which samples from the dest-texture sampler at the
325         // top of the fragment shader.
326         const char* dstTextureCoordsName;
327         fUniformHandles.fDstTextureCoordsUni = this->uniformHandler()->addUniform(
328                 /*owner=*/nullptr,
329                 kFragment_GrShaderFlag,
330                 SkSLType::kHalf4,
331                 "DstTextureCoords",
332                 &dstTextureCoordsName);
333         fFS.codeAppend("// Read color from copy of the destination\n");
334         fFS.codeAppendf("half2 _dstTexCoord = (half2(sk_FragCoord.xy) - %s.xy) * %s.zw;\n",
335                         dstTextureCoordsName, dstTextureCoordsName);
336         if (fDstTextureOrigin == kBottomLeft_GrSurfaceOrigin) {
337             fFS.codeAppend("_dstTexCoord.y = 1.0 - _dstTexCoord.y;\n");
338         }
339         const char* dstColor = fFS.dstColor();
340         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
341         fFS.definitionAppend(dstColorDecl.c_str());
342         fFS.codeAppendf("%s = ", dstColor);
343         fFS.appendTextureLookup(fDstTextureSamplerHandle, "_dstTexCoord");
344         fFS.codeAppend(";\n");
345     } else if (this->pipeline().usesDstInputAttachment()) {
346         // Set up an input attachment for the destination texture.
347         const skgpu::Swizzle& swizzle = dstView.swizzle();
348         fDstTextureSamplerHandle = this->emitInputSampler(swizzle, "DstTextureInput");
349         if (!fDstTextureSamplerHandle.isValid()) {
350             return false;
351         }
352 
353         // Populate the _dstColor variable by loading from the input attachment at the top of the
354         // fragment shader.
355         fFS.codeAppend("// Read color from input attachment\n");
356         const char* dstColor = fFS.dstColor();
357         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
358         fFS.definitionAppend(dstColorDecl.c_str());
359         fFS.codeAppendf("%s = ", dstColor);
360         fFS.appendInputLoad(fDstTextureSamplerHandle);
361         fFS.codeAppend(";\n");
362     }
363 
364     return true;
365 }
366 
emitAndInstallXferProc(const SkString & colorIn,const SkString & coverageIn)367 bool GrGLSLProgramBuilder::emitAndInstallXferProc(const SkString& colorIn,
368                                                   const SkString& coverageIn) {
369     // Program builders have a bit of state we need to clear with each effect
370     this->advanceStage();
371 
372     SkASSERT(!fXPImpl);
373     const GrXferProcessor& xp = this->pipeline().getXferProcessor();
374     fXPImpl = xp.makeProgramImpl();
375 
376     // Enable dual source secondary output if we have one
377     if (xp.hasSecondaryOutput()) {
378         fFS.enableSecondaryOutput();
379     }
380 
381     if (this->shaderCaps()->mustDeclareFragmentShaderOutput()) {
382         fFS.enableCustomOutput();
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.maxFragmentSamplers()) {
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