1 /*
2 * Copyright 2014 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/GrRenderTarget.h"
9 #include "src/gpu/GrRenderTargetPriv.h"
10 #include "src/gpu/GrShaderCaps.h"
11 #include "src/gpu/gl/GrGLGpu.h"
12 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
13 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
14 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
15 #include "src/gpu/glsl/GrGLSLVarying.h"
16
17 const char* GrGLSLFragmentShaderBuilder::kDstColorName = "_dstColor";
18
specific_layout_qualifier_name(GrBlendEquation equation)19 static const char* specific_layout_qualifier_name(GrBlendEquation equation) {
20 SkASSERT(GrBlendEquationIsAdvanced(equation));
21
22 static const char* kLayoutQualifierNames[] = {
23 "blend_support_screen",
24 "blend_support_overlay",
25 "blend_support_darken",
26 "blend_support_lighten",
27 "blend_support_colordodge",
28 "blend_support_colorburn",
29 "blend_support_hardlight",
30 "blend_support_softlight",
31 "blend_support_difference",
32 "blend_support_exclusion",
33 "blend_support_multiply",
34 "blend_support_hsl_hue",
35 "blend_support_hsl_saturation",
36 "blend_support_hsl_color",
37 "blend_support_hsl_luminosity"
38 };
39 return kLayoutQualifierNames[equation - kFirstAdvancedGrBlendEquation];
40
41 GR_STATIC_ASSERT(0 == kScreen_GrBlendEquation - kFirstAdvancedGrBlendEquation);
42 GR_STATIC_ASSERT(1 == kOverlay_GrBlendEquation - kFirstAdvancedGrBlendEquation);
43 GR_STATIC_ASSERT(2 == kDarken_GrBlendEquation - kFirstAdvancedGrBlendEquation);
44 GR_STATIC_ASSERT(3 == kLighten_GrBlendEquation - kFirstAdvancedGrBlendEquation);
45 GR_STATIC_ASSERT(4 == kColorDodge_GrBlendEquation - kFirstAdvancedGrBlendEquation);
46 GR_STATIC_ASSERT(5 == kColorBurn_GrBlendEquation - kFirstAdvancedGrBlendEquation);
47 GR_STATIC_ASSERT(6 == kHardLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);
48 GR_STATIC_ASSERT(7 == kSoftLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);
49 GR_STATIC_ASSERT(8 == kDifference_GrBlendEquation - kFirstAdvancedGrBlendEquation);
50 GR_STATIC_ASSERT(9 == kExclusion_GrBlendEquation - kFirstAdvancedGrBlendEquation);
51 GR_STATIC_ASSERT(10 == kMultiply_GrBlendEquation - kFirstAdvancedGrBlendEquation);
52 GR_STATIC_ASSERT(11 == kHSLHue_GrBlendEquation - kFirstAdvancedGrBlendEquation);
53 GR_STATIC_ASSERT(12 == kHSLSaturation_GrBlendEquation - kFirstAdvancedGrBlendEquation);
54 GR_STATIC_ASSERT(13 == kHSLColor_GrBlendEquation - kFirstAdvancedGrBlendEquation);
55 GR_STATIC_ASSERT(14 == kHSLLuminosity_GrBlendEquation - kFirstAdvancedGrBlendEquation);
56 // There's an illegal GrBlendEquation at the end there, hence the -1.
57 GR_STATIC_ASSERT(SK_ARRAY_COUNT(kLayoutQualifierNames) ==
58 kGrBlendEquationCnt - kFirstAdvancedGrBlendEquation - 1);
59 }
60
KeyForSurfaceOrigin(GrSurfaceOrigin origin)61 uint8_t GrGLSLFragmentShaderBuilder::KeyForSurfaceOrigin(GrSurfaceOrigin origin) {
62 SkASSERT(kTopLeft_GrSurfaceOrigin == origin || kBottomLeft_GrSurfaceOrigin == origin);
63 return origin + 1;
64
65 GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);
66 GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);
67 }
68
GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder * program)69 GrGLSLFragmentShaderBuilder::GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder* program)
70 : GrGLSLFragmentBuilder(program) {
71 fSubstageIndices.push_back(0);
72 }
73
ensureCoords2D(const GrShaderVar & coords)74 SkString GrGLSLFragmentShaderBuilder::ensureCoords2D(const GrShaderVar& coords) {
75 if (kFloat3_GrSLType != coords.getType() && kHalf3_GrSLType != coords.getType()) {
76 SkASSERT(kFloat2_GrSLType == coords.getType() || kHalf2_GrSLType == coords.getType());
77 return coords.getName();
78 }
79
80 SkString coords2D;
81 coords2D.printf("%s_ensure2D", coords.c_str());
82 this->codeAppendf("\tfloat2 %s = %s.xy / %s.z;", coords2D.c_str(), coords.c_str(),
83 coords.c_str());
84 return coords2D;
85 }
86
sampleOffsets()87 const char* GrGLSLFragmentShaderBuilder::sampleOffsets() {
88 SkASSERT(CustomFeatures::kSampleLocations & fProgramBuilder->header().processorFeatures());
89 SkDEBUGCODE(fUsedProcessorFeaturesThisStage_DebugOnly |= CustomFeatures::kSampleLocations);
90 SkDEBUGCODE(fUsedProcessorFeaturesAllStages_DebugOnly |= CustomFeatures::kSampleLocations);
91 return "_sampleOffsets";
92 }
93
maskOffMultisampleCoverage(const char * mask,ScopeFlags scopeFlags)94 void GrGLSLFragmentShaderBuilder::maskOffMultisampleCoverage(
95 const char* mask, ScopeFlags scopeFlags) {
96 const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();
97 if (!shaderCaps.sampleVariablesSupport() && !shaderCaps.sampleVariablesStencilSupport()) {
98 SkDEBUGFAIL("Attempted to mask sample coverage without support.");
99 return;
100 }
101 if (const char* extension = shaderCaps.sampleVariablesExtensionString()) {
102 this->addFeature(1 << kSampleVariables_GLSLPrivateFeature, extension);
103 }
104
105 if (!fHasModifiedSampleMask) {
106 fHasModifiedSampleMask = true;
107 if (ScopeFlags::kTopLevel != scopeFlags) {
108 this->codePrependf("gl_SampleMask[0] = ~0;");
109 }
110 if (!(ScopeFlags::kInsideLoop & scopeFlags)) {
111 this->codeAppendf("gl_SampleMask[0] = (%s);", mask);
112 return;
113 }
114 }
115
116 this->codeAppendf("gl_SampleMask[0] &= (%s);", mask);
117 }
118
applyFnToMultisampleMask(const char * fn,const char * grad,ScopeFlags scopeFlags)119 void GrGLSLFragmentShaderBuilder::applyFnToMultisampleMask(
120 const char* fn, const char* grad, ScopeFlags scopeFlags) {
121 SkASSERT(CustomFeatures::kSampleLocations & fProgramBuilder->header().processorFeatures());
122 SkDEBUGCODE(fUsedProcessorFeaturesThisStage_DebugOnly |= CustomFeatures::kSampleLocations);
123 SkDEBUGCODE(fUsedProcessorFeaturesAllStages_DebugOnly |= CustomFeatures::kSampleLocations);
124
125 int sampleCnt = fProgramBuilder->effectiveSampleCnt();
126 SkASSERT(sampleCnt > 1);
127
128 this->codeAppendf("{");
129
130 if (!grad) {
131 SkASSERT(fProgramBuilder->shaderCaps()->shaderDerivativeSupport());
132 // In order to use HW derivatives, our neighbors within the same primitive must also be
133 // executing the same code. A per-pixel branch makes this pre-condition impossible to
134 // fulfill.
135 SkASSERT(!(ScopeFlags::kInsidePerPixelBranch & scopeFlags));
136 this->codeAppendf("float2 grad = float2(dFdx(%s), dFdy(%s));", fn, fn);
137 this->codeAppendf("float fnwidth = fwidth(%s);", fn);
138 grad = "grad";
139 } else {
140 this->codeAppendf("float fnwidth = abs(%s.x) + abs(%s.y);", grad, grad);
141 }
142
143 this->codeAppendf("int mask = 0;");
144 this->codeAppendf("if (%s*2 < fnwidth) {", fn); // Are ANY samples inside the implicit fn?
145 this->codeAppendf( "if (%s*-2 >= fnwidth) {", fn); // Are ALL samples inside the implicit?
146 this->codeAppendf( "mask = ~0;");
147 this->codeAppendf( "} else for (int i = 0; i < %i; ++i) {", sampleCnt);
148 this->codeAppendf( "float fnsample = dot(%s, _sampleOffsets[i]) + %s;", grad, fn);
149 this->codeAppendf( "if (fnsample < 0) {");
150 this->codeAppendf( "mask |= (1 << i);");
151 this->codeAppendf( "}");
152 this->codeAppendf( "}");
153 this->codeAppendf("}");
154 this->maskOffMultisampleCoverage("mask", scopeFlags);
155
156 this->codeAppendf("}");
157 }
158
writeProcessorFunction(GrGLSLFragmentProcessor * fp,GrGLSLFragmentProcessor::EmitArgs & args)159 SkString GrGLSLFPFragmentBuilder::writeProcessorFunction(GrGLSLFragmentProcessor* fp,
160 GrGLSLFragmentProcessor::EmitArgs& args) {
161 this->onBeforeChildProcEmitCode();
162 this->nextStage();
163 this->codeAppendf("half4 %s;\n", args.fOutputColor);
164 fp->emitCode(args);
165 this->codeAppendf("return %s;", args.fOutputColor);
166 GrShaderVar inColor(args.fInputColor, kHalf4_GrSLType);
167 SkString result;
168 this->emitFunction(kHalf4_GrSLType,
169 "stage",
170 1,
171 &inColor,
172 this->code().c_str(),
173 &result);
174 this->deleteStage();
175 this->onAfterChildProcEmitCode();
176 return result;
177 }
178
dstColor()179 const char* GrGLSLFragmentShaderBuilder::dstColor() {
180 SkDEBUGCODE(fHasReadDstColorThisStage_DebugOnly = true;)
181
182 const GrShaderCaps* shaderCaps = fProgramBuilder->shaderCaps();
183 if (shaderCaps->fbFetchSupport()) {
184 this->addFeature(1 << kFramebufferFetch_GLSLPrivateFeature,
185 shaderCaps->fbFetchExtensionString());
186
187 // Some versions of this extension string require declaring custom color output on ES 3.0+
188 const char* fbFetchColorName = "sk_LastFragColor";
189 if (shaderCaps->fbFetchNeedsCustomOutput()) {
190 this->enableCustomOutput();
191 fOutputs[fCustomColorOutputIndex].setTypeModifier(GrShaderVar::kInOut_TypeModifier);
192 fbFetchColorName = DeclaredColorOutputName();
193 // Set the dstColor to an intermediate variable so we don't override it with the output
194 this->codeAppendf("half4 %s = %s;", kDstColorName, fbFetchColorName);
195 } else {
196 return fbFetchColorName;
197 }
198 }
199 return kDstColorName;
200 }
201
enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation)202 void GrGLSLFragmentShaderBuilder::enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation) {
203 SkASSERT(GrBlendEquationIsAdvanced(equation));
204
205 const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();
206 if (!caps.mustEnableAdvBlendEqs()) {
207 return;
208 }
209
210 this->addFeature(1 << kBlendEquationAdvanced_GLSLPrivateFeature,
211 "GL_KHR_blend_equation_advanced");
212 if (caps.mustEnableSpecificAdvBlendEqs()) {
213 this->addLayoutQualifier(specific_layout_qualifier_name(equation), kOut_InterfaceQualifier);
214 } else {
215 this->addLayoutQualifier("blend_support_all_equations", kOut_InterfaceQualifier);
216 }
217 }
218
enableCustomOutput()219 void GrGLSLFragmentShaderBuilder::enableCustomOutput() {
220 if (!fHasCustomColorOutput) {
221 fHasCustomColorOutput = true;
222 fCustomColorOutputIndex = fOutputs.count();
223 fOutputs.push_back().set(kHalf4_GrSLType, DeclaredColorOutputName(),
224 GrShaderVar::kOut_TypeModifier);
225 fProgramBuilder->finalizeFragmentOutputColor(fOutputs.back());
226 }
227 }
228
enableSecondaryOutput()229 void GrGLSLFragmentShaderBuilder::enableSecondaryOutput() {
230 SkASSERT(!fHasSecondaryOutput);
231 fHasSecondaryOutput = true;
232 const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();
233 if (const char* extension = caps.secondaryOutputExtensionString()) {
234 this->addFeature(1 << kBlendFuncExtended_GLSLPrivateFeature, extension);
235 }
236
237 // If the primary output is declared, we must declare also the secondary output
238 // and vice versa, since it is not allowed to use a built-in gl_FragColor and a custom
239 // output. The condition also co-incides with the condition in whici GLES SL 2.0
240 // requires the built-in gl_SecondaryFragColorEXT, where as 3.0 requires a custom output.
241 if (caps.mustDeclareFragmentShaderOutput()) {
242 fOutputs.push_back().set(kHalf4_GrSLType, DeclaredSecondaryColorOutputName(),
243 GrShaderVar::kOut_TypeModifier);
244 fProgramBuilder->finalizeFragmentSecondaryColor(fOutputs.back());
245 }
246 }
247
getPrimaryColorOutputName() const248 const char* GrGLSLFragmentShaderBuilder::getPrimaryColorOutputName() const {
249 return fHasCustomColorOutput ? DeclaredColorOutputName() : "sk_FragColor";
250 }
251
primaryColorOutputIsInOut() const252 bool GrGLSLFragmentShaderBuilder::primaryColorOutputIsInOut() const {
253 return fHasCustomColorOutput &&
254 fOutputs[fCustomColorOutputIndex].getTypeModifier() == GrShaderVar::kInOut_TypeModifier;
255 }
256
declAppendf(const char * fmt,...)257 void GrGLSLFragmentBuilder::declAppendf(const char* fmt, ...) {
258 va_list argp;
259 va_start(argp, fmt);
260 inputs().appendVAList(fmt, argp);
261 va_end(argp);
262 }
263
getSecondaryColorOutputName() const264 const char* GrGLSLFragmentShaderBuilder::getSecondaryColorOutputName() const {
265 if (this->hasSecondaryOutput()) {
266 return (fProgramBuilder->shaderCaps()->mustDeclareFragmentShaderOutput())
267 ? DeclaredSecondaryColorOutputName()
268 : "gl_SecondaryFragColorEXT";
269 }
270 return nullptr;
271 }
272
getSurfaceOrigin() const273 GrSurfaceOrigin GrGLSLFragmentShaderBuilder::getSurfaceOrigin() const {
274 SkASSERT(fProgramBuilder->header().hasSurfaceOriginKey());
275 return static_cast<GrSurfaceOrigin>(fProgramBuilder->header().fSurfaceOriginKey-1);
276
277 GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);
278 GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);
279 }
280
onFinalize()281 void GrGLSLFragmentShaderBuilder::onFinalize() {
282 SkASSERT(fProgramBuilder->header().processorFeatures()
283 == fUsedProcessorFeaturesAllStages_DebugOnly);
284
285 if (CustomFeatures::kSampleLocations & fProgramBuilder->header().processorFeatures()) {
286 const SkTArray<SkPoint>& sampleLocations =
287 fProgramBuilder->renderTarget()->renderTargetPriv().getSampleLocations();
288 this->definitions().append("const float2 _sampleOffsets[] = float2[](");
289 for (int i = 0; i < sampleLocations.count(); ++i) {
290 SkPoint offset = sampleLocations[i] - SkPoint::Make(.5f, .5f);
291 if (kBottomLeft_GrSurfaceOrigin == this->getSurfaceOrigin()) {
292 offset.fY = -offset.fY;
293 }
294 this->definitions().appendf("float2(%f, %f)", offset.x(), offset.y());
295 this->definitions().append((i + 1 != sampleLocations.count()) ? ", " : ");");
296 }
297 }
298
299 fProgramBuilder->varyingHandler()->getFragDecls(&this->inputs(), &this->outputs());
300 }
301
onBeforeChildProcEmitCode()302 void GrGLSLFragmentShaderBuilder::onBeforeChildProcEmitCode() {
303 SkASSERT(fSubstageIndices.count() >= 1);
304 fSubstageIndices.push_back(0);
305 // second-to-last value in the fSubstageIndices stack is the index of the child proc
306 // at that level which is currently emitting code.
307 fMangleString.appendf("_c%d", fSubstageIndices[fSubstageIndices.count() - 2]);
308 }
309
onAfterChildProcEmitCode()310 void GrGLSLFragmentShaderBuilder::onAfterChildProcEmitCode() {
311 SkASSERT(fSubstageIndices.count() >= 2);
312 fSubstageIndices.pop_back();
313 fSubstageIndices.back()++;
314 int removeAt = fMangleString.findLastOf('_');
315 fMangleString.remove(removeAt, fMangleString.size() - removeAt);
316 }
317