blob: 88c7ed3cdfd61d23647fe838a8f73ffef23f7aee [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
8#include "SkSLCPPCodeGenerator.h"
9
10#include "SkSLCompiler.h"
Michael Ludwiga4275592018-08-31 10:52:47 -040011#include "SkSLCPPUniformCTypes.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040012#include "SkSLHCodeGenerator.h"
13
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 }
80 } else {
81 INHERITED::writeBinaryExpression(b, parentPrecedence);
82 }
83}
84
85void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
86 const Expression& base = *i.fBase;
87 if (base.fKind == Expression::kVariableReference_Kind) {
88 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
89 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
90 this->write("%s");
91 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -070092 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -040093 "index into sk_TransformedCoords2D must be an integer literal");
94 return;
95 }
96 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
97 String name = "sk_TransformedCoords2D_" + to_string(index);
98 fFormatArgs.push_back(name + ".c_str()");
99 if (fWrittenTransformedCoords.find(index) == fWrittenTransformedCoords.end()) {
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400100 addExtraEmitCodeLine("SkString " + name +
101 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
102 to_string(index) + "]);");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400103 fWrittenTransformedCoords.insert(index);
104 }
105 return;
106 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
107 this->write("%s");
108 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700109 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400110 "index into sk_TextureSamplers must be an integer literal");
111 return;
112 }
113 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
114 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
115 "args.fTexSamplers[" + to_string(index) + "]).c_str()");
116 return;
117 }
118 }
119 INHERITED::writeIndexExpression(i);
120}
121
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400122static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500123 if (type.fName == "bool") {
124 return "false";
125 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400126 switch (type.kind()) {
127 case Type::kScalar_Kind: return "0";
128 case Type::kVector_Kind: return type.name() + "(0)";
129 case Type::kMatrix_Kind: return type.name() + "(1)";
130 default: ABORT("unsupported default_value type\n");
131 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400132}
133
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500134static String default_value(const Variable& var) {
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400135 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kGrColor4f) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500136 return "GrColor4f::kIllegalConstructor";
137 }
138 return default_value(var.fType);
139}
140
Ethan Nicholas762466e2017-06-29 10:03:38 -0400141static bool is_private(const Variable& var) {
142 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
143 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
144 var.fStorage == Variable::kGlobal_Storage &&
145 var.fModifiers.fLayout.fBuiltin == -1;
146}
147
Michael Ludwiga4275592018-08-31 10:52:47 -0400148static bool is_uniform_in(const Variable& var) {
149 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
150 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
151 var.fType.kind() != Type::kSampler_Kind;
152}
153
Ethan Nicholasd608c092017-10-26 09:30:08 -0400154void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
155 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400156 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400157 this->write("%f");
158 fFormatArgs.push_back(cppCode);
159 } else if (type == *fContext.fInt_Type) {
160 this->write("%d");
161 fFormatArgs.push_back(cppCode);
162 } else if (type == *fContext.fBool_Type) {
163 this->write("%s");
164 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400165 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
166 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400167 fFormatArgs.push_back(cppCode + ".fX");
168 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400169 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
170 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400171 switch (layout.fCType) {
172 case Layout::CType::kSkPMColor:
173 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
174 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
175 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
176 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
177 break;
178 case Layout::CType::kGrColor4f:
179 fFormatArgs.push_back(cppCode + ".fRGBA[0]");
180 fFormatArgs.push_back(cppCode + ".fRGBA[1]");
181 fFormatArgs.push_back(cppCode + ".fRGBA[2]");
182 fFormatArgs.push_back(cppCode + ".fRGBA[3]");
183 break;
184 case Layout::CType::kSkRect: // fall through
185 case Layout::CType::kDefault:
186 fFormatArgs.push_back(cppCode + ".left()");
187 fFormatArgs.push_back(cppCode + ".top()");
188 fFormatArgs.push_back(cppCode + ".right()");
189 fFormatArgs.push_back(cppCode + ".bottom()");
190 break;
191 default:
192 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400193 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500194 } else if (type.kind() == Type::kEnum_Kind) {
195 this->write("%d");
196 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400197 } else if (type == *fContext.fInt4_Type ||
198 type == *fContext.fShort4_Type ||
199 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500200 this->write(type.name() + "(%d, %d, %d, %d)");
201 fFormatArgs.push_back(cppCode + ".left()");
202 fFormatArgs.push_back(cppCode + ".top()");
203 fFormatArgs.push_back(cppCode + ".right()");
204 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400205 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400206 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400207 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400208 }
209}
210
211void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
212 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400213 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400214 } else {
215 this->writeExpression(value, kTopLevel_Precedence);
216 }
217}
218
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400219String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
220 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400221 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400222 if (&var == param) {
223 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
224 }
225 if (param->fType.kind() == Type::kSampler_Kind) {
226 ++samplerCount;
227 }
228 }
229 ABORT("should have found sampler in parameters\n");
230}
231
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400232void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
233 this->write(to_string((int32_t) i.fValue));
234}
235
Ethan Nicholas82399462017-10-16 12:35:44 -0400236void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
237 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400238 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400239 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
240 switch (swizzle.fComponents[0]) {
241 case 0: this->write(".left()"); break;
242 case 1: this->write(".top()"); break;
243 case 2: this->write(".right()"); break;
244 case 3: this->write(".bottom()"); break;
245 }
246 } else {
247 INHERITED::writeSwizzle(swizzle);
248 }
249}
250
Ethan Nicholas762466e2017-06-29 10:03:38 -0400251void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400252 if (fCPPMode) {
253 this->write(ref.fVariable.fName);
254 return;
255 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400256 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
257 case SK_INCOLOR_BUILTIN:
258 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400259 // EmitArgs.fInputColor is automatically set to half4(1) if
260 // no input was specified
261 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400262 break;
263 case SK_OUTCOLOR_BUILTIN:
264 this->write("%s");
265 fFormatArgs.push_back(String("args.fOutputColor"));
266 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400267 case SK_WIDTH_BUILTIN:
268 this->write("sk_Width");
269 break;
270 case SK_HEIGHT_BUILTIN:
271 this->write("sk_Height");
272 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400273 default:
274 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400275 this->write("%s");
276 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
277 this->getSamplerHandle(ref.fVariable) + ").c_str()");
278 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400279 }
280 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
281 this->write("%s");
282 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400283 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
284 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400285 String code;
286 if (ref.fVariable.fModifiers.fLayout.fWhen.size()) {
287 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
288 HCodeGenerator::FieldName(name.c_str()).c_str(),
289 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400290 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400291 } else {
292 code = var;
293 }
294 fFormatArgs.push_back(code);
295 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700296 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400297 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700298 String::printf("_outer.%s()", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400299 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700300 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400301 }
302 }
303}
304
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400305void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
306 if (s.fIsStatic) {
307 this->write("@");
308 }
309 INHERITED::writeIfStatement(s);
310}
311
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400312void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
313 if (fInMain) {
314 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
315 }
316 INHERITED::writeReturnStatement(s);
317}
318
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400319void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
320 if (s.fIsStatic) {
321 this->write("@");
322 }
323 INHERITED::writeSwitchStatement(s);
324}
325
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400326void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400327 if (c.fFunction.fBuiltin && c.fFunction.fName == "process") {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400328 // Sanity checks that are detected by function definition in sksl_fp.inc
329 SkASSERT(c.fArguments.size() == 1 || c.fArguments.size() == 2);
330 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name());
331
332 // Actually fail during compilation if arguments with valid types are
333 // provided that are not variable references, since process() is a
334 // special function that impacts code emission.
335 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
336 fErrors.error(c.fArguments[0]->fOffset,
337 "process()'s fragmentProcessor argument must be a variable reference\n");
338 return;
339 }
340 if (c.fArguments.size() > 1) {
341 // Second argument must also be a half4 expression
342 SkASSERT("half4" == c.fArguments[1]->fType.name());
343 }
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400344 int index = 0;
345 bool found = false;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400346 for (const auto& p : fProgram) {
347 if (ProgramElement::kVar_Kind == p.fKind) {
348 const VarDeclarations& decls = (const VarDeclarations&) p;
349 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000350 VarDeclaration& decl = (VarDeclaration&) *raw;
351 if (decl.fVar == &((VariableReference&) *c.fArguments[0]).fVariable) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400352 found = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000353 } else if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400354 ++index;
355 }
356 }
357 }
358 if (found) {
359 break;
360 }
361 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400362 SkASSERT(found);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400363
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400364 // Start a new extra emit code section so that the emitted child processor can depend on
365 // sksl variables defined in earlier sksl code.
366 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400367
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400368 // Set to the empty string when no input color parameter should be emitted, which means this
369 // must be properly formatted with a prefixed comma when the parameter should be inserted
370 // into the emitChild() parameter list.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400371 String inputArg;
372 if (c.fArguments.size() > 1) {
373 SkASSERT(c.fArguments.size() == 2);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400374 // Use the emitChild() variant that accepts an input color, so convert the 2nd
375 // argument's expression into C++ code that produces sksl stored in an SkString.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400376 String inputName = "_input" + to_string(index);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400377 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400378
379 // emitChild() needs a char*
380 inputArg = ", " + inputName + ".c_str()";
381 }
382
383 // Write the output handling after the possible input handling
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400384 String childName = "_child" + to_string(index);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400385 addExtraEmitCodeLine("SkString " + childName + "(\"" + childName + "\");");
386 addExtraEmitCodeLine("this->emitChild(" + to_string(index) + inputArg +
387 ", &" + childName + ", args);");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400388
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400389 this->write("%s");
390 fFormatArgs.push_back(childName + ".c_str()");
391 return;
392 }
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400393 INHERITED::writeFunctionCall(c);
394 if (c.fFunction.fBuiltin && c.fFunction.fName == "texture") {
395 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400396 SkASSERT(c.fArguments.size() >= 1);
397 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400398 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
399 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
400 ").c_str()");
401 }
402}
403
Ethan Nicholas762466e2017-06-29 10:03:38 -0400404void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
405 if (f.fDeclaration.fName == "main") {
406 fFunctionHeader = "";
407 OutputStream* oldOut = fOut;
408 StringStream buffer;
409 fOut = &buffer;
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400410 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400411 for (const auto& s : ((Block&) *f.fBody).fStatements) {
412 this->writeStatement(*s);
413 this->writeLine();
414 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400415 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400416
417 fOut = oldOut;
418 this->write(fFunctionHeader);
419 this->write(buffer.str());
420 } else {
421 INHERITED::writeFunction(f);
422 }
423}
424
425void CPPCodeGenerator::writeSetting(const Setting& s) {
426 static constexpr const char* kPrefix = "sk_Args.";
427 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
428 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400429 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400430 } else {
431 this->write(s.fName.c_str());
432 }
433}
434
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400435bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400436 const Section* s = fSectionAndParameterHelper.getSection(name);
437 if (s) {
438 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400439 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400440 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400441 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400442}
443
444void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
445 if (p.fKind == ProgramElement::kSection_Kind) {
446 return;
447 }
448 if (p.fKind == ProgramElement::kVar_Kind) {
449 const VarDeclarations& decls = (const VarDeclarations&) p;
450 if (!decls.fVars.size()) {
451 return;
452 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000453 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400454 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
455 -1 != var.fModifiers.fLayout.fBuiltin) {
456 return;
457 }
458 }
459 INHERITED::writeProgramElement(p);
460}
461
462void CPPCodeGenerator::addUniform(const Variable& var) {
463 if (!needs_uniform_var(var)) {
464 return;
465 }
466 const char* precision;
467 if (var.fModifiers.fFlags & Modifiers::kHighp_Flag) {
468 precision = "kHigh_GrSLPrecision";
469 } else if (var.fModifiers.fFlags & Modifiers::kMediump_Flag) {
470 precision = "kMedium_GrSLPrecision";
471 } else if (var.fModifiers.fFlags & Modifiers::kLowp_Flag) {
472 precision = "kLow_GrSLPrecision";
473 } else {
474 precision = "kDefault_GrSLPrecision";
475 }
476 const char* type;
477 if (var.fType == *fContext.fFloat_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400478 type = "kFloat_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400479 } else if (var.fType == *fContext.fHalf_Type) {
480 type = "kHalf_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400481 } else if (var.fType == *fContext.fFloat2_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400482 type = "kFloat2_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400483 } else if (var.fType == *fContext.fHalf2_Type) {
484 type = "kHalf2_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400485 } else if (var.fType == *fContext.fFloat4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400486 type = "kFloat4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400487 } else if (var.fType == *fContext.fHalf4_Type) {
488 type = "kHalf4_GrSLType";
Brian Osman1cb41712017-10-19 12:54:52 -0400489 } else if (var.fType == *fContext.fFloat4x4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400490 type = "kFloat4x4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400491 } else if (var.fType == *fContext.fHalf4x4_Type) {
492 type = "kHalf4x4_GrSLType";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400493 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700494 ABORT("unsupported uniform type: %s %s;\n", String(var.fType.fName).c_str(),
495 String(var.fName).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400496 }
497 if (var.fModifiers.fLayout.fWhen.size()) {
498 this->writef(" if (%s) {\n ", var.fModifiers.fLayout.fWhen.c_str());
499 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700500 String name(var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400501 this->writef(" %sVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, %s, "
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700502 "%s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type, precision,
503 name.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400504 if (var.fModifiers.fLayout.fWhen.size()) {
505 this->write(" }\n");
506 }
507}
508
Ethan Nicholascd700e92018-08-24 16:43:57 -0400509void CPPCodeGenerator::writeInputVars() {
510}
511
Ethan Nicholas762466e2017-06-29 10:03:38 -0400512void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400513 for (const auto& p : fProgram) {
514 if (ProgramElement::kVar_Kind == p.fKind) {
515 const VarDeclarations& decls = (const VarDeclarations&) p;
516 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000517 VarDeclaration& decl = (VarDeclaration&) *raw;
518 if (is_private(*decl.fVar)) {
519 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
520 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400521 "fragmentProcessor variables must be declared 'in'");
522 return;
523 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500524 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000525 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
526 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500527 String(decl.fVar->fName).c_str(),
528 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400529 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
530 // An auto-tracked uniform in variable, so add a field to hold onto the prior
531 // state. Note that tracked variables must be uniform in's and that is validated
532 // before writePrivateVars() is called.
533 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
534 SkASSERT(mapper && mapper->supportsTracking());
535
536 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
537 // The member statement is different if the mapper reports a default value
538 if (mapper->defaultValue().size() > 0) {
539 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400540 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400541 mapper->defaultValue().c_str());
542 } else {
543 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400544 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400545 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400546 }
547 }
548 }
549 }
550}
551
552void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400553 for (const auto& p : fProgram) {
554 if (ProgramElement::kVar_Kind == p.fKind) {
555 const VarDeclarations& decls = (const VarDeclarations&) p;
556 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000557 VarDeclaration& decl = (VarDeclaration&) *raw;
558 if (is_private(*decl.fVar) && decl.fValue) {
559 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400560 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000561 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400562 fCPPMode = false;
563 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400564 }
565 }
566 }
567 }
568}
569
Ethan Nicholas82399462017-10-16 12:35:44 -0400570static bool is_accessible(const Variable& var) {
571 return Type::kSampler_Kind != var.fType.kind() &&
572 Type::kOther_Kind != var.fType.kind();
573}
574
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400575void CPPCodeGenerator::newExtraEmitCodeBlock() {
576 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
577 // cpp buffer is not null, and the cpp buffer is not the current output.
578 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
579
580 // Start a new block as an empty string
581 fExtraEmitCodeBlocks.push_back("");
582 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
583 // valid sksl and makes detection trivial.
584 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
585}
586
587void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
588 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
589 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
590 // Automatically add indentation and newline
591 currentBlock += " " + toAppend + "\n";
592}
593
594void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400595 if (fCPPBuffer == nullptr) {
596 // Not actually within writeEmitCode() so nothing to flush
597 return;
598 }
599
600 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
601
602 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400603 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400604 skslBuffer->reset();
605
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400606 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000607 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400608
609 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
610 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
611 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
612 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
613 // statement left off (minus the encountered token).
614 size_t i = 0;
615 int flushPoint = -1;
616 int tokenStart = -1;
617 while (i < sksl.size()) {
618 if (tokenStart >= 0) {
619 // Looking for the end of the token
620 if (sksl[i] == '}') {
621 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
622 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
623 String toFlush = String(sksl.c_str(), flushPoint + 1);
624 // writeCodeAppend automatically removes the format args that it consumed, so
625 // fFormatArgs will be in a valid state for any future sksl
626 this->writeCodeAppend(toFlush);
627
628 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
629 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
630 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
631 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
632 }
633
634 // Now reset the sksl buffer to start after the flush point, but remove the token.
635 String compacted = String(sksl.c_str() + flushPoint + 1,
636 tokenStart - flushPoint - 1);
637 if (i < sksl.size() - 1) {
638 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
639 }
640 sksl = compacted;
641
642 // And reset iteration
643 i = -1;
644 flushPoint = -1;
645 tokenStart = -1;
646 }
647 } else {
648 // Looking for the start of extra emit block tokens, and tracking when statements end
649 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
650 flushPoint = i;
651 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
652 // found an extra emit code block token
653 tokenStart = i++;
654 }
655 }
656 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000657 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400658
659 // Once we've gone through the sksl string to this point, there are no remaining extra emit
660 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400661 this->writeCodeAppend(sksl);
662
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400663 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400664 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400665 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400666}
667
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400668void CPPCodeGenerator::writeCodeAppend(const String& code) {
669 // codeAppendf can only handle appending 1024 bytes at a time, so we need to break the string
670 // into chunks. Unfortunately we can't tell exactly how long the string is going to end up,
671 // because printf escape sequences get replaced by strings of unknown length, but keeping the
672 // format string below 512 bytes is probably safe.
673 static constexpr size_t maxChunkSize = 512;
674 size_t start = 0;
675 size_t index = 0;
676 size_t argStart = 0;
677 size_t argCount;
678 while (index < code.size()) {
679 argCount = 0;
680 this->write(" fragBuilder->codeAppendf(\"");
681 while (index < code.size() && index < start + maxChunkSize) {
682 if ('%' == code[index]) {
683 if (index == start + maxChunkSize - 1 || index == code.size() - 1) {
684 break;
685 }
686 if (code[index + 1] != '%') {
687 ++argCount;
688 }
Ethan Nicholasef0c9fd2017-10-30 10:04:14 -0400689 } else if ('\\' == code[index] && index == start + maxChunkSize - 1) {
690 // avoid splitting an escape sequence that happens to fall across a chunk boundary
691 break;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400692 }
693 ++index;
694 }
695 fOut->write(code.c_str() + start, index - start);
696 this->write("\"");
697 for (size_t i = argStart; i < argStart + argCount; ++i) {
698 this->writef(", %s", fFormatArgs[i].c_str());
699 }
700 this->write(");\n");
701 argStart += argCount;
702 start = index;
703 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400704
705 // argStart is equal to the number of fFormatArgs that were consumed
706 // so they should be removed from the list
707 if (argStart > 0) {
708 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argStart);
709 }
710}
711
712String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
713 const String& cppVar) {
714 // To do this conversion, we temporarily switch the sksl output stream
715 // to an empty stringstream and reset the format args to empty.
716 OutputStream* oldSKSL = fOut;
717 StringStream exprBuffer;
718 fOut = &exprBuffer;
719
720 std::vector<String> oldArgs(fFormatArgs);
721 fFormatArgs.clear();
722
723 // Convert the argument expression into a format string and args
724 this->writeExpression(e, Precedence::kTopLevel_Precedence);
725 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400726 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400727
728 // After generating, restore the original output stream and format args
729 fFormatArgs = oldArgs;
730 fOut = oldSKSL;
731
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400732 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
733 // block tokens won't get handled. So we need to strip them from the expression and stick them
734 // to the end of the original sksl stream.
735 String exprFormat = "";
736 int tokenStart = -1;
737 for (size_t i = 0; i < expr.size(); i++) {
738 if (tokenStart >= 0) {
739 if (expr[i] == '}') {
740 // End of the token, so append the token to fOut
741 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
742 tokenStart = -1;
743 }
744 } else {
745 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
746 tokenStart = i++;
747 } else {
748 exprFormat += expr[i];
749 }
750 }
751 }
752
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400753 // Now build the final C++ code snippet from the format string and args
754 String cppExpr;
755 if (newArgs.size() == 0) {
756 // This was a static expression, so we can simplify the input
757 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400758 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400759 } else {
760 // String formatting must occur dynamically, so have the C++ declaration
761 // use SkStringPrintf with the format args that were accumulated
762 // when the expression was written.
763 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
764 for (size_t i = 0; i < newArgs.size(); i++) {
765 cppExpr += ", " + newArgs[i];
766 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400767 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400768 }
769 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400770}
771
Ethan Nicholas762466e2017-06-29 10:03:38 -0400772bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
773 this->write(" void emitCode(EmitArgs& args) override {\n"
774 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
775 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
776 " (void) _outer;\n",
777 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400778 for (const auto& p : fProgram) {
779 if (ProgramElement::kVar_Kind == p.fKind) {
780 const VarDeclarations& decls = (const VarDeclarations&) p;
781 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000782 VarDeclaration& decl = (VarDeclaration&) *raw;
783 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400784 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000785 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
786 is_accessible(*decl.fVar)) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400787 this->writef(" auto %s = _outer.%s();\n"
788 " (void) %s;\n",
789 name, name, name);
790 }
791 }
792 }
793 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400794 this->writePrivateVarValues();
795 for (const auto u : uniforms) {
796 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400797 }
798 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400799
800 // Save original buffer as the CPP buffer for flushEmittedCode()
801 fCPPBuffer = fOut;
802 StringStream skslBuffer;
803 fOut = &skslBuffer;
804
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400805 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400806 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400807 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400808
809 // Then restore the original CPP buffer and close the function
810 fOut = fCPPBuffer;
811 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400812 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400813 return result;
814}
815
816void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
817 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400818 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
819 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400820 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
821 "const GrFragmentProcessor& _proc) override {\n",
822 pdman);
823 bool wroteProcessor = false;
824 for (const auto u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400825 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400826 if (!wroteProcessor) {
827 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
828 wroteProcessor = true;
829 this->writef(" {\n");
830 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400831
832 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
833 SkASSERT(mapper);
834
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700835 String nameString(u->fName);
836 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400837
838 // Switches for setData behavior in the generated code
839 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
840 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
841 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
842
843 String uniformName = HCodeGenerator::FieldName(name) + "Var";
844
845 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
846 if (conditionalUniform) {
847 // Add a pre-check to make sure the uniform was emitted
848 // before trying to send any data to the GPU
849 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
850 indent += " ";
851 }
852
853 String valueVar = "";
854 if (needsValueDeclaration) {
855 valueVar.appendf("%sValue", name);
856 // Use AccessType since that will match the return type of _outer's public API.
857 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
858 u->fModifiers.fLayout);
859 this->writef("%s%s %s = _outer.%s();\n",
860 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400861 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -0400862 // Not tracked and the mapper only needs to use the value once
863 // so send it a safe expression instead of the variable name
864 valueVar.appendf("(_outer.%s())", name);
865 }
866
867 if (isTracked) {
868 SkASSERT(mapper->supportsTracking());
869
870 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
871 this->writef("%sif (%s) {\n"
872 "%s %s;\n"
873 "%s %s;\n"
874 "%s}\n", indent.c_str(),
875 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
876 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
877 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
878 } else {
879 this->writef("%s%s;\n", indent.c_str(),
880 mapper->setUniform(pdman, uniformName, valueVar).c_str());
881 }
882
883 if (conditionalUniform) {
884 // Close the earlier precheck block
885 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400886 }
887 }
888 }
889 if (wroteProcessor) {
890 this->writef(" }\n");
891 }
Ethan Nicholas68990be2017-07-13 09:36:52 -0400892 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500893 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400894 for (const auto& p : fProgram) {
895 if (ProgramElement::kVar_Kind == p.fKind) {
896 const VarDeclarations& decls = (const VarDeclarations&) p;
897 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000898 VarDeclaration& decl = (VarDeclaration&) *raw;
899 String nameString(decl.fVar->fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700900 const char* name = nameString.c_str();
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500901 if (decl.fVar->fType.kind() == Type::kSampler_Kind) {
902 this->writef(" GrSurfaceProxy& %sProxy = "
903 "*_outer.textureSampler(%d).proxy();\n",
904 name, samplerIndex);
Brian Salomonfd98c2c2018-07-31 17:25:29 -0400905 this->writef(" GrTexture& %s = *%sProxy.peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500906 name, name);
907 this->writef(" (void) %s;\n", name);
908 ++samplerIndex;
909 } else if (needs_uniform_var(*decl.fVar)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400910 this->writef(" UniformHandle& %s = %sVar;\n"
911 " (void) %s;\n",
912 name, HCodeGenerator::FieldName(name).c_str(), name);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000913 } else if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
914 decl.fVar->fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400915 if (!wroteProcessor) {
916 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
917 fullName);
918 wroteProcessor = true;
919 }
920 this->writef(" auto %s = _outer.%s();\n"
921 " (void) %s;\n",
922 name, name, name);
923 }
924 }
925 }
926 }
927 this->writeSection(SET_DATA_SECTION);
928 }
929 this->write(" }\n");
930}
931
Brian Salomonf7dcd762018-07-30 14:48:15 -0400932void CPPCodeGenerator::writeOnTextureSampler() {
933 bool foundSampler = false;
934 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
935 if (param->fType.kind() == Type::kSampler_Kind) {
936 if (!foundSampler) {
937 this->writef(
938 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
939 "index) const {\n",
940 fFullName.c_str());
941 this->writef(" return IthTextureSampler(index, %s",
942 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
943 foundSampler = true;
944 } else {
945 this->writef(", %s",
946 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
947 }
948 }
949 }
950 if (foundSampler) {
951 this->write(");\n}\n");
952 }
953}
954
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400955void CPPCodeGenerator::writeClone() {
956 if (!this->writeSection(CLONE_SECTION)) {
957 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700958 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
959 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400960 }
961 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -0400962 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
963 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400964 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400965 if (param->fType == *fContext.fFragmentProcessor_Type) {
966 continue;
967 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700968 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400969 this->writef("\n, %s(src.%s)",
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400970 fieldName.c_str(),
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400971 fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400972 }
Ethan Nicholas929a6812018-08-06 14:56:59 -0400973 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
974 for (size_t i = 0; i < transforms.size(); ++i) {
975 const Section& s = *transforms[i];
976 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
977 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400978 }
Ethan Nicholasabff9562017-10-09 10:54:08 -0400979 this->writef(" {\n");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400980 int childCount = 0;
Brian Salomonf7dcd762018-07-30 14:48:15 -0400981 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400982 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
983 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -0400984 ++samplerCount;
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400985 } else if (param->fType == *fContext.fFragmentProcessor_Type) {
986 this->writef(" this->registerChildProcessor(src.childProcessor(%d).clone());"
987 "\n", childCount++);
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400988 }
989 }
Brian Salomonf7dcd762018-07-30 14:48:15 -0400990 if (samplerCount) {
991 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
992 }
Ethan Nicholas929a6812018-08-06 14:56:59 -0400993 for (size_t i = 0; i < transforms.size(); ++i) {
994 const Section& s = *transforms[i];
995 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
996 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400997 }
998 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -0400999 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1000 fFullName.c_str());
1001 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1002 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001003 this->write("}\n");
1004 }
1005}
1006
Ethan Nicholas762466e2017-06-29 10:03:38 -04001007void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001008 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1009 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001010 this->writef(
1011 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1012 "#if GR_TEST_UTILS\n"
1013 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1014 fFullName.c_str(),
1015 fFullName.c_str(),
1016 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001017 this->writeSection(TEST_CODE_SECTION);
1018 this->write("}\n"
1019 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001020 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001021}
1022
1023void CPPCodeGenerator::writeGetKey() {
1024 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1025 "GrProcessorKeyBuilder* b) const {\n",
1026 fFullName.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001027 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001028 String nameString(param->fName);
1029 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001030 if (param->fModifiers.fLayout.fKey != Layout::kNo_Key &&
1031 (param->fModifiers.fFlags & Modifiers::kUniform_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001032 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -04001033 "layout(key) may not be specified on uniforms");
1034 }
1035 switch (param->fModifiers.fLayout.fKey) {
1036 case Layout::kKey_Key:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001037 if (param->fType == *fContext.fFloat4x4_Type) {
1038 ABORT("no automatic key handling for float4x4\n");
1039 } else if (param->fType == *fContext.fFloat2_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001040 this->writef(" b->add32(%s.fX);\n",
1041 HCodeGenerator::FieldName(name).c_str());
1042 this->writef(" b->add32(%s.fY);\n",
1043 HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001044 } else if (param->fType == *fContext.fFloat4_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001045 this->writef(" b->add32(%s.x());\n",
1046 HCodeGenerator::FieldName(name).c_str());
1047 this->writef(" b->add32(%s.y());\n",
1048 HCodeGenerator::FieldName(name).c_str());
1049 this->writef(" b->add32(%s.width());\n",
1050 HCodeGenerator::FieldName(name).c_str());
1051 this->writef(" b->add32(%s.height());\n",
1052 HCodeGenerator::FieldName(name).c_str());
1053 } else {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001054 this->writef(" b->add32((int32_t) %s);\n",
Ethan Nicholas762466e2017-06-29 10:03:38 -04001055 HCodeGenerator::FieldName(name).c_str());
1056 }
1057 break;
1058 case Layout::kIdentity_Key:
1059 if (param->fType.kind() != Type::kMatrix_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001060 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -04001061 "layout(key=identity) requires matrix type");
1062 }
1063 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1064 HCodeGenerator::FieldName(name).c_str());
1065 break;
1066 case Layout::kNo_Key:
1067 break;
1068 }
1069 }
1070 this->write("}\n");
1071}
1072
1073bool CPPCodeGenerator::generateCode() {
1074 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001075 for (const auto& p : fProgram) {
1076 if (ProgramElement::kVar_Kind == p.fKind) {
1077 const VarDeclarations& decls = (const VarDeclarations&) p;
1078 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001079 VarDeclaration& decl = (VarDeclaration&) *raw;
1080 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1081 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1082 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001083 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001084
1085 if (is_uniform_in(*decl.fVar)) {
1086 // Validate the "uniform in" declarations to make sure they are fully supported,
1087 // instead of generating surprising C++
1088 const UniformCTypeMapper* mapper =
1089 UniformCTypeMapper::Get(fContext, *decl.fVar);
1090 if (mapper == nullptr) {
1091 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1092 + "'s type is not supported for use as a 'uniform in'");
1093 return false;
1094 }
1095 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1096 if (!mapper->supportsTracking()) {
1097 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1098 + "'s type does not support state tracking");
1099 return false;
1100 }
1101 }
1102
1103 } else {
1104 // If it's not a uniform_in, it's an error to be tracked
1105 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1106 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1107 return false;
1108 }
1109 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001110 }
1111 }
1112 }
1113 const char* baseName = fName.c_str();
1114 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001115 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001116 this->writef(kFragmentProcessorHeader, fullName);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001117 this->writef("#include \"%s.h\"\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001118 this->writeSection(CPP_SECTION);
Brian Osman1cb41712017-10-19 12:54:52 -04001119 this->writef("#include \"glsl/GrGLSLFragmentProcessor.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001120 "#include \"glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1121 "#include \"glsl/GrGLSLProgramBuilder.h\"\n"
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001122 "#include \"GrTexture.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001123 "#include \"SkSLCPP.h\"\n"
1124 "#include \"SkSLUtil.h\"\n"
1125 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1126 "public:\n"
1127 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001128 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001129 bool result = this->writeEmitCode(uniforms);
1130 this->write("private:\n");
1131 this->writeSetData(uniforms);
1132 this->writePrivateVars();
1133 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001134 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001135 this->writef(" UniformHandle %sVar;\n",
1136 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001137 }
1138 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001139 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001140 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001141 this->writef(" UniformHandle %sVar;\n",
1142 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001143 }
1144 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001145 this->writef("};\n"
1146 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1147 " return new GrGLSL%s();\n"
1148 "}\n",
1149 fullName, baseName);
1150 this->writeGetKey();
1151 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1152 " const %s& that = other.cast<%s>();\n"
1153 " (void) that;\n",
1154 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001155 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001156 if (param->fType == *fContext.fFragmentProcessor_Type) {
1157 continue;
1158 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001159 String nameString(param->fName);
1160 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001161 this->writef(" if (%s != that.%s) return false;\n",
1162 HCodeGenerator::FieldName(name).c_str(),
1163 HCodeGenerator::FieldName(name).c_str());
1164 }
1165 this->write(" return true;\n"
1166 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001167 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001168 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001169 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001170 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001171
Ethan Nicholas762466e2017-06-29 10:03:38 -04001172 result &= 0 == fErrors.errorCount();
1173 return result;
1174}
1175
1176} // namespace