blob: 5f4665f7de4c711152194a3179be2c1b8788b409 [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 Ludwigd0440192018-09-07 14:24:52 +0000100 fExtraEmitCodeCode += " SkString " + name +
101 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
102 to_string(index) + "]);\n";
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 Ludwigd0440192018-09-07 14:24:52 +0000364 // Flush all previous statements so that this emitted child can
365 // depend upon any declared variables within that section
366 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400367
Michael Ludwigd0440192018-09-07 14:24:52 +0000368 // Set to the empty string when no input color parameter should be emitted,
369 // which means this must be properly formatted with a prefixed comma
370 // when the parameter should be inserted 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 Ludwigd0440192018-09-07 14:24:52 +0000374 // Use the emitChild() variant that accepts an input color, so convert
375 // the 2nd argument's expression into C++ code that produces sksl
376 // stored in an SkString.
377
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400378 String inputName = "_input" + to_string(index);
Michael Ludwigd0440192018-09-07 14:24:52 +0000379 fExtraEmitCodeCode += " " + convertSKSLExpressionToCPP(
380 *c.fArguments[1], inputName);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400381
382 // emitChild() needs a char*
383 inputArg = ", " + inputName + ".c_str()";
384 }
385
386 // Write the output handling after the possible input handling
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400387 String childName = "_child" + to_string(index);
Michael Ludwigd0440192018-09-07 14:24:52 +0000388 fExtraEmitCodeCode += " SkString " + childName + "(\"" + childName + "\");\n";
389 fExtraEmitCodeCode += " this->emitChild(" + to_string(index) + inputArg +
390 ", &" + childName + ", args);\n";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400391
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400392 this->write("%s");
393 fFormatArgs.push_back(childName + ".c_str()");
394 return;
395 }
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400396 INHERITED::writeFunctionCall(c);
397 if (c.fFunction.fBuiltin && c.fFunction.fName == "texture") {
398 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400399 SkASSERT(c.fArguments.size() >= 1);
400 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400401 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
402 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
403 ").c_str()");
404 }
405}
406
Ethan Nicholas762466e2017-06-29 10:03:38 -0400407void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
408 if (f.fDeclaration.fName == "main") {
409 fFunctionHeader = "";
410 OutputStream* oldOut = fOut;
411 StringStream buffer;
412 fOut = &buffer;
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400413 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400414 for (const auto& s : ((Block&) *f.fBody).fStatements) {
415 this->writeStatement(*s);
416 this->writeLine();
417 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400418 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400419
420 fOut = oldOut;
421 this->write(fFunctionHeader);
422 this->write(buffer.str());
423 } else {
424 INHERITED::writeFunction(f);
425 }
426}
427
428void CPPCodeGenerator::writeSetting(const Setting& s) {
429 static constexpr const char* kPrefix = "sk_Args.";
430 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
431 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400432 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400433 } else {
434 this->write(s.fName.c_str());
435 }
436}
437
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400438bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400439 const Section* s = fSectionAndParameterHelper.getSection(name);
440 if (s) {
441 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400442 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400443 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400444 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400445}
446
447void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
448 if (p.fKind == ProgramElement::kSection_Kind) {
449 return;
450 }
451 if (p.fKind == ProgramElement::kVar_Kind) {
452 const VarDeclarations& decls = (const VarDeclarations&) p;
453 if (!decls.fVars.size()) {
454 return;
455 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000456 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400457 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
458 -1 != var.fModifiers.fLayout.fBuiltin) {
459 return;
460 }
461 }
462 INHERITED::writeProgramElement(p);
463}
464
465void CPPCodeGenerator::addUniform(const Variable& var) {
466 if (!needs_uniform_var(var)) {
467 return;
468 }
469 const char* precision;
470 if (var.fModifiers.fFlags & Modifiers::kHighp_Flag) {
471 precision = "kHigh_GrSLPrecision";
472 } else if (var.fModifiers.fFlags & Modifiers::kMediump_Flag) {
473 precision = "kMedium_GrSLPrecision";
474 } else if (var.fModifiers.fFlags & Modifiers::kLowp_Flag) {
475 precision = "kLow_GrSLPrecision";
476 } else {
477 precision = "kDefault_GrSLPrecision";
478 }
479 const char* type;
480 if (var.fType == *fContext.fFloat_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400481 type = "kFloat_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400482 } else if (var.fType == *fContext.fHalf_Type) {
483 type = "kHalf_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400484 } else if (var.fType == *fContext.fFloat2_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400485 type = "kFloat2_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400486 } else if (var.fType == *fContext.fHalf2_Type) {
487 type = "kHalf2_GrSLType";
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400488 } else if (var.fType == *fContext.fFloat4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400489 type = "kFloat4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400490 } else if (var.fType == *fContext.fHalf4_Type) {
491 type = "kHalf4_GrSLType";
Brian Osman1cb41712017-10-19 12:54:52 -0400492 } else if (var.fType == *fContext.fFloat4x4_Type) {
Ethan Nicholas8aa45692017-09-20 11:24:15 -0400493 type = "kFloat4x4_GrSLType";
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400494 } else if (var.fType == *fContext.fHalf4x4_Type) {
495 type = "kHalf4x4_GrSLType";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400496 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700497 ABORT("unsupported uniform type: %s %s;\n", String(var.fType.fName).c_str(),
498 String(var.fName).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400499 }
500 if (var.fModifiers.fLayout.fWhen.size()) {
501 this->writef(" if (%s) {\n ", var.fModifiers.fLayout.fWhen.c_str());
502 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700503 String name(var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400504 this->writef(" %sVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, %s, "
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700505 "%s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type, precision,
506 name.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400507 if (var.fModifiers.fLayout.fWhen.size()) {
508 this->write(" }\n");
509 }
510}
511
Ethan Nicholascd700e92018-08-24 16:43:57 -0400512void CPPCodeGenerator::writeInputVars() {
513}
514
Ethan Nicholas762466e2017-06-29 10:03:38 -0400515void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400516 for (const auto& p : fProgram) {
517 if (ProgramElement::kVar_Kind == p.fKind) {
518 const VarDeclarations& decls = (const VarDeclarations&) p;
519 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000520 VarDeclaration& decl = (VarDeclaration&) *raw;
521 if (is_private(*decl.fVar)) {
522 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
523 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400524 "fragmentProcessor variables must be declared 'in'");
525 return;
526 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500527 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000528 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
529 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500530 String(decl.fVar->fName).c_str(),
531 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400532 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
533 // An auto-tracked uniform in variable, so add a field to hold onto the prior
534 // state. Note that tracked variables must be uniform in's and that is validated
535 // before writePrivateVars() is called.
536 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
537 SkASSERT(mapper && mapper->supportsTracking());
538
539 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
540 // The member statement is different if the mapper reports a default value
541 if (mapper->defaultValue().size() > 0) {
542 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400543 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400544 mapper->defaultValue().c_str());
545 } else {
546 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400547 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400548 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400549 }
550 }
551 }
552 }
553}
554
555void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400556 for (const auto& p : fProgram) {
557 if (ProgramElement::kVar_Kind == p.fKind) {
558 const VarDeclarations& decls = (const VarDeclarations&) p;
559 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000560 VarDeclaration& decl = (VarDeclaration&) *raw;
561 if (is_private(*decl.fVar) && decl.fValue) {
562 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400563 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000564 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400565 fCPPMode = false;
566 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400567 }
568 }
569 }
570 }
571}
572
Ethan Nicholas82399462017-10-16 12:35:44 -0400573static bool is_accessible(const Variable& var) {
574 return Type::kSampler_Kind != var.fType.kind() &&
575 Type::kOther_Kind != var.fType.kind();
576}
577
Michael Ludwigd0440192018-09-07 14:24:52 +0000578void CPPCodeGenerator::flushEmittedCode(bool flushAll) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400579 if (fCPPBuffer == nullptr) {
580 // Not actually within writeEmitCode() so nothing to flush
581 return;
582 }
583
584 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
585
586 String sksl = skslBuffer->str();
Michael Ludwigd0440192018-09-07 14:24:52 +0000587 // Empty the accumulation buffer; if there are any partial statements in
588 // the extracted sksl string they will be re-added later
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400589 skslBuffer->reset();
590
Michael Ludwigd0440192018-09-07 14:24:52 +0000591 if (!flushAll) {
592 // Find the last ';', '{', or '}' and leave everything after that in the buffer
593 int lastStatementEnd = sksl.findLastOf(';');
594 int lastBlockOpen = sksl.findLastOf('{');
595 int lastBlockEnd = sksl.findLastOf('}');
Michael Ludwig9b8181b2018-09-07 09:32:11 -0400596
Michael Ludwigd0440192018-09-07 14:24:52 +0000597 int flushPoint = std::max(lastStatementEnd, std::max(lastBlockEnd, lastBlockOpen));
Michael Ludwig9b8181b2018-09-07 09:32:11 -0400598
Michael Ludwigd0440192018-09-07 14:24:52 +0000599 // NOTE: this does the right thing when flushPoint = -1
600 if (flushPoint < (int) sksl.size() - 1) {
601 // There is partial sksl content that can't be flushed yet so put
602 // that back into the sksl buffer and remove it from the string
603 skslBuffer->writeText(sksl.c_str() + flushPoint + 1);
604 sksl = String(sksl.c_str(), flushPoint + 1);
Michael Ludwig9b8181b2018-09-07 09:32:11 -0400605 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400606 }
Michael Ludwig9b8181b2018-09-07 09:32:11 -0400607
Michael Ludwigd0440192018-09-07 14:24:52 +0000608 // Switch back to the CPP buffer for the actual code appending statements
609 fOut = fCPPBuffer;
610 if (fExtraEmitCodeCode.size() > 0) {
611 this->writef("%s", fExtraEmitCodeCode.c_str());
612 fExtraEmitCodeCode.reset();
613 }
614 // writeCodeAppend automatically removes the format args that it consumed,
615 // so fFormatArgs will be in a valid state for any partial statements left
616 // in the sksl buffer.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400617 this->writeCodeAppend(sksl);
618
Michael Ludwigd0440192018-09-07 14:24:52 +0000619 // After appending, switch back to an sksl buffer that contains any
620 // remaining partial statements that couldn't be appended
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400621 fOut = skslBuffer;
622}
623
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400624void CPPCodeGenerator::writeCodeAppend(const String& code) {
625 // codeAppendf can only handle appending 1024 bytes at a time, so we need to break the string
626 // into chunks. Unfortunately we can't tell exactly how long the string is going to end up,
627 // because printf escape sequences get replaced by strings of unknown length, but keeping the
628 // format string below 512 bytes is probably safe.
629 static constexpr size_t maxChunkSize = 512;
630 size_t start = 0;
631 size_t index = 0;
632 size_t argStart = 0;
633 size_t argCount;
634 while (index < code.size()) {
635 argCount = 0;
636 this->write(" fragBuilder->codeAppendf(\"");
637 while (index < code.size() && index < start + maxChunkSize) {
638 if ('%' == code[index]) {
639 if (index == start + maxChunkSize - 1 || index == code.size() - 1) {
640 break;
641 }
642 if (code[index + 1] != '%') {
643 ++argCount;
644 }
Ethan Nicholasef0c9fd2017-10-30 10:04:14 -0400645 } else if ('\\' == code[index] && index == start + maxChunkSize - 1) {
646 // avoid splitting an escape sequence that happens to fall across a chunk boundary
647 break;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400648 }
649 ++index;
650 }
651 fOut->write(code.c_str() + start, index - start);
652 this->write("\"");
653 for (size_t i = argStart; i < argStart + argCount; ++i) {
654 this->writef(", %s", fFormatArgs[i].c_str());
655 }
656 this->write(");\n");
657 argStart += argCount;
658 start = index;
659 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400660
661 // argStart is equal to the number of fFormatArgs that were consumed
662 // so they should be removed from the list
663 if (argStart > 0) {
664 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argStart);
665 }
666}
667
668String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
669 const String& cppVar) {
670 // To do this conversion, we temporarily switch the sksl output stream
671 // to an empty stringstream and reset the format args to empty.
672 OutputStream* oldSKSL = fOut;
673 StringStream exprBuffer;
674 fOut = &exprBuffer;
675
676 std::vector<String> oldArgs(fFormatArgs);
677 fFormatArgs.clear();
678
679 // Convert the argument expression into a format string and args
680 this->writeExpression(e, Precedence::kTopLevel_Precedence);
681 std::vector<String> newArgs(fFormatArgs);
Michael Ludwigd0440192018-09-07 14:24:52 +0000682 String exprFormat = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400683
684 // After generating, restore the original output stream and format args
685 fFormatArgs = oldArgs;
686 fOut = oldSKSL;
687
688 // Now build the final C++ code snippet from the format string and args
689 String cppExpr;
690 if (newArgs.size() == 0) {
691 // This was a static expression, so we can simplify the input
692 // color declaration in the emitted code to just a static string
Michael Ludwigd0440192018-09-07 14:24:52 +0000693 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");\n";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400694 } else {
695 // String formatting must occur dynamically, so have the C++ declaration
696 // use SkStringPrintf with the format args that were accumulated
697 // when the expression was written.
698 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
699 for (size_t i = 0; i < newArgs.size(); i++) {
700 cppExpr += ", " + newArgs[i];
701 }
Michael Ludwigd0440192018-09-07 14:24:52 +0000702 cppExpr += ");\n";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400703 }
704 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400705}
706
Ethan Nicholas762466e2017-06-29 10:03:38 -0400707bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
708 this->write(" void emitCode(EmitArgs& args) override {\n"
709 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
710 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
711 " (void) _outer;\n",
712 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400713 for (const auto& p : fProgram) {
714 if (ProgramElement::kVar_Kind == p.fKind) {
715 const VarDeclarations& decls = (const VarDeclarations&) p;
716 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000717 VarDeclaration& decl = (VarDeclaration&) *raw;
718 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400719 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000720 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
721 is_accessible(*decl.fVar)) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400722 this->writef(" auto %s = _outer.%s();\n"
723 " (void) %s;\n",
724 name, name, name);
725 }
726 }
727 }
728 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400729 this->writePrivateVarValues();
730 for (const auto u : uniforms) {
731 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400732 }
733 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400734
735 // Save original buffer as the CPP buffer for flushEmittedCode()
736 fCPPBuffer = fOut;
737 StringStream skslBuffer;
738 fOut = &skslBuffer;
739
Ethan Nicholas762466e2017-06-29 10:03:38 -0400740 bool result = INHERITED::generateCode();
Michael Ludwigd0440192018-09-07 14:24:52 +0000741 // Final flush in case there is anything extra, forcing it to emit everything
742 this->flushEmittedCode(true);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400743
744 // Then restore the original CPP buffer and close the function
745 fOut = fCPPBuffer;
746 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400747 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400748 return result;
749}
750
751void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
752 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400753 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
754 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400755 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
756 "const GrFragmentProcessor& _proc) override {\n",
757 pdman);
758 bool wroteProcessor = false;
759 for (const auto u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400760 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400761 if (!wroteProcessor) {
762 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
763 wroteProcessor = true;
764 this->writef(" {\n");
765 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400766
767 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
768 SkASSERT(mapper);
769
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700770 String nameString(u->fName);
771 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400772
773 // Switches for setData behavior in the generated code
774 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
775 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
776 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
777
778 String uniformName = HCodeGenerator::FieldName(name) + "Var";
779
780 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
781 if (conditionalUniform) {
782 // Add a pre-check to make sure the uniform was emitted
783 // before trying to send any data to the GPU
784 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
785 indent += " ";
786 }
787
788 String valueVar = "";
789 if (needsValueDeclaration) {
790 valueVar.appendf("%sValue", name);
791 // Use AccessType since that will match the return type of _outer's public API.
792 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
793 u->fModifiers.fLayout);
794 this->writef("%s%s %s = _outer.%s();\n",
795 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400796 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -0400797 // Not tracked and the mapper only needs to use the value once
798 // so send it a safe expression instead of the variable name
799 valueVar.appendf("(_outer.%s())", name);
800 }
801
802 if (isTracked) {
803 SkASSERT(mapper->supportsTracking());
804
805 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
806 this->writef("%sif (%s) {\n"
807 "%s %s;\n"
808 "%s %s;\n"
809 "%s}\n", indent.c_str(),
810 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
811 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
812 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
813 } else {
814 this->writef("%s%s;\n", indent.c_str(),
815 mapper->setUniform(pdman, uniformName, valueVar).c_str());
816 }
817
818 if (conditionalUniform) {
819 // Close the earlier precheck block
820 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400821 }
822 }
823 }
824 if (wroteProcessor) {
825 this->writef(" }\n");
826 }
Ethan Nicholas68990be2017-07-13 09:36:52 -0400827 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500828 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400829 for (const auto& p : fProgram) {
830 if (ProgramElement::kVar_Kind == p.fKind) {
831 const VarDeclarations& decls = (const VarDeclarations&) p;
832 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000833 VarDeclaration& decl = (VarDeclaration&) *raw;
834 String nameString(decl.fVar->fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700835 const char* name = nameString.c_str();
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500836 if (decl.fVar->fType.kind() == Type::kSampler_Kind) {
837 this->writef(" GrSurfaceProxy& %sProxy = "
838 "*_outer.textureSampler(%d).proxy();\n",
839 name, samplerIndex);
Brian Salomonfd98c2c2018-07-31 17:25:29 -0400840 this->writef(" GrTexture& %s = *%sProxy.peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500841 name, name);
842 this->writef(" (void) %s;\n", name);
843 ++samplerIndex;
844 } else if (needs_uniform_var(*decl.fVar)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400845 this->writef(" UniformHandle& %s = %sVar;\n"
846 " (void) %s;\n",
847 name, HCodeGenerator::FieldName(name).c_str(), name);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000848 } else if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
849 decl.fVar->fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400850 if (!wroteProcessor) {
851 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
852 fullName);
853 wroteProcessor = true;
854 }
855 this->writef(" auto %s = _outer.%s();\n"
856 " (void) %s;\n",
857 name, name, name);
858 }
859 }
860 }
861 }
862 this->writeSection(SET_DATA_SECTION);
863 }
864 this->write(" }\n");
865}
866
Brian Salomonf7dcd762018-07-30 14:48:15 -0400867void CPPCodeGenerator::writeOnTextureSampler() {
868 bool foundSampler = false;
869 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
870 if (param->fType.kind() == Type::kSampler_Kind) {
871 if (!foundSampler) {
872 this->writef(
873 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
874 "index) const {\n",
875 fFullName.c_str());
876 this->writef(" return IthTextureSampler(index, %s",
877 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
878 foundSampler = true;
879 } else {
880 this->writef(", %s",
881 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
882 }
883 }
884 }
885 if (foundSampler) {
886 this->write(");\n}\n");
887 }
888}
889
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400890void CPPCodeGenerator::writeClone() {
891 if (!this->writeSection(CLONE_SECTION)) {
892 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700893 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
894 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400895 }
896 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -0400897 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
898 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400899 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400900 if (param->fType == *fContext.fFragmentProcessor_Type) {
901 continue;
902 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700903 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400904 this->writef("\n, %s(src.%s)",
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400905 fieldName.c_str(),
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400906 fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400907 }
Ethan Nicholas929a6812018-08-06 14:56:59 -0400908 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
909 for (size_t i = 0; i < transforms.size(); ++i) {
910 const Section& s = *transforms[i];
911 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
912 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400913 }
Ethan Nicholasabff9562017-10-09 10:54:08 -0400914 this->writef(" {\n");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400915 int childCount = 0;
Brian Salomonf7dcd762018-07-30 14:48:15 -0400916 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400917 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
918 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -0400919 ++samplerCount;
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400920 } else if (param->fType == *fContext.fFragmentProcessor_Type) {
921 this->writef(" this->registerChildProcessor(src.childProcessor(%d).clone());"
922 "\n", childCount++);
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400923 }
924 }
Brian Salomonf7dcd762018-07-30 14:48:15 -0400925 if (samplerCount) {
926 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
927 }
Ethan Nicholas929a6812018-08-06 14:56:59 -0400928 for (size_t i = 0; i < transforms.size(); ++i) {
929 const Section& s = *transforms[i];
930 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
931 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400932 }
933 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -0400934 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
935 fFullName.c_str());
936 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
937 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400938 this->write("}\n");
939 }
940}
941
Ethan Nicholas762466e2017-06-29 10:03:38 -0400942void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400943 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
944 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -0400945 this->writef(
946 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
947 "#if GR_TEST_UTILS\n"
948 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
949 fFullName.c_str(),
950 fFullName.c_str(),
951 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -0400952 this->writeSection(TEST_CODE_SECTION);
953 this->write("}\n"
954 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400955 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400956}
957
958void CPPCodeGenerator::writeGetKey() {
959 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
960 "GrProcessorKeyBuilder* b) const {\n",
961 fFullName.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -0400962 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700963 String nameString(param->fName);
964 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400965 if (param->fModifiers.fLayout.fKey != Layout::kNo_Key &&
966 (param->fModifiers.fFlags & Modifiers::kUniform_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700967 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400968 "layout(key) may not be specified on uniforms");
969 }
970 switch (param->fModifiers.fLayout.fKey) {
971 case Layout::kKey_Key:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400972 if (param->fType == *fContext.fFloat4x4_Type) {
973 ABORT("no automatic key handling for float4x4\n");
974 } else if (param->fType == *fContext.fFloat2_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400975 this->writef(" b->add32(%s.fX);\n",
976 HCodeGenerator::FieldName(name).c_str());
977 this->writef(" b->add32(%s.fY);\n",
978 HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400979 } else if (param->fType == *fContext.fFloat4_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400980 this->writef(" b->add32(%s.x());\n",
981 HCodeGenerator::FieldName(name).c_str());
982 this->writef(" b->add32(%s.y());\n",
983 HCodeGenerator::FieldName(name).c_str());
984 this->writef(" b->add32(%s.width());\n",
985 HCodeGenerator::FieldName(name).c_str());
986 this->writef(" b->add32(%s.height());\n",
987 HCodeGenerator::FieldName(name).c_str());
988 } else {
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500989 this->writef(" b->add32((int32_t) %s);\n",
Ethan Nicholas762466e2017-06-29 10:03:38 -0400990 HCodeGenerator::FieldName(name).c_str());
991 }
992 break;
993 case Layout::kIdentity_Key:
994 if (param->fType.kind() != Type::kMatrix_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700995 fErrors.error(param->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400996 "layout(key=identity) requires matrix type");
997 }
998 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
999 HCodeGenerator::FieldName(name).c_str());
1000 break;
1001 case Layout::kNo_Key:
1002 break;
1003 }
1004 }
1005 this->write("}\n");
1006}
1007
1008bool CPPCodeGenerator::generateCode() {
1009 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001010 for (const auto& p : fProgram) {
1011 if (ProgramElement::kVar_Kind == p.fKind) {
1012 const VarDeclarations& decls = (const VarDeclarations&) p;
1013 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001014 VarDeclaration& decl = (VarDeclaration&) *raw;
1015 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1016 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1017 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001018 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001019
1020 if (is_uniform_in(*decl.fVar)) {
1021 // Validate the "uniform in" declarations to make sure they are fully supported,
1022 // instead of generating surprising C++
1023 const UniformCTypeMapper* mapper =
1024 UniformCTypeMapper::Get(fContext, *decl.fVar);
1025 if (mapper == nullptr) {
1026 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1027 + "'s type is not supported for use as a 'uniform in'");
1028 return false;
1029 }
1030 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1031 if (!mapper->supportsTracking()) {
1032 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1033 + "'s type does not support state tracking");
1034 return false;
1035 }
1036 }
1037
1038 } else {
1039 // If it's not a uniform_in, it's an error to be tracked
1040 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1041 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1042 return false;
1043 }
1044 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001045 }
1046 }
1047 }
1048 const char* baseName = fName.c_str();
1049 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001050 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001051 this->writef(kFragmentProcessorHeader, fullName);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001052 this->writef("#include \"%s.h\"\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001053 this->writeSection(CPP_SECTION);
Brian Osman1cb41712017-10-19 12:54:52 -04001054 this->writef("#include \"glsl/GrGLSLFragmentProcessor.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001055 "#include \"glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1056 "#include \"glsl/GrGLSLProgramBuilder.h\"\n"
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001057 "#include \"GrTexture.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001058 "#include \"SkSLCPP.h\"\n"
1059 "#include \"SkSLUtil.h\"\n"
1060 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1061 "public:\n"
1062 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001063 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001064 bool result = this->writeEmitCode(uniforms);
1065 this->write("private:\n");
1066 this->writeSetData(uniforms);
1067 this->writePrivateVars();
1068 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001069 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001070 this->writef(" UniformHandle %sVar;\n",
1071 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001072 }
1073 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001074 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001075 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001076 this->writef(" UniformHandle %sVar;\n",
1077 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001078 }
1079 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001080 this->writef("};\n"
1081 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1082 " return new GrGLSL%s();\n"
1083 "}\n",
1084 fullName, baseName);
1085 this->writeGetKey();
1086 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1087 " const %s& that = other.cast<%s>();\n"
1088 " (void) that;\n",
1089 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001090 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001091 if (param->fType == *fContext.fFragmentProcessor_Type) {
1092 continue;
1093 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001094 String nameString(param->fName);
1095 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001096 this->writef(" if (%s != that.%s) return false;\n",
1097 HCodeGenerator::FieldName(name).c_str(),
1098 HCodeGenerator::FieldName(name).c_str());
1099 }
1100 this->write(" return true;\n"
1101 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001102 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001103 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001104 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001105 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001106
Ethan Nicholas762466e2017-06-29 10:03:38 -04001107 result &= 0 == fErrors.errorCount();
1108 return result;
1109}
1110
1111} // namespace