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/glsl/GrGLSLShaderBuilder.h"
9
10 #include "include/sksl/DSL.h"
11 #include "src/gpu/GrShaderCaps.h"
12 #include "src/gpu/GrShaderVar.h"
13 #include "src/gpu/GrSwizzle.h"
14 #include "src/gpu/glsl/GrGLSLBlend.h"
15 #include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
16 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
17 #include "src/sksl/SkSLThreadContext.h"
18 #include "src/sksl/ir/SkSLVarDeclarations.h"
19
GrGLSLShaderBuilder(GrGLSLProgramBuilder * program)20 GrGLSLShaderBuilder::GrGLSLShaderBuilder(GrGLSLProgramBuilder* program)
21 : fProgramBuilder(program)
22 , fInputs(GrGLSLProgramBuilder::kVarsPerBlock)
23 , fOutputs(GrGLSLProgramBuilder::kVarsPerBlock)
24 , fFeaturesAddedMask(0)
25 , fCodeIndex(kCode)
26 , fFinalized(false)
27 , fTmpVariableCounter(0) {
28 // We push back some placeholder pointers which will later become our header
29 for (int i = 0; i <= kCode; i++) {
30 fShaderStrings.push_back();
31 }
32
33 this->main() = "void main() {";
34 }
35
declAppend(const GrShaderVar & var)36 void GrGLSLShaderBuilder::declAppend(const GrShaderVar& var) {
37 SkString tempDecl;
38 var.appendDecl(fProgramBuilder->shaderCaps(), &tempDecl);
39 this->codeAppendf("%s;", tempDecl.c_str());
40 }
41
declareGlobal(const GrShaderVar & v)42 void GrGLSLShaderBuilder::declareGlobal(const GrShaderVar& v) {
43 v.appendDecl(this->getProgramBuilder()->shaderCaps(), &this->definitions());
44 this->definitions().append(";");
45 }
46
getMangledFunctionName(const char * baseName)47 SkString GrGLSLShaderBuilder::getMangledFunctionName(const char* baseName) {
48 return fProgramBuilder->nameVariable(/*prefix=*/'\0', baseName);
49 }
50
appendFunctionDecl(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args)51 void GrGLSLShaderBuilder::appendFunctionDecl(GrSLType returnType,
52 const char* mangledName,
53 SkSpan<const GrShaderVar> args) {
54 this->functions().appendf("%s %s(", GrGLSLTypeString(returnType), mangledName);
55 for (size_t i = 0; i < args.size(); ++i) {
56 if (i > 0) {
57 this->functions().append(", ");
58 }
59 args[i].appendDecl(fProgramBuilder->shaderCaps(), &this->functions());
60 }
61
62 this->functions().append(")");
63 }
64
emitFunction(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args,const char * body)65 void GrGLSLShaderBuilder::emitFunction(GrSLType returnType,
66 const char* mangledName,
67 SkSpan<const GrShaderVar> args,
68 const char* body) {
69 this->appendFunctionDecl(returnType, mangledName, args);
70 this->functions().appendf(" {\n"
71 "%s"
72 "}\n\n", body);
73 }
74
emitFunction(const char * declaration,const char * body)75 void GrGLSLShaderBuilder::emitFunction(const char* declaration, const char* body) {
76 this->functions().appendf("%s {\n"
77 "%s"
78 "}\n\n", declaration, body);
79 }
80
emitFunctionPrototype(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args)81 void GrGLSLShaderBuilder::emitFunctionPrototype(GrSLType returnType,
82 const char* mangledName,
83 SkSpan<const GrShaderVar> args) {
84 this->appendFunctionDecl(returnType, mangledName, args);
85 this->functions().append(";\n");
86 }
87
emitFunctionPrototype(const char * declaration)88 void GrGLSLShaderBuilder::emitFunctionPrototype(const char* declaration) {
89 this->functions().appendf("%s;\n", declaration);
90 }
91
codeAppend(std::unique_ptr<SkSL::Statement> stmt)92 void GrGLSLShaderBuilder::codeAppend(std::unique_ptr<SkSL::Statement> stmt) {
93 SkASSERT(SkSL::ThreadContext::CurrentProcessor());
94 SkASSERT(stmt);
95 this->codeAppend(stmt->description().c_str());
96 if (stmt->is<SkSL::VarDeclaration>()) {
97 fDeclarations.push_back(std::move(stmt));
98 }
99 }
100
append_texture_swizzle(SkString * out,GrSwizzle swizzle)101 static inline void append_texture_swizzle(SkString* out, GrSwizzle swizzle) {
102 if (swizzle != GrSwizzle::RGBA()) {
103 out->appendf(".%s", swizzle.asString().c_str());
104 }
105 }
106
appendTextureLookup(SkString * out,SamplerHandle samplerHandle,const char * coordName) const107 void GrGLSLShaderBuilder::appendTextureLookup(SkString* out,
108 SamplerHandle samplerHandle,
109 const char* coordName) const {
110 const char* sampler = fProgramBuilder->samplerVariable(samplerHandle);
111 out->appendf("sample(%s, %s)", sampler, coordName);
112 append_texture_swizzle(out, fProgramBuilder->samplerSwizzle(samplerHandle));
113 }
114
appendTextureLookup(SamplerHandle samplerHandle,const char * coordName,GrGLSLColorSpaceXformHelper * colorXformHelper)115 void GrGLSLShaderBuilder::appendTextureLookup(SamplerHandle samplerHandle,
116 const char* coordName,
117 GrGLSLColorSpaceXformHelper* colorXformHelper) {
118 SkString lookup;
119 this->appendTextureLookup(&lookup, samplerHandle, coordName);
120 this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
121 }
122
appendTextureLookupAndBlend(const char * dst,SkBlendMode mode,SamplerHandle samplerHandle,const char * coordName,GrGLSLColorSpaceXformHelper * colorXformHelper)123 void GrGLSLShaderBuilder::appendTextureLookupAndBlend(
124 const char* dst,
125 SkBlendMode mode,
126 SamplerHandle samplerHandle,
127 const char* coordName,
128 GrGLSLColorSpaceXformHelper* colorXformHelper) {
129 if (!dst) {
130 dst = "half4(1)";
131 }
132 SkString lookup;
133 // This works around an issue in SwiftShader where the texture lookup is messed up
134 // if we use blend_modulate instead of simply operator * on dst and the sampled result.
135 // At this time it's unknown if the same problem exists for other modes.
136 if (mode == SkBlendMode::kModulate) {
137 this->codeAppend("(");
138 this->appendTextureLookup(&lookup, samplerHandle, coordName);
139 this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
140 this->codeAppendf(" * %s)", dst);
141 } else {
142 this->codeAppendf("%s(", GrGLSLBlend::BlendFuncName(mode));
143 this->appendTextureLookup(&lookup, samplerHandle, coordName);
144 this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
145 this->codeAppendf(", %s)", dst);
146 }
147 }
148
appendInputLoad(SamplerHandle samplerHandle)149 void GrGLSLShaderBuilder::appendInputLoad(SamplerHandle samplerHandle) {
150 const char* input = fProgramBuilder->inputSamplerVariable(samplerHandle);
151 SkString load;
152 load.appendf("subpassLoad(%s)", input);
153 append_texture_swizzle(&load, fProgramBuilder->inputSamplerSwizzle(samplerHandle));
154 this->codeAppend(load.c_str());
155 }
156
appendColorGamutXform(SkString * out,const char * srcColor,GrGLSLColorSpaceXformHelper * colorXformHelper)157 void GrGLSLShaderBuilder::appendColorGamutXform(SkString* out,
158 const char* srcColor,
159 GrGLSLColorSpaceXformHelper* colorXformHelper) {
160 if (!colorXformHelper || colorXformHelper->isNoop()) {
161 *out = srcColor;
162 return;
163 }
164
165 GrGLSLUniformHandler* uniformHandler = fProgramBuilder->uniformHandler();
166
167 // We define up to three helper functions, to keep things clearer. One for the source transfer
168 // function, one for the (inverse) destination transfer function, and one for the gamut xform.
169 // Any combination of these may be present, although some configurations are much more likely.
170
171 auto emitTFFunc = [=](const char* name, GrGLSLProgramDataManager::UniformHandle uniform,
172 TFKind kind) {
173 const GrShaderVar gTFArgs[] = { GrShaderVar("x", kHalf_GrSLType) };
174 const char* coeffs = uniformHandler->getUniformCStr(uniform);
175 SkString body;
176 // Temporaries to make evaluation line readable. We always use the sRGBish names, so the
177 // PQ and HLG math is confusing.
178 body.appendf("half G = %s[0];", coeffs);
179 body.appendf("half A = %s[1];", coeffs);
180 body.appendf("half B = %s[2];", coeffs);
181 body.appendf("half C = %s[3];", coeffs);
182 body.appendf("half D = %s[4];", coeffs);
183 body.appendf("half E = %s[5];", coeffs);
184 body.appendf("half F = %s[6];", coeffs);
185 body.append("half s = sign(x);");
186 body.append("x = abs(x);");
187 switch (kind) {
188 case TFKind::sRGBish_TF:
189 body.append("x = (x < D) ? (C * x) + F : pow(A * x + B, G) + E;");
190 break;
191 case TFKind::PQish_TF:
192 body.append("x = pow(max(A + B * pow(x, C), 0) / (D + E * pow(x, C)), F);");
193 break;
194 case TFKind::HLGish_TF:
195 body.append("x = (x*A <= 1) ? pow(x*A, B) : exp((x-E)*C) + D; x *= (F+1);");
196 break;
197 case TFKind::HLGinvish_TF:
198 body.append("x /= (F+1); x = (x <= 1) ? A * pow(x, B) : C * log(x - D) + E;");
199 break;
200 default:
201 SkASSERT(false);
202 break;
203 }
204 body.append("return s * x;");
205 SkString funcName = this->getMangledFunctionName(name);
206 this->emitFunction(kHalf_GrSLType, funcName.c_str(), {gTFArgs, SK_ARRAY_COUNT(gTFArgs)},
207 body.c_str());
208 return funcName;
209 };
210
211 SkString srcTFFuncName;
212 if (colorXformHelper->applySrcTF()) {
213 srcTFFuncName = emitTFFunc("src_tf", colorXformHelper->srcTFUniform(),
214 colorXformHelper->srcTFKind());
215 }
216
217 SkString dstTFFuncName;
218 if (colorXformHelper->applyDstTF()) {
219 dstTFFuncName = emitTFFunc("dst_tf", colorXformHelper->dstTFUniform(),
220 colorXformHelper->dstTFKind());
221 }
222
223 SkString gamutXformFuncName;
224 if (colorXformHelper->applyGamutXform()) {
225 const GrShaderVar gGamutXformArgs[] = { GrShaderVar("color", kHalf4_GrSLType) };
226 const char* xform = uniformHandler->getUniformCStr(colorXformHelper->gamutXformUniform());
227 SkString body;
228 body.appendf("color.rgb = (%s * color.rgb);", xform);
229 body.append("return color;");
230 gamutXformFuncName = this->getMangledFunctionName("gamut_xform");
231 this->emitFunction(kHalf4_GrSLType, gamutXformFuncName.c_str(),
232 {gGamutXformArgs, SK_ARRAY_COUNT(gGamutXformArgs)}, body.c_str());
233 }
234
235 // Now define a wrapper function that applies all the intermediate steps
236 {
237 // Some GPUs require full float to get results that are as accurate as expected/required.
238 // Most GPUs work just fine with half float. Strangely, the GPUs that have this bug
239 // (Mali G series) only require us to promote the type of a few temporaries here --
240 // the helper functions above can always be written to use half.
241 bool useFloat = fProgramBuilder->shaderCaps()->colorSpaceMathNeedsFloat();
242
243 const GrShaderVar gColorXformArgs[] = {
244 GrShaderVar("color", useFloat ? kFloat4_GrSLType : kHalf4_GrSLType)};
245 SkString body;
246 if (colorXformHelper->applyUnpremul()) {
247 body.append("color = unpremul(color);");
248 }
249 if (colorXformHelper->applySrcTF()) {
250 body.appendf("color.r = %s(half(color.r));", srcTFFuncName.c_str());
251 body.appendf("color.g = %s(half(color.g));", srcTFFuncName.c_str());
252 body.appendf("color.b = %s(half(color.b));", srcTFFuncName.c_str());
253 }
254 if (colorXformHelper->applyGamutXform()) {
255 body.appendf("color = %s(half4(color));", gamutXformFuncName.c_str());
256 }
257 if (colorXformHelper->applyDstTF()) {
258 body.appendf("color.r = %s(half(color.r));", dstTFFuncName.c_str());
259 body.appendf("color.g = %s(half(color.g));", dstTFFuncName.c_str());
260 body.appendf("color.b = %s(half(color.b));", dstTFFuncName.c_str());
261 }
262 if (colorXformHelper->applyPremul()) {
263 body.append("color.rgb *= color.a;");
264 }
265 body.append("return half4(color);");
266 SkString colorXformFuncName = this->getMangledFunctionName("color_xform");
267 this->emitFunction(kHalf4_GrSLType, colorXformFuncName.c_str(),
268 {gColorXformArgs, SK_ARRAY_COUNT(gColorXformArgs)}, body.c_str());
269 out->appendf("%s(%s)", colorXformFuncName.c_str(), srcColor);
270 }
271 }
272
appendColorGamutXform(const char * srcColor,GrGLSLColorSpaceXformHelper * colorXformHelper)273 void GrGLSLShaderBuilder::appendColorGamutXform(const char* srcColor,
274 GrGLSLColorSpaceXformHelper* colorXformHelper) {
275 SkString xform;
276 this->appendColorGamutXform(&xform, srcColor, colorXformHelper);
277 this->codeAppend(xform.c_str());
278 }
279
addFeature(uint32_t featureBit,const char * extensionName)280 bool GrGLSLShaderBuilder::addFeature(uint32_t featureBit, const char* extensionName) {
281 if (featureBit & fFeaturesAddedMask) {
282 return false;
283 }
284 this->extensions().appendf("#extension %s: require\n", extensionName);
285 fFeaturesAddedMask |= featureBit;
286 return true;
287 }
288
appendDecls(const VarArray & vars,SkString * out) const289 void GrGLSLShaderBuilder::appendDecls(const VarArray& vars, SkString* out) const {
290 for (const auto& v : vars.items()) {
291 v.appendDecl(fProgramBuilder->shaderCaps(), out);
292 out->append(";\n");
293 }
294 }
295
addLayoutQualifier(const char * param,InterfaceQualifier interface)296 void GrGLSLShaderBuilder::addLayoutQualifier(const char* param, InterfaceQualifier interface) {
297 SkASSERT(fProgramBuilder->shaderCaps()->generation() >= k330_GrGLSLGeneration ||
298 fProgramBuilder->shaderCaps()->mustEnableAdvBlendEqs());
299 fLayoutParams[interface].push_back() = param;
300 }
301
compileAndAppendLayoutQualifiers()302 void GrGLSLShaderBuilder::compileAndAppendLayoutQualifiers() {
303 static const char* interfaceQualifierNames[] = {
304 "in",
305 "out"
306 };
307
308 for (int interface = 0; interface <= kLastInterfaceQualifier; ++interface) {
309 const SkTArray<SkString>& params = fLayoutParams[interface];
310 if (params.empty()) {
311 continue;
312 }
313 this->layoutQualifiers().appendf("layout(%s", params[0].c_str());
314 for (int i = 1; i < params.count(); ++i) {
315 this->layoutQualifiers().appendf(", %s", params[i].c_str());
316 }
317 this->layoutQualifiers().appendf(") %s;\n", interfaceQualifierNames[interface]);
318 }
319
320 static_assert(0 == GrGLSLShaderBuilder::kIn_InterfaceQualifier);
321 static_assert(1 == GrGLSLShaderBuilder::kOut_InterfaceQualifier);
322 static_assert(SK_ARRAY_COUNT(interfaceQualifierNames) == kLastInterfaceQualifier + 1);
323 }
324
finalize(uint32_t visibility)325 void GrGLSLShaderBuilder::finalize(uint32_t visibility) {
326 SkASSERT(!fFinalized);
327 this->compileAndAppendLayoutQualifiers();
328 SkASSERT(visibility);
329 fProgramBuilder->appendUniformDecls((GrShaderFlags) visibility, &this->uniforms());
330 this->appendDecls(fInputs, &this->inputs());
331 this->appendDecls(fOutputs, &this->outputs());
332 this->onFinalize();
333 // append the 'footer' to code
334 this->code().append("}");
335
336 for (int i = 0; i <= fCodeIndex; i++) {
337 fCompilerString.append(fShaderStrings[i].c_str(), fShaderStrings[i].size());
338 }
339
340 fFinalized = true;
341 }
342