blob: 1ef7c43a7186bdad1538dc326d32e071e8b86ba9 [file] [log] [blame]
Ethan Nicholas762466e2017-06-29 10:03:38 -04001/*
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCPPCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCPPUniformCTypes.h"
11#include "src/sksl/SkSLCompiler.h"
12#include "src/sksl/SkSLHCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040013
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040014#include <algorithm>
15
Ethan Nicholas762466e2017-06-29 10:03:38 -040016namespace SkSL {
17
18static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050019 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
20 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040021}
22
23CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
24 ErrorReporter* errors, String name, OutputStream* out)
25: INHERITED(context, program, errors, out)
26, fName(std::move(name))
27, fFullName(String::printf("Gr%s", fName.c_str()))
28, fSectionAndParameterHelper(*program, *errors) {
29 fLineEnding = "\\n";
30}
31
32void CPPCodeGenerator::writef(const char* s, va_list va) {
33 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040034 va_list copy;
35 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040036 char buffer[BUFFER_SIZE];
37 int length = vsnprintf(buffer, BUFFER_SIZE, s, va);
38 if (length < BUFFER_SIZE) {
39 fOut->write(buffer, length);
40 } else {
41 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040042 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040043 fOut->write(heap.get(), length);
44 }
z102.zhangd74f2c82018-08-10 09:08:47 +080045 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040046}
47
48void CPPCodeGenerator::writef(const char* s, ...) {
49 va_list va;
50 va_start(va, s);
51 this->writef(s, va);
52 va_end(va);
53}
54
55void CPPCodeGenerator::writeHeader() {
56}
57
Ethan Nicholasf7b88202017-09-18 14:10:39 -040058bool CPPCodeGenerator::usesPrecisionModifiers() const {
59 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040060}
61
Ethan Nicholasf7b88202017-09-18 14:10:39 -040062String CPPCodeGenerator::getTypeName(const Type& type) {
63 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040064}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040065
Ethan Nicholas762466e2017-06-29 10:03:38 -040066void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
67 Precedence parentPrecedence) {
68 if (b.fOperator == Token::PERCENT) {
69 // need to use "%%" instead of "%" b/c the code will be inside of a printf
70 Precedence precedence = GetBinaryPrecedence(b.fOperator);
71 if (precedence >= parentPrecedence) {
72 this->write("(");
73 }
74 this->writeExpression(*b.fLeft, precedence);
75 this->write(" %% ");
76 this->writeExpression(*b.fRight, precedence);
77 if (precedence >= parentPrecedence) {
78 this->write(")");
79 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050080 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
81 b.fRight->fKind == Expression::kNullLiteral_Kind) {
82 const Variable* var;
83 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
84 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
85 var = &((VariableReference&) *b.fLeft).fVariable;
86 } else {
87 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
88 var = &((VariableReference&) *b.fRight).fVariable;
89 }
90 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
91 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
92 this->write("%s");
93 const char* op;
94 switch (b.fOperator) {
95 case Token::EQEQ:
96 op = "<";
97 break;
98 case Token::NEQ:
99 op = ">=";
100 break;
101 default:
102 SkASSERT(false);
103 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400104 fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500105 ": \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400106 } else {
107 INHERITED::writeBinaryExpression(b, parentPrecedence);
108 }
109}
110
111void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
112 const Expression& base = *i.fBase;
113 if (base.fKind == Expression::kVariableReference_Kind) {
114 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
115 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
116 this->write("%s");
117 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700118 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400119 "index into sk_TransformedCoords2D must be an integer literal");
120 return;
121 }
122 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
123 String name = "sk_TransformedCoords2D_" + to_string(index);
124 fFormatArgs.push_back(name + ".c_str()");
125 if (fWrittenTransformedCoords.find(index) == fWrittenTransformedCoords.end()) {
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400126 addExtraEmitCodeLine("SkString " + name +
127 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
128 to_string(index) + "]);");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400129 fWrittenTransformedCoords.insert(index);
130 }
131 return;
132 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
133 this->write("%s");
134 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700135 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400136 "index into sk_TextureSamplers must be an integer literal");
137 return;
138 }
139 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
140 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
141 "args.fTexSamplers[" + to_string(index) + "]).c_str()");
142 return;
143 }
144 }
145 INHERITED::writeIndexExpression(i);
146}
147
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400148static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500149 if (type.fName == "bool") {
150 return "false";
151 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400152 switch (type.kind()) {
153 case Type::kScalar_Kind: return "0";
154 case Type::kVector_Kind: return type.name() + "(0)";
155 case Type::kMatrix_Kind: return type.name() + "(1)";
156 default: ABORT("unsupported default_value type\n");
157 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400158}
159
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500160static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400161 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400162 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500163 }
164 return default_value(var.fType);
165}
166
Ethan Nicholas762466e2017-06-29 10:03:38 -0400167static bool is_private(const Variable& var) {
168 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
169 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
170 var.fStorage == Variable::kGlobal_Storage &&
171 var.fModifiers.fLayout.fBuiltin == -1;
172}
173
Michael Ludwiga4275592018-08-31 10:52:47 -0400174static bool is_uniform_in(const Variable& var) {
175 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
176 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
177 var.fType.kind() != Type::kSampler_Kind;
178}
179
Ethan Nicholasd608c092017-10-26 09:30:08 -0400180void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
181 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400182 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400183 this->write("%f");
184 fFormatArgs.push_back(cppCode);
185 } else if (type == *fContext.fInt_Type) {
186 this->write("%d");
187 fFormatArgs.push_back(cppCode);
188 } else if (type == *fContext.fBool_Type) {
189 this->write("%s");
190 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400191 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
192 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400193 fFormatArgs.push_back(cppCode + ".fX");
194 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400195 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
196 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400197 switch (layout.fCType) {
198 case Layout::CType::kSkPMColor:
199 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
200 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
201 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
202 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
203 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400204 case Layout::CType::kSkPMColor4f:
205 fFormatArgs.push_back(cppCode + ".fR");
206 fFormatArgs.push_back(cppCode + ".fG");
207 fFormatArgs.push_back(cppCode + ".fB");
208 fFormatArgs.push_back(cppCode + ".fA");
209 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400210 case Layout::CType::kSkRect: // fall through
211 case Layout::CType::kDefault:
212 fFormatArgs.push_back(cppCode + ".left()");
213 fFormatArgs.push_back(cppCode + ".top()");
214 fFormatArgs.push_back(cppCode + ".right()");
215 fFormatArgs.push_back(cppCode + ".bottom()");
216 break;
217 default:
218 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400219 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500220 } else if (type.kind() == Type::kEnum_Kind) {
221 this->write("%d");
222 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400223 } else if (type == *fContext.fInt4_Type ||
224 type == *fContext.fShort4_Type ||
225 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500226 this->write(type.name() + "(%d, %d, %d, %d)");
227 fFormatArgs.push_back(cppCode + ".left()");
228 fFormatArgs.push_back(cppCode + ".top()");
229 fFormatArgs.push_back(cppCode + ".right()");
230 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400231 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400232 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400233 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400234 }
235}
236
237void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
238 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400239 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400240 } else {
241 this->writeExpression(value, kTopLevel_Precedence);
242 }
243}
244
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400245String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
246 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400247 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400248 if (&var == param) {
249 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
250 }
251 if (param->fType.kind() == Type::kSampler_Kind) {
252 ++samplerCount;
253 }
254 }
255 ABORT("should have found sampler in parameters\n");
256}
257
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400258void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
259 this->write(to_string((int32_t) i.fValue));
260}
261
Ethan Nicholas82399462017-10-16 12:35:44 -0400262void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
263 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400264 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400265 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
266 switch (swizzle.fComponents[0]) {
267 case 0: this->write(".left()"); break;
268 case 1: this->write(".top()"); break;
269 case 2: this->write(".right()"); break;
270 case 3: this->write(".bottom()"); break;
271 }
272 } else {
273 INHERITED::writeSwizzle(swizzle);
274 }
275}
276
Ethan Nicholas762466e2017-06-29 10:03:38 -0400277void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400278 if (fCPPMode) {
279 this->write(ref.fVariable.fName);
280 return;
281 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400282 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
283 case SK_INCOLOR_BUILTIN:
284 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400285 // EmitArgs.fInputColor is automatically set to half4(1) if
286 // no input was specified
287 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400288 break;
289 case SK_OUTCOLOR_BUILTIN:
290 this->write("%s");
291 fFormatArgs.push_back(String("args.fOutputColor"));
292 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400293 case SK_WIDTH_BUILTIN:
294 this->write("sk_Width");
295 break;
296 case SK_HEIGHT_BUILTIN:
297 this->write("sk_Height");
298 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400299 default:
300 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400301 this->write("%s");
302 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
303 this->getSamplerHandle(ref.fVariable) + ").c_str()");
304 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400305 }
306 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
307 this->write("%s");
308 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400309 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
310 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400311 String code;
312 if (ref.fVariable.fModifiers.fLayout.fWhen.size()) {
313 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
314 HCodeGenerator::FieldName(name.c_str()).c_str(),
315 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400316 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400317 } else {
318 code = var;
319 }
320 fFormatArgs.push_back(code);
321 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700322 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400323 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400324 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700326 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400327 }
328 }
329}
330
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400331void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
332 if (s.fIsStatic) {
333 this->write("@");
334 }
335 INHERITED::writeIfStatement(s);
336}
337
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400338void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
339 if (fInMain) {
340 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
341 }
342 INHERITED::writeReturnStatement(s);
343}
344
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400345void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
346 if (s.fIsStatic) {
347 this->write("@");
348 }
349 INHERITED::writeSwitchStatement(s);
350}
351
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400352void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
353 if (access.fBase->fType.name() == "fragmentProcessor") {
354 // Special field access on fragment processors are converted into function calls on
355 // GrFragmentProcessor's getters.
356 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
357 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
358 return;
359 }
360
361 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500362 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400363 String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500364 String(var.fName).c_str(),
365 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400366
367 if (fCPPMode) {
368 this->write(cppAccess.c_str());
369 } else {
370 writeRuntimeValue(*field.fType, Layout(), cppAccess);
371 }
372 return;
373 }
374 INHERITED::writeFieldAccess(access);
375}
376
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500377int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400378 int index = 0;
379 bool found = false;
380 for (const auto& p : fProgram) {
381 if (ProgramElement::kVar_Kind == p.fKind) {
382 const VarDeclarations& decls = (const VarDeclarations&) p;
383 for (const auto& raw : decls.fVars) {
384 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500385 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500387 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400388 ++index;
389 }
390 }
391 }
392 if (found) {
393 break;
394 }
395 }
396 SkASSERT(found);
397 return index;
398}
399
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400400void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400401 if (c.fFunction.fBuiltin && c.fFunction.fName == "process") {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400402 // Sanity checks that are detected by function definition in sksl_fp.inc
403 SkASSERT(c.fArguments.size() == 1 || c.fArguments.size() == 2);
Florin Malita390f9bd2019-03-04 12:25:57 -0500404 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
405 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400406
407 // Actually fail during compilation if arguments with valid types are
408 // provided that are not variable references, since process() is a
409 // special function that impacts code emission.
410 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
411 fErrors.error(c.fArguments[0]->fOffset,
412 "process()'s fragmentProcessor argument must be a variable reference\n");
413 return;
414 }
415 if (c.fArguments.size() > 1) {
416 // Second argument must also be a half4 expression
417 SkASSERT("half4" == c.fArguments[1]->fType.name());
418 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500419 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
420 int index = getChildFPIndex(child);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400421
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400422 // Start a new extra emit code section so that the emitted child processor can depend on
423 // sksl variables defined in earlier sksl code.
424 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400425
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400426 // Set to the empty string when no input color parameter should be emitted, which means this
427 // must be properly formatted with a prefixed comma when the parameter should be inserted
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000428 // into the emitChild() parameter list.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400429 String inputArg;
430 if (c.fArguments.size() > 1) {
431 SkASSERT(c.fArguments.size() == 2);
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000432 // Use the emitChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400433 // argument's expression into C++ code that produces sksl stored in an SkString.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400434 String inputName = "_input" + to_string(index);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400435 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400436
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000437 // emitChild() needs a char*
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400438 inputArg = ", " + inputName + ".c_str()";
439 }
440
441 // Write the output handling after the possible input handling
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000442 String childName = "_child" + to_string(index);
443 addExtraEmitCodeLine("SkString " + childName + "(\"" + childName + "\");");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500444 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400445 addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500446 }
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000447 addExtraEmitCodeLine("this->emitChild(_outer." + String(child.fName) + "_index" +
448 inputArg + ", &" + childName + ", args);");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500449 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000450 // Null FPs are not emitted, but their output can still be referenced in dependent
451 // expressions - thus we always declare the variable.
452 // Note: this is essentially dead code required to satisfy the compiler, because
453 // 'process' function calls should always be guarded at a higher level, in the .fp
454 // source.
455 addExtraEmitCodeLine(
456 "} else {"
457 " fragBuilder->codeAppendf(\"half4 %s;\", " + childName + ".c_str());"
458 "}");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500459 }
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000460 this->write("%s");
461 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400462 return;
463 }
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400464 INHERITED::writeFunctionCall(c);
465 if (c.fFunction.fBuiltin && c.fFunction.fName == "texture") {
466 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400467 SkASSERT(c.fArguments.size() >= 1);
468 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400469 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
470 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
471 ").c_str()");
472 }
473}
474
Ethan Nicholas762466e2017-06-29 10:03:38 -0400475void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
476 if (f.fDeclaration.fName == "main") {
477 fFunctionHeader = "";
478 OutputStream* oldOut = fOut;
479 StringStream buffer;
480 fOut = &buffer;
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400481 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400482 for (const auto& s : ((Block&) *f.fBody).fStatements) {
483 this->writeStatement(*s);
484 this->writeLine();
485 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400486 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400487
488 fOut = oldOut;
489 this->write(fFunctionHeader);
490 this->write(buffer.str());
491 } else {
492 INHERITED::writeFunction(f);
493 }
494}
495
496void CPPCodeGenerator::writeSetting(const Setting& s) {
497 static constexpr const char* kPrefix = "sk_Args.";
498 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
499 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400500 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400501 } else {
502 this->write(s.fName.c_str());
503 }
504}
505
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400506bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400507 const Section* s = fSectionAndParameterHelper.getSection(name);
508 if (s) {
509 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400510 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400511 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400512 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400513}
514
515void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
516 if (p.fKind == ProgramElement::kSection_Kind) {
517 return;
518 }
519 if (p.fKind == ProgramElement::kVar_Kind) {
520 const VarDeclarations& decls = (const VarDeclarations&) p;
521 if (!decls.fVars.size()) {
522 return;
523 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000524 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400525 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
526 -1 != var.fModifiers.fLayout.fBuiltin) {
527 return;
528 }
529 }
530 INHERITED::writeProgramElement(p);
531}
532
533void CPPCodeGenerator::addUniform(const Variable& var) {
534 if (!needs_uniform_var(var)) {
535 return;
536 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400537 const char* type;
538 if (var.fType == *fContext.fFloat_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400539 type = "kFloat_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400540 } else if (var.fType == *fContext.fHalf_Type) {
541 type = "kHalf_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400542 } else if (var.fType == *fContext.fFloat2_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400543 type = "kFloat2_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400544 } else if (var.fType == *fContext.fHalf2_Type) {
545 type = "kHalf2_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400546 } else if (var.fType == *fContext.fFloat4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400547 type = "kFloat4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400548 } else if (var.fType == *fContext.fHalf4_Type) {
549 type = "kHalf4_GrSLType";
Brian Osman1cb41712017-10-19 12:54:52 -0400550 } else if (var.fType == *fContext.fFloat4x4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400551 type = "kFloat4x4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400552 } else if (var.fType == *fContext.fHalf4x4_Type) {
553 type = "kHalf4x4_GrSLType";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400554 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700555 ABORT("unsupported uniform type: %s %s;\n", String(var.fType.fName).c_str(),
556 String(var.fName).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400557 }
558 if (var.fModifiers.fLayout.fWhen.size()) {
559 this->writef(" if (%s) {\n ", var.fModifiers.fLayout.fWhen.c_str());
560 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700561 String name(var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400562 this->writef(" %sVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, %s, "
Ethan Nicholas858fecc2019-03-07 13:19:18 -0500563 "\"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700564 name.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400565 if (var.fModifiers.fLayout.fWhen.size()) {
566 this->write(" }\n");
567 }
568}
569
Ethan Nicholascd700e92018-08-24 16:43:57 -0400570void CPPCodeGenerator::writeInputVars() {
571}
572
Ethan Nicholas762466e2017-06-29 10:03:38 -0400573void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400574 for (const auto& p : fProgram) {
575 if (ProgramElement::kVar_Kind == p.fKind) {
576 const VarDeclarations& decls = (const VarDeclarations&) p;
577 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000578 VarDeclaration& decl = (VarDeclaration&) *raw;
579 if (is_private(*decl.fVar)) {
580 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
581 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400582 "fragmentProcessor variables must be declared 'in'");
583 return;
584 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500585 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000586 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
587 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500588 String(decl.fVar->fName).c_str(),
589 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400590 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
591 // An auto-tracked uniform in variable, so add a field to hold onto the prior
592 // state. Note that tracked variables must be uniform in's and that is validated
593 // before writePrivateVars() is called.
594 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
595 SkASSERT(mapper && mapper->supportsTracking());
596
597 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
598 // The member statement is different if the mapper reports a default value
599 if (mapper->defaultValue().size() > 0) {
600 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400601 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400602 mapper->defaultValue().c_str());
603 } else {
604 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400605 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400606 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400607 }
608 }
609 }
610 }
611}
612
613void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400614 for (const auto& p : fProgram) {
615 if (ProgramElement::kVar_Kind == p.fKind) {
616 const VarDeclarations& decls = (const VarDeclarations&) p;
617 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000618 VarDeclaration& decl = (VarDeclaration&) *raw;
619 if (is_private(*decl.fVar) && decl.fValue) {
620 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400621 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000622 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400623 fCPPMode = false;
624 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400625 }
626 }
627 }
628 }
629}
630
Ethan Nicholas82399462017-10-16 12:35:44 -0400631static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500632 const Type& type = var.fType.nonnullable();
633 return Type::kSampler_Kind != type.kind() &&
634 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400635}
636
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400637void CPPCodeGenerator::newExtraEmitCodeBlock() {
638 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
639 // cpp buffer is not null, and the cpp buffer is not the current output.
640 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
641
642 // Start a new block as an empty string
643 fExtraEmitCodeBlocks.push_back("");
644 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
645 // valid sksl and makes detection trivial.
646 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
647}
648
649void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
650 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
651 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
652 // Automatically add indentation and newline
653 currentBlock += " " + toAppend + "\n";
654}
655
656void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400657 if (fCPPBuffer == nullptr) {
658 // Not actually within writeEmitCode() so nothing to flush
659 return;
660 }
661
662 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
663
664 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400665 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400666 skslBuffer->reset();
667
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400668 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000669 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400670
671 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
672 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
673 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
674 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
675 // statement left off (minus the encountered token).
676 size_t i = 0;
677 int flushPoint = -1;
678 int tokenStart = -1;
679 while (i < sksl.size()) {
680 if (tokenStart >= 0) {
681 // Looking for the end of the token
682 if (sksl[i] == '}') {
683 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
684 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
685 String toFlush = String(sksl.c_str(), flushPoint + 1);
686 // writeCodeAppend automatically removes the format args that it consumed, so
687 // fFormatArgs will be in a valid state for any future sksl
688 this->writeCodeAppend(toFlush);
689
690 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
691 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
692 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
693 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
694 }
695
696 // Now reset the sksl buffer to start after the flush point, but remove the token.
697 String compacted = String(sksl.c_str() + flushPoint + 1,
698 tokenStart - flushPoint - 1);
699 if (i < sksl.size() - 1) {
700 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
701 }
702 sksl = compacted;
703
704 // And reset iteration
705 i = -1;
706 flushPoint = -1;
707 tokenStart = -1;
708 }
709 } else {
710 // Looking for the start of extra emit block tokens, and tracking when statements end
711 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
712 flushPoint = i;
713 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
714 // found an extra emit code block token
715 tokenStart = i++;
716 }
717 }
718 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000719 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400720
721 // Once we've gone through the sksl string to this point, there are no remaining extra emit
722 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400723 this->writeCodeAppend(sksl);
724
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400725 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400726 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400727 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400728}
729
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400730void CPPCodeGenerator::writeCodeAppend(const String& code) {
731 // codeAppendf can only handle appending 1024 bytes at a time, so we need to break the string
732 // into chunks. Unfortunately we can't tell exactly how long the string is going to end up,
733 // because printf escape sequences get replaced by strings of unknown length, but keeping the
734 // format string below 512 bytes is probably safe.
735 static constexpr size_t maxChunkSize = 512;
736 size_t start = 0;
737 size_t index = 0;
738 size_t argStart = 0;
739 size_t argCount;
740 while (index < code.size()) {
741 argCount = 0;
742 this->write(" fragBuilder->codeAppendf(\"");
743 while (index < code.size() && index < start + maxChunkSize) {
744 if ('%' == code[index]) {
745 if (index == start + maxChunkSize - 1 || index == code.size() - 1) {
746 break;
747 }
748 if (code[index + 1] != '%') {
749 ++argCount;
750 }
Ethan Nicholasef0c9fd2017-10-30 10:04:14 -0400751 } else if ('\\' == code[index] && index == start + maxChunkSize - 1) {
752 // avoid splitting an escape sequence that happens to fall across a chunk boundary
753 break;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400754 }
755 ++index;
756 }
757 fOut->write(code.c_str() + start, index - start);
758 this->write("\"");
759 for (size_t i = argStart; i < argStart + argCount; ++i) {
760 this->writef(", %s", fFormatArgs[i].c_str());
761 }
762 this->write(");\n");
763 argStart += argCount;
764 start = index;
765 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400766
767 // argStart is equal to the number of fFormatArgs that were consumed
768 // so they should be removed from the list
769 if (argStart > 0) {
770 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argStart);
771 }
772}
773
774String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
775 const String& cppVar) {
776 // To do this conversion, we temporarily switch the sksl output stream
777 // to an empty stringstream and reset the format args to empty.
778 OutputStream* oldSKSL = fOut;
779 StringStream exprBuffer;
780 fOut = &exprBuffer;
781
782 std::vector<String> oldArgs(fFormatArgs);
783 fFormatArgs.clear();
784
785 // Convert the argument expression into a format string and args
786 this->writeExpression(e, Precedence::kTopLevel_Precedence);
787 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400788 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400789
790 // After generating, restore the original output stream and format args
791 fFormatArgs = oldArgs;
792 fOut = oldSKSL;
793
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400794 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
795 // block tokens won't get handled. So we need to strip them from the expression and stick them
796 // to the end of the original sksl stream.
797 String exprFormat = "";
798 int tokenStart = -1;
799 for (size_t i = 0; i < expr.size(); i++) {
800 if (tokenStart >= 0) {
801 if (expr[i] == '}') {
802 // End of the token, so append the token to fOut
803 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
804 tokenStart = -1;
805 }
806 } else {
807 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
808 tokenStart = i++;
809 } else {
810 exprFormat += expr[i];
811 }
812 }
813 }
814
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400815 // Now build the final C++ code snippet from the format string and args
816 String cppExpr;
817 if (newArgs.size() == 0) {
818 // This was a static expression, so we can simplify the input
819 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400820 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400821 } else {
822 // String formatting must occur dynamically, so have the C++ declaration
823 // use SkStringPrintf with the format args that were accumulated
824 // when the expression was written.
825 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
826 for (size_t i = 0; i < newArgs.size(); i++) {
827 cppExpr += ", " + newArgs[i];
828 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400829 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400830 }
831 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400832}
833
Ethan Nicholas762466e2017-06-29 10:03:38 -0400834bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
835 this->write(" void emitCode(EmitArgs& args) override {\n"
836 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
837 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
838 " (void) _outer;\n",
839 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400840 for (const auto& p : fProgram) {
841 if (ProgramElement::kVar_Kind == p.fKind) {
842 const VarDeclarations& decls = (const VarDeclarations&) p;
843 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000844 VarDeclaration& decl = (VarDeclaration&) *raw;
845 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400846 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000847 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
848 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400849 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400850 " (void) %s;\n",
851 name, name, name);
852 }
853 }
854 }
855 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400856 this->writePrivateVarValues();
857 for (const auto u : uniforms) {
858 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400859 }
860 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400861
862 // Save original buffer as the CPP buffer for flushEmittedCode()
863 fCPPBuffer = fOut;
864 StringStream skslBuffer;
865 fOut = &skslBuffer;
866
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400867 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400868 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400869 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400870
871 // Then restore the original CPP buffer and close the function
872 fOut = fCPPBuffer;
873 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400874 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400875 return result;
876}
877
878void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
879 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400880 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
881 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400882 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
883 "const GrFragmentProcessor& _proc) override {\n",
884 pdman);
885 bool wroteProcessor = false;
886 for (const auto u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400887 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400888 if (!wroteProcessor) {
889 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
890 wroteProcessor = true;
891 this->writef(" {\n");
892 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400893
894 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
895 SkASSERT(mapper);
896
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700897 String nameString(u->fName);
898 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400899
900 // Switches for setData behavior in the generated code
901 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
902 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
903 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
904
905 String uniformName = HCodeGenerator::FieldName(name) + "Var";
906
907 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
908 if (conditionalUniform) {
909 // Add a pre-check to make sure the uniform was emitted
910 // before trying to send any data to the GPU
911 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
912 indent += " ";
913 }
914
915 String valueVar = "";
916 if (needsValueDeclaration) {
917 valueVar.appendf("%sValue", name);
918 // Use AccessType since that will match the return type of _outer's public API.
919 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
920 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400921 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -0400922 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400923 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -0400924 // Not tracked and the mapper only needs to use the value once
925 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400926 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -0400927 }
928
929 if (isTracked) {
930 SkASSERT(mapper->supportsTracking());
931
932 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
933 this->writef("%sif (%s) {\n"
934 "%s %s;\n"
935 "%s %s;\n"
936 "%s}\n", indent.c_str(),
937 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
938 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
939 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
940 } else {
941 this->writef("%s%s;\n", indent.c_str(),
942 mapper->setUniform(pdman, uniformName, valueVar).c_str());
943 }
944
945 if (conditionalUniform) {
946 // Close the earlier precheck block
947 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400948 }
949 }
950 }
951 if (wroteProcessor) {
952 this->writef(" }\n");
953 }
Ethan Nicholas68990be2017-07-13 09:36:52 -0400954 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500955 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400956 for (const auto& p : fProgram) {
957 if (ProgramElement::kVar_Kind == p.fKind) {
958 const VarDeclarations& decls = (const VarDeclarations&) p;
959 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000960 VarDeclaration& decl = (VarDeclaration&) *raw;
961 String nameString(decl.fVar->fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700962 const char* name = nameString.c_str();
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500963 if (decl.fVar->fType.kind() == Type::kSampler_Kind) {
964 this->writef(" GrSurfaceProxy& %sProxy = "
965 "*_outer.textureSampler(%d).proxy();\n",
966 name, samplerIndex);
Brian Salomonfd98c2c2018-07-31 17:25:29 -0400967 this->writef(" GrTexture& %s = *%sProxy.peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500968 name, name);
969 this->writef(" (void) %s;\n", name);
970 ++samplerIndex;
971 } else if (needs_uniform_var(*decl.fVar)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400972 this->writef(" UniformHandle& %s = %sVar;\n"
973 " (void) %s;\n",
974 name, HCodeGenerator::FieldName(name).c_str(), name);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000975 } else if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
976 decl.fVar->fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400977 if (!wroteProcessor) {
978 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
979 fullName);
980 wroteProcessor = true;
981 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400982 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -0400983 " (void) %s;\n",
984 name, name, name);
985 }
986 }
987 }
988 }
989 this->writeSection(SET_DATA_SECTION);
990 }
991 this->write(" }\n");
992}
993
Brian Salomonf7dcd762018-07-30 14:48:15 -0400994void CPPCodeGenerator::writeOnTextureSampler() {
995 bool foundSampler = false;
996 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
997 if (param->fType.kind() == Type::kSampler_Kind) {
998 if (!foundSampler) {
999 this->writef(
1000 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1001 "index) const {\n",
1002 fFullName.c_str());
1003 this->writef(" return IthTextureSampler(index, %s",
1004 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1005 foundSampler = true;
1006 } else {
1007 this->writef(", %s",
1008 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1009 }
1010 }
1011 }
1012 if (foundSampler) {
1013 this->write(");\n}\n");
1014 }
1015}
1016
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001017void CPPCodeGenerator::writeClone() {
1018 if (!this->writeSection(CLONE_SECTION)) {
1019 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001020 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1021 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001022 }
1023 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001024 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1025 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001026 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
1027 for (size_t i = 0; i < transforms.size(); ++i) {
1028 const Section& s = *transforms[i];
1029 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1030 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
1031 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001032 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001033 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001034 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1035 this->writef("\n, %s_index(src.%s_index)",
1036 fieldName.c_str(),
1037 fieldName.c_str());
1038 } else {
1039 this->writef("\n, %s(src.%s)",
1040 fieldName.c_str(),
1041 fieldName.c_str());
1042 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001043 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001044 this->writef(" {\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001045 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001046 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1047 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001048 ++samplerCount;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001049 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1050 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1051 if (param->fType.kind() == Type::kNullable_Kind) {
1052 this->writef(" if (%s_index >= 0) {\n ", fieldName.c_str());
1053 }
1054 this->writef(" this->registerChildProcessor(src.childProcessor(%s_index)."
1055 "clone());\n", fieldName.c_str());
1056 if (param->fType.kind() == Type::kNullable_Kind) {
1057 this->writef(" }\n");
1058 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001059 }
1060 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001061 if (samplerCount) {
1062 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1063 }
Ethan Nicholas929a6812018-08-06 14:56:59 -04001064 for (size_t i = 0; i < transforms.size(); ++i) {
1065 const Section& s = *transforms[i];
1066 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1067 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001068 }
1069 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001070 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1071 fFullName.c_str());
1072 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1073 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001074 this->write("}\n");
1075 }
1076}
1077
Ethan Nicholas762466e2017-06-29 10:03:38 -04001078void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001079 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1080 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001081 this->writef(
1082 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1083 "#if GR_TEST_UTILS\n"
1084 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1085 fFullName.c_str(),
1086 fFullName.c_str(),
1087 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001088 this->writeSection(TEST_CODE_SECTION);
1089 this->write("}\n"
1090 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001091 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001092}
1093
1094void CPPCodeGenerator::writeGetKey() {
1095 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1096 "GrProcessorKeyBuilder* b) const {\n",
1097 fFullName.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001098 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001099 String nameString(param->fName);
1100 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001101 if (param->fModifiers.fLayout.fKey != Layout::kNo_Key &&
1102 (param->fModifiers.fFlags & Modifiers::kUniform_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001103 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -04001104 "layout(key) may not be specified on uniforms");
1105 }
1106 switch (param->fModifiers.fLayout.fKey) {
1107 case Layout::kKey_Key:
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001108 if (param->fModifiers.fLayout.fWhen.size()) {
Brian Salomonc0d79e52019-04-10 15:02:11 -04001109 this->writef("if (%s) {", param->fModifiers.fLayout.fWhen.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001110 }
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001111 if (param->fType == *fContext.fFloat4x4_Type) {
1112 ABORT("no automatic key handling for float4x4\n");
1113 } else if (param->fType == *fContext.fFloat2_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001114 this->writef(" b->add32(%s.fX);\n",
1115 HCodeGenerator::FieldName(name).c_str());
1116 this->writef(" b->add32(%s.fY);\n",
1117 HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001118 } else if (param->fType == *fContext.fFloat4_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001119 this->writef(" b->add32(%s.x());\n",
1120 HCodeGenerator::FieldName(name).c_str());
1121 this->writef(" b->add32(%s.y());\n",
1122 HCodeGenerator::FieldName(name).c_str());
1123 this->writef(" b->add32(%s.width());\n",
1124 HCodeGenerator::FieldName(name).c_str());
1125 this->writef(" b->add32(%s.height());\n",
1126 HCodeGenerator::FieldName(name).c_str());
Brian Salomonc0d79e52019-04-10 15:02:11 -04001127 } else if (param->fType == *fContext.fHalf4_Type) {
1128 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1129 HCodeGenerator::FieldName(name).c_str());
1130 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1131 HCodeGenerator::FieldName(name).c_str());
1132 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1133 HCodeGenerator::FieldName(name).c_str());
1134 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1135 HCodeGenerator::FieldName(name).c_str());
1136 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1137 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001138 } else {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001139 this->writef(" b->add32((int32_t) %s);\n",
Ethan Nicholas762466e2017-06-29 10:03:38 -04001140 HCodeGenerator::FieldName(name).c_str());
1141 }
Brian Salomonc0d79e52019-04-10 15:02:11 -04001142 if (param->fModifiers.fLayout.fWhen.size()) {
1143 this->write("}");
1144 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001145 break;
1146 case Layout::kIdentity_Key:
1147 if (param->fType.kind() != Type::kMatrix_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001148 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -04001149 "layout(key=identity) requires matrix type");
1150 }
1151 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1152 HCodeGenerator::FieldName(name).c_str());
1153 break;
1154 case Layout::kNo_Key:
1155 break;
1156 }
1157 }
1158 this->write("}\n");
1159}
1160
1161bool CPPCodeGenerator::generateCode() {
1162 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001163 for (const auto& p : fProgram) {
1164 if (ProgramElement::kVar_Kind == p.fKind) {
1165 const VarDeclarations& decls = (const VarDeclarations&) p;
1166 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001167 VarDeclaration& decl = (VarDeclaration&) *raw;
1168 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1169 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1170 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001171 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001172
1173 if (is_uniform_in(*decl.fVar)) {
1174 // Validate the "uniform in" declarations to make sure they are fully supported,
1175 // instead of generating surprising C++
1176 const UniformCTypeMapper* mapper =
1177 UniformCTypeMapper::Get(fContext, *decl.fVar);
1178 if (mapper == nullptr) {
1179 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1180 + "'s type is not supported for use as a 'uniform in'");
1181 return false;
1182 }
1183 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1184 if (!mapper->supportsTracking()) {
1185 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1186 + "'s type does not support state tracking");
1187 return false;
1188 }
1189 }
1190
1191 } else {
1192 // If it's not a uniform_in, it's an error to be tracked
1193 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1194 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1195 return false;
1196 }
1197 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001198 }
1199 }
1200 }
1201 const char* baseName = fName.c_str();
1202 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001203 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001204 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001205 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001206 this->writeSection(CPP_SECTION);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001207 this->writef("#include \"include/gpu/GrTexture.h\"\n"
1208 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1209 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1210 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1211 "#include \"src/sksl/SkSLCPP.h\"\n"
1212 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001213 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1214 "public:\n"
1215 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001216 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001217 bool result = this->writeEmitCode(uniforms);
1218 this->write("private:\n");
1219 this->writeSetData(uniforms);
1220 this->writePrivateVars();
1221 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001222 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001223 this->writef(" UniformHandle %sVar;\n",
1224 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001225 }
1226 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001227 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001228 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001229 this->writef(" UniformHandle %sVar;\n",
1230 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001231 }
1232 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001233 this->writef("};\n"
1234 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1235 " return new GrGLSL%s();\n"
1236 "}\n",
1237 fullName, baseName);
1238 this->writeGetKey();
1239 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1240 " const %s& that = other.cast<%s>();\n"
1241 " (void) that;\n",
1242 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001243 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001244 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001245 continue;
1246 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001247 String nameString(param->fName);
1248 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001249 this->writef(" if (%s != that.%s) return false;\n",
1250 HCodeGenerator::FieldName(name).c_str(),
1251 HCodeGenerator::FieldName(name).c_str());
1252 }
1253 this->write(" return true;\n"
1254 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001255 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001256 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001257 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001258 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001259
Ethan Nicholas762466e2017-06-29 10:03:38 -04001260 result &= 0 == fErrors.errorCount();
1261 return result;
1262}
1263
1264} // namespace