blob: c641fbdebf36b134cbeba7c36c21f78749591845 [file] [log] [blame]
Ethan Nicholas762466e2017-06-29 10:03:38 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCPPCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -04009
Brian Osman1298bc42020-06-30 13:39:35 -040010#include "include/private/SkSLSampleUsage.h"
Michael Ludwig8f3a8362020-06-29 17:27:00 -040011#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/SkSLCPPUniformCTypes.h"
13#include "src/sksl/SkSLCompiler.h"
14#include "src/sksl/SkSLHCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040015
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040016#include <algorithm>
17
Ethan Nicholasbc6fb272020-08-18 16:29:45 -040018#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
19
Ethan Nicholas762466e2017-06-29 10:03:38 -040020namespace SkSL {
21
22static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050023 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
24 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040025}
26
27CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
28 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040029 : INHERITED(context, program, errors, out)
30 , fName(std::move(name))
31 , fFullName(String::printf("Gr%s", fName.c_str()))
32 , fSectionAndParameterHelper(program, *errors) {
33 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040035}
36
37void CPPCodeGenerator::writef(const char* s, va_list va) {
38 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040039 va_list copy;
40 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040041 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040042 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040043 if (length < BUFFER_SIZE) {
44 fOut->write(buffer, length);
45 } else {
46 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040047 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040048 fOut->write(heap.get(), length);
49 }
z102.zhangd74f2c82018-08-10 09:08:47 +080050 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040051}
52
53void CPPCodeGenerator::writef(const char* s, ...) {
54 va_list va;
55 va_start(va, s);
56 this->writef(s, va);
57 va_end(va);
58}
59
60void CPPCodeGenerator::writeHeader() {
61}
62
Ethan Nicholasf7b88202017-09-18 14:10:39 -040063bool CPPCodeGenerator::usesPrecisionModifiers() const {
64 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040065}
66
Ethan Nicholasf7b88202017-09-18 14:10:39 -040067String CPPCodeGenerator::getTypeName(const Type& type) {
68 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040069}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040070
Ethan Nicholas762466e2017-06-29 10:03:38 -040071void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
72 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040073 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040074 // need to use "%%" instead of "%" b/c the code will be inside of a printf
75 Precedence precedence = GetBinaryPrecedence(b.fOperator);
76 if (precedence >= parentPrecedence) {
77 this->write("(");
78 }
79 this->writeExpression(*b.fLeft, precedence);
80 this->write(" %% ");
81 this->writeExpression(*b.fRight, precedence);
82 if (precedence >= parentPrecedence) {
83 this->write(")");
84 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050085 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
86 b.fRight->fKind == Expression::kNullLiteral_Kind) {
87 const Variable* var;
88 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
John Stiles17c5b702020-08-18 10:40:03 -040089 var = &b.fLeft->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050090 } else {
John Stiles17c5b702020-08-18 10:40:03 -040091 var = &b.fRight->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050092 }
93 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
94 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
95 this->write("%s");
Brian Osman12c5d292020-07-13 16:11:35 -040096 const char* op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050097 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040098 case Token::Kind::TK_EQEQ:
Brian Osman12c5d292020-07-13 16:11:35 -040099 op = "!";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500100 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400101 case Token::Kind::TK_NEQ:
Brian Osman12c5d292020-07-13 16:11:35 -0400102 op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500103 break;
104 default:
105 SkASSERT(false);
106 }
Brian Osman12c5d292020-07-13 16:11:35 -0400107 int childIndex = this->getChildFPIndex(*var);
108 fFormatArgs.push_back(String(op) + "_outer.childProcessor(" + to_string(childIndex) +
109 ") ? \"true\" : \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400110 } else {
111 INHERITED::writeBinaryExpression(b, parentPrecedence);
112 }
113}
114
115void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
116 const Expression& base = *i.fBase;
117 if (base.fKind == Expression::kVariableReference_Kind) {
118 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400119 if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400120 this->write("%s");
121 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700122 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400123 "index into sk_TextureSamplers must be an integer literal");
124 return;
125 }
John Stiles81365af2020-08-18 09:24:00 -0400126 int64_t index = i.fIndex->as<IntLiteral>().fValue;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400127 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400128 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400129 return;
130 }
131 }
132 INHERITED::writeIndexExpression(i);
133}
134
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400135static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500136 if (type.fName == "bool") {
137 return "false";
138 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400139 switch (type.kind()) {
140 case Type::kScalar_Kind: return "0";
141 case Type::kVector_Kind: return type.name() + "(0)";
142 case Type::kMatrix_Kind: return type.name() + "(1)";
143 default: ABORT("unsupported default_value type\n");
144 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400145}
146
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500147static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400148 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400149 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500150 }
151 return default_value(var.fType);
152}
153
Ethan Nicholas762466e2017-06-29 10:03:38 -0400154static bool is_private(const Variable& var) {
155 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
156 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
157 var.fStorage == Variable::kGlobal_Storage &&
158 var.fModifiers.fLayout.fBuiltin == -1;
159}
160
Michael Ludwiga4275592018-08-31 10:52:47 -0400161static bool is_uniform_in(const Variable& var) {
162 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
163 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
164 var.fType.kind() != Type::kSampler_Kind;
165}
166
John Stiles47b4e222020-08-12 09:56:50 -0400167String CPPCodeGenerator::formatRuntimeValue(const Type& type,
168 const Layout& layout,
169 const String& cppCode,
170 std::vector<String>* formatArgs) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400171 if (type.isFloat()) {
John Stiles47b4e222020-08-12 09:56:50 -0400172 formatArgs->push_back(cppCode);
173 return "%f";
174 }
175 if (type == *fContext.fInt_Type) {
176 formatArgs->push_back(cppCode);
177 return "%d";
178 }
179 if (type == *fContext.fBool_Type) {
180 formatArgs->push_back("(" + cppCode + " ? \"true\" : \"false\")");
181 return "%s";
182 }
183 if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
184 formatArgs->push_back(cppCode + ".fX");
185 formatArgs->push_back(cppCode + ".fY");
186 return type.name() + "(%f, %f)";
187 }
188 if (type == *fContext.fFloat3_Type || type == *fContext.fHalf3_Type) {
189 formatArgs->push_back(cppCode + ".fX");
190 formatArgs->push_back(cppCode + ".fY");
191 formatArgs->push_back(cppCode + ".fZ");
192 return type.name() + "(%f, %f, %f)";
193 }
194 if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400195 switch (layout.fCType) {
196 case Layout::CType::kSkPMColor:
John Stiles47b4e222020-08-12 09:56:50 -0400197 formatArgs->push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
198 formatArgs->push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
199 formatArgs->push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
200 formatArgs->push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400201 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400202 case Layout::CType::kSkPMColor4f:
John Stiles47b4e222020-08-12 09:56:50 -0400203 formatArgs->push_back(cppCode + ".fR");
204 formatArgs->push_back(cppCode + ".fG");
205 formatArgs->push_back(cppCode + ".fB");
206 formatArgs->push_back(cppCode + ".fA");
Brian Osmanf28e55d2018-10-03 16:35:54 -0400207 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500208 case Layout::CType::kSkV4:
John Stiles47b4e222020-08-12 09:56:50 -0400209 formatArgs->push_back(cppCode + ".x");
210 formatArgs->push_back(cppCode + ".y");
211 formatArgs->push_back(cppCode + ".z");
212 formatArgs->push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400213 break;
John Stiles47b4e222020-08-12 09:56:50 -0400214 case Layout::CType::kSkRect:
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400215 case Layout::CType::kDefault:
John Stiles47b4e222020-08-12 09:56:50 -0400216 formatArgs->push_back(cppCode + ".left()");
217 formatArgs->push_back(cppCode + ".top()");
218 formatArgs->push_back(cppCode + ".right()");
219 formatArgs->push_back(cppCode + ".bottom()");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400220 break;
221 default:
222 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400223 }
John Stiles47b4e222020-08-12 09:56:50 -0400224 return type.name() + "(%f, %f, %f, %f)";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400225 }
John Stiles47b4e222020-08-12 09:56:50 -0400226 if (type.kind() == Type::kMatrix_Kind) {
227 SkASSERT(type.componentType() == *fContext.fFloat_Type ||
228 type.componentType() == *fContext.fHalf_Type);
229
230 String format = type.name() + "(";
231 for (int c = 0; c < type.columns(); ++c) {
232 for (int r = 0; r < type.rows(); ++r) {
233 formatArgs->push_back(String::printf("%s.rc(%d, %d)", cppCode.c_str(), r, c));
234 format += "%f, ";
235 }
236 }
237
238 // Replace trailing ", " with ")".
239 format.pop_back();
240 format.back() = ')';
241 return format;
242 }
243 if (type.kind() == Type::kEnum_Kind) {
244 formatArgs->push_back("(int) " + cppCode);
245 return "%d";
246 }
247 if (type == *fContext.fInt4_Type ||
248 type == *fContext.fShort4_Type ||
249 type == *fContext.fByte4_Type) {
250 formatArgs->push_back(cppCode + ".left()");
251 formatArgs->push_back(cppCode + ".top()");
252 formatArgs->push_back(cppCode + ".right()");
253 formatArgs->push_back(cppCode + ".bottom()");
254 return type.name() + "(%d, %d, %d, %d)";
255 }
256
257 SkDEBUGFAILF("unsupported runtime value type '%s'\n", String(type.fName).c_str());
258 return "";
259}
260
261void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
262 const String& cppCode) {
263 this->write(this->formatRuntimeValue(type, layout, cppCode, &fFormatArgs));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400264}
265
266void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
267 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400268 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400269 } else {
270 this->writeExpression(value, kTopLevel_Precedence);
271 }
272}
273
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400274String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
275 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400276 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400277 if (&var == param) {
278 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
279 }
280 if (param->fType.kind() == Type::kSampler_Kind) {
281 ++samplerCount;
282 }
283 }
284 ABORT("should have found sampler in parameters\n");
285}
286
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400287void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
288 this->write(to_string((int32_t) i.fValue));
289}
290
Ethan Nicholas82399462017-10-16 12:35:44 -0400291void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
292 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400293 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400294 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
295 switch (swizzle.fComponents[0]) {
296 case 0: this->write(".left()"); break;
297 case 1: this->write(".top()"); break;
298 case 2: this->write(".right()"); break;
299 case 3: this->write(".bottom()"); break;
300 }
301 } else {
302 INHERITED::writeSwizzle(swizzle);
303 }
304}
305
Ethan Nicholas762466e2017-06-29 10:03:38 -0400306void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400307 if (fCPPMode) {
308 this->write(ref.fVariable.fName);
309 return;
310 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400311 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
312 case SK_INCOLOR_BUILTIN:
313 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400314 // EmitArgs.fInputColor is automatically set to half4(1) if
315 // no input was specified
316 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400317 break;
318 case SK_OUTCOLOR_BUILTIN:
319 this->write("%s");
320 fFormatArgs.push_back(String("args.fOutputColor"));
321 break;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400322 case SK_MAIN_COORDS_BUILTIN:
323 this->write("%s");
324 fFormatArgs.push_back(String("args.fSampleCoord"));
325 fAccessSampleCoordsDirectly = true;
326 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400327 case SK_WIDTH_BUILTIN:
328 this->write("sk_Width");
329 break;
330 case SK_HEIGHT_BUILTIN:
331 this->write("sk_Height");
332 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400333 default:
334 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400335 this->write("%s");
336 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400337 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400338 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400339 }
340 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
341 this->write("%s");
342 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400343 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
344 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400345 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400346 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400347 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
348 HCodeGenerator::FieldName(name.c_str()).c_str(),
349 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400350 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400351 } else {
352 code = var;
353 }
354 fFormatArgs.push_back(code);
355 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700356 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400357 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400358 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400359 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700360 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400361 }
362 }
363}
364
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400365void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
366 if (s.fIsStatic) {
367 this->write("@");
368 }
369 INHERITED::writeIfStatement(s);
370}
371
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400372void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
373 if (fInMain) {
374 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
375 }
376 INHERITED::writeReturnStatement(s);
377}
378
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400379void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
380 if (s.fIsStatic) {
381 this->write("@");
382 }
383 INHERITED::writeSwitchStatement(s);
384}
385
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
387 if (access.fBase->fType.name() == "fragmentProcessor") {
388 // Special field access on fragment processors are converted into function calls on
389 // GrFragmentProcessor's getters.
390 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
391 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
392 return;
393 }
394
395 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500396 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Brian Osman12c5d292020-07-13 16:11:35 -0400397 String cppAccess = String::printf("_outer.childProcessor(%d)->%s()",
398 this->getChildFPIndex(var),
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500399 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400400
401 if (fCPPMode) {
402 this->write(cppAccess.c_str());
403 } else {
404 writeRuntimeValue(*field.fType, Layout(), cppAccess);
405 }
406 return;
407 }
408 INHERITED::writeFieldAccess(access);
409}
410
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500411int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400412 int index = 0;
413 bool found = false;
414 for (const auto& p : fProgram) {
415 if (ProgramElement::kVar_Kind == p.fKind) {
416 const VarDeclarations& decls = (const VarDeclarations&) p;
417 for (const auto& raw : decls.fVars) {
418 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500419 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400420 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500421 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400422 ++index;
423 }
424 }
425 }
426 if (found) {
427 break;
428 }
429 }
430 SkASSERT(found);
431 return index;
432}
433
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400434void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400435 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
436 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Leon Scroggins III982fff22020-07-31 14:09:06 -0400437 // Validity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400438 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500439 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
440 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400441
442 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400443 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400444 // special function that impacts code emission.
445 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
446 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400447 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400448 return;
449 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500450 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400451
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400452 // Start a new extra emit code section so that the emitted child processor can depend on
453 // sksl variables defined in earlier sksl code.
454 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400455
Michael Ludwige88320b2020-06-24 09:04:56 -0400456 String inputColor;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400457 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400458 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400459 // argument's expression into C++ code that produces sksl stored in an SkString.
Brian Osman12c5d292020-07-13 16:11:35 -0400460 String inputColorName = "_input" + to_string(c.fOffset);
John Stilesd060c9d2020-06-08 11:44:25 -0400461 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400462
Michael Ludwige88320b2020-06-24 09:04:56 -0400463 // invokeChild() needs a char* and a pre-pended comma
464 inputColor = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400465 }
466
Michael Ludwige88320b2020-06-24 09:04:56 -0400467 String inputCoord;
468 String invokeFunction = "invokeChild";
469 if (c.fArguments.back()->fType.name() == "float2") {
470 // Invoking child with explicit coordinates at this call site
471 inputCoord = "_coords" + to_string(c.fOffset);
472 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
473 inputCoord.append(".c_str()");
474 } else if (c.fArguments.back()->fType.name() == "float3x3") {
475 // Invoking child with a matrix, sampling relative to the input coords.
476 invokeFunction = "invokeChildWithMatrix";
Brian Osman1298bc42020-06-30 13:39:35 -0400477 SampleUsage usage = Analysis::GetSampleUsage(fProgram, child);
Michael Ludwige88320b2020-06-24 09:04:56 -0400478
Brian Osman1298bc42020-06-30 13:39:35 -0400479 if (!usage.hasUniformMatrix()) {
Michael Ludwige88320b2020-06-24 09:04:56 -0400480 inputCoord = "_matrix" + to_string(c.fOffset);
481 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
482 inputCoord.append(".c_str()");
483 }
484 // else pass in the empty string to rely on invokeChildWithMatrix's automatic uniform
485 // resolution
486 }
487 if (!inputCoord.empty()) {
488 inputCoord = ", " + inputCoord;
489 }
490
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400491 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400492 String childName = "_sample" + to_string(c.fOffset);
Brian Osman12c5d292020-07-13 16:11:35 -0400493 String childIndexStr = to_string(this->getChildFPIndex(child));
494 addExtraEmitCodeLine("SkString " + childName + " = this->" + invokeFunction + "(" +
495 childIndexStr + inputColor + ", args" + inputCoord + ");");
John Stiles50819422020-06-18 13:00:38 -0400496
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000497 this->write("%s");
498 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400499 return;
500 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400501 if (c.fFunction.fBuiltin) {
502 INHERITED::writeFunctionCall(c);
503 } else {
504 this->write("%s");
505 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
506 this->write("(");
507 const char* separator = "";
508 for (const auto& arg : c.fArguments) {
509 this->write(separator);
510 separator = ", ";
511 this->writeExpression(*arg, kSequence_Precedence);
512 }
513 this->write(")");
514 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400515 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400516 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400517 SkASSERT(c.fArguments.size() >= 1);
518 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400519 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
520 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500521 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400522 }
523}
524
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400525static const char* glsltype_string(const Context& context, const Type& type) {
526 if (type == *context.fFloat_Type) {
527 return "kFloat_GrSLType";
528 } else if (type == *context.fHalf_Type) {
529 return "kHalf_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400530 } else if (type == *context.fInt_Type) {
531 return "kInt_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400532 } else if (type == *context.fFloat2_Type) {
533 return "kFloat2_GrSLType";
534 } else if (type == *context.fHalf2_Type) {
535 return "kHalf2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400536 } else if (type == *context.fInt2_Type) {
537 return "kInt2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500538 } else if (type == *context.fFloat3_Type) {
539 return "kFloat3_GrSLType";
540 } else if (type == *context.fHalf3_Type) {
541 return "kHalf3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400542 } else if (type == *context.fInt3_Type) {
543 return "kInt3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400544 } else if (type == *context.fFloat4_Type) {
545 return "kFloat4_GrSLType";
546 } else if (type == *context.fHalf4_Type) {
547 return "kHalf4_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400548 } else if (type == *context.fInt4_Type) {
549 return "kInt4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400550 } else if (type == *context.fFloat2x2_Type) {
551 return "kFloat2x2_GrSLType";
552 } else if (type == *context.fHalf2x2_Type) {
553 return "kHalf2x2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400554 } else if (type == *context.fFloat2x3_Type) {
555 return "kFloat2x3_GrSLType";
556 } else if (type == *context.fHalf2x3_Type) {
557 return "kHalf2x3_GrSLType";
558 } else if (type == *context.fFloat2x4_Type) {
559 return "kFloat2x4_GrSLType";
560 } else if (type == *context.fHalf2x4_Type) {
561 return "kHalf2x4_GrSLType";
562 } else if (type == *context.fFloat3x2_Type) {
563 return "kFloat3x2_GrSLType";
564 } else if (type == *context.fHalf3x2_Type) {
565 return "kHalf3x2_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400566 } else if (type == *context.fFloat3x3_Type) {
567 return "kFloat3x3_GrSLType";
568 } else if (type == *context.fHalf3x3_Type) {
569 return "kHalf3x3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400570 } else if (type == *context.fFloat3x4_Type) {
571 return "kFloat3x4_GrSLType";
572 } else if (type == *context.fHalf3x4_Type) {
573 return "kHalf3x4_GrSLType";
574 } else if (type == *context.fFloat4x2_Type) {
575 return "kFloat4x2_GrSLType";
576 } else if (type == *context.fHalf4x2_Type) {
577 return "kHalf4x2_GrSLType";
578 } else if (type == *context.fFloat4x3_Type) {
579 return "kFloat4x3_GrSLType";
580 } else if (type == *context.fHalf4x3_Type) {
581 return "kHalf4x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400582 } else if (type == *context.fFloat4x4_Type) {
583 return "kFloat4x4_GrSLType";
584 } else if (type == *context.fHalf4x4_Type) {
585 return "kHalf4x4_GrSLType";
586 } else if (type == *context.fVoid_Type) {
587 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500588 } else if (type.kind() == Type::kEnum_Kind) {
589 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400590 }
591 SkASSERT(false);
592 return nullptr;
593}
594
Ethan Nicholas762466e2017-06-29 10:03:38 -0400595void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400596 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400597 if (decl.fBuiltin) {
598 return;
599 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400600 fFunctionHeader = "";
601 OutputStream* oldOut = fOut;
602 StringStream buffer;
603 fOut = &buffer;
604 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400605 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400606 for (const auto& s : ((Block&) *f.fBody).fStatements) {
607 this->writeStatement(*s);
608 this->writeLine();
609 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400610 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400611
612 fOut = oldOut;
613 this->write(fFunctionHeader);
614 this->write(buffer.str());
615 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400616 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
617 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
618 const char* separator = "";
619 for (const auto& param : decl.fParameters) {
620 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
621 glsltype_string(fContext, param->fType) + ")";
622 separator = ", ";
623 }
624 args += "};";
625 this->addExtraEmitCodeLine(args.c_str());
626 for (const auto& s : ((Block&) *f.fBody).fStatements) {
627 this->writeStatement(*s);
628 this->writeLine();
629 }
630
631 fOut = oldOut;
632 String emit = "fragBuilder->emitFunction(";
633 emit += glsltype_string(fContext, decl.fReturnType);
634 emit += ", \"" + decl.fName + "\"";
635 emit += ", " + to_string((int64_t) decl.fParameters.size());
636 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400637 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400638 emit += ", &" + decl.fName + "_name);";
639 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400640 }
641}
642
643void CPPCodeGenerator::writeSetting(const Setting& s) {
Brian Osmanf265afd2020-08-04 13:23:36 -0400644 this->write(s.fName.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400645}
646
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400647bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400648 const Section* s = fSectionAndParameterHelper.getSection(name);
649 if (s) {
650 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400651 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400652 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400653 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400654}
655
656void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
657 if (p.fKind == ProgramElement::kSection_Kind) {
658 return;
659 }
660 if (p.fKind == ProgramElement::kVar_Kind) {
661 const VarDeclarations& decls = (const VarDeclarations&) p;
662 if (!decls.fVars.size()) {
663 return;
664 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000665 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400666 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
667 -1 != var.fModifiers.fLayout.fBuiltin) {
668 return;
669 }
670 }
671 INHERITED::writeProgramElement(p);
672}
673
674void CPPCodeGenerator::addUniform(const Variable& var) {
675 if (!needs_uniform_var(var)) {
676 return;
677 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400678 if (var.fModifiers.fLayout.fWhen.fLength) {
679 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400680 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400681 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700682 String name(var.fName);
Ethan Nicholas16464c32020-04-06 13:53:05 -0400683 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
684 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700685 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400686 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400687 this->write(" }\n");
688 }
689}
690
Ethan Nicholascd700e92018-08-24 16:43:57 -0400691void CPPCodeGenerator::writeInputVars() {
692}
693
Ethan Nicholas762466e2017-06-29 10:03:38 -0400694void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400695 for (const auto& p : fProgram) {
696 if (ProgramElement::kVar_Kind == p.fKind) {
697 const VarDeclarations& decls = (const VarDeclarations&) p;
698 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000699 VarDeclaration& decl = (VarDeclaration&) *raw;
700 if (is_private(*decl.fVar)) {
701 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
702 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400703 "fragmentProcessor variables must be declared 'in'");
704 return;
705 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500706 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000707 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
708 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500709 String(decl.fVar->fName).c_str(),
710 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400711 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
712 // An auto-tracked uniform in variable, so add a field to hold onto the prior
713 // state. Note that tracked variables must be uniform in's and that is validated
714 // before writePrivateVars() is called.
715 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
716 SkASSERT(mapper && mapper->supportsTracking());
717
718 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
719 // The member statement is different if the mapper reports a default value
720 if (mapper->defaultValue().size() > 0) {
721 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400722 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400723 mapper->defaultValue().c_str());
724 } else {
725 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400726 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400727 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400728 }
729 }
730 }
731 }
732}
733
734void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400735 for (const auto& p : fProgram) {
736 if (ProgramElement::kVar_Kind == p.fKind) {
737 const VarDeclarations& decls = (const VarDeclarations&) p;
738 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000739 VarDeclaration& decl = (VarDeclaration&) *raw;
740 if (is_private(*decl.fVar) && decl.fValue) {
741 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400742 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000743 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400744 fCPPMode = false;
745 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400746 }
747 }
748 }
749 }
750}
751
Ethan Nicholas82399462017-10-16 12:35:44 -0400752static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500753 const Type& type = var.fType.nonnullable();
754 return Type::kSampler_Kind != type.kind() &&
755 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400756}
757
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400758void CPPCodeGenerator::newExtraEmitCodeBlock() {
759 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
760 // cpp buffer is not null, and the cpp buffer is not the current output.
761 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
762
763 // Start a new block as an empty string
764 fExtraEmitCodeBlocks.push_back("");
765 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
766 // valid sksl and makes detection trivial.
767 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
768}
769
770void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
771 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
772 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
773 // Automatically add indentation and newline
774 currentBlock += " " + toAppend + "\n";
775}
776
777void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400778 if (fCPPBuffer == nullptr) {
779 // Not actually within writeEmitCode() so nothing to flush
780 return;
781 }
782
783 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
784
785 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400786 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400787 skslBuffer->reset();
788
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400789 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000790 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400791
792 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
793 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
794 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
795 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
796 // statement left off (minus the encountered token).
797 size_t i = 0;
798 int flushPoint = -1;
799 int tokenStart = -1;
800 while (i < sksl.size()) {
801 if (tokenStart >= 0) {
802 // Looking for the end of the token
803 if (sksl[i] == '}') {
804 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
805 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
806 String toFlush = String(sksl.c_str(), flushPoint + 1);
807 // writeCodeAppend automatically removes the format args that it consumed, so
808 // fFormatArgs will be in a valid state for any future sksl
809 this->writeCodeAppend(toFlush);
810
811 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
812 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
813 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
814 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
815 }
816
817 // Now reset the sksl buffer to start after the flush point, but remove the token.
818 String compacted = String(sksl.c_str() + flushPoint + 1,
819 tokenStart - flushPoint - 1);
820 if (i < sksl.size() - 1) {
821 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
822 }
823 sksl = compacted;
824
825 // And reset iteration
826 i = -1;
827 flushPoint = -1;
828 tokenStart = -1;
829 }
830 } else {
831 // Looking for the start of extra emit block tokens, and tracking when statements end
832 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
833 flushPoint = i;
834 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
835 // found an extra emit code block token
836 tokenStart = i++;
837 }
838 }
839 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000840 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400841
842 // Once we've gone through the sksl string to this point, there are no remaining extra emit
843 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400844 this->writeCodeAppend(sksl);
845
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400846 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400847 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400848 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400849}
850
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400851void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400852 if (!code.empty()) {
853 // Count % format specifiers.
854 size_t argCount = 0;
855 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400856 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400857 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400858 break;
859 }
860 if (code[index + 1] != '%') {
861 ++argCount;
862 }
863 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400864 }
John Stiles50819422020-06-18 13:00:38 -0400865
866 // Emit the code string.
867 this->writef(" fragBuilder->codeAppendf(\n"
868 "R\"SkSL(%s)SkSL\"\n", code.c_str());
869 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400870 this->writef(", %s", fFormatArgs[i].c_str());
871 }
872 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400873
John Stiles50819422020-06-18 13:00:38 -0400874 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
875 // removed from the list.
876 if (argCount > 0) {
877 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
878 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400879 }
880}
881
882String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
883 const String& cppVar) {
884 // To do this conversion, we temporarily switch the sksl output stream
885 // to an empty stringstream and reset the format args to empty.
886 OutputStream* oldSKSL = fOut;
887 StringStream exprBuffer;
888 fOut = &exprBuffer;
889
890 std::vector<String> oldArgs(fFormatArgs);
891 fFormatArgs.clear();
892
893 // Convert the argument expression into a format string and args
894 this->writeExpression(e, Precedence::kTopLevel_Precedence);
895 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400896 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400897
898 // After generating, restore the original output stream and format args
899 fFormatArgs = oldArgs;
900 fOut = oldSKSL;
901
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400902 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
903 // block tokens won't get handled. So we need to strip them from the expression and stick them
904 // to the end of the original sksl stream.
905 String exprFormat = "";
906 int tokenStart = -1;
907 for (size_t i = 0; i < expr.size(); i++) {
908 if (tokenStart >= 0) {
909 if (expr[i] == '}') {
910 // End of the token, so append the token to fOut
911 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
912 tokenStart = -1;
913 }
914 } else {
915 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
916 tokenStart = i++;
917 } else {
918 exprFormat += expr[i];
919 }
920 }
921 }
922
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400923 // Now build the final C++ code snippet from the format string and args
924 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400925 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400926 // This was a static expression, so we can simplify the input
927 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400928 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400929 } else if (newArgs.size() == 1 && exprFormat == "%s") {
930 // If the format expression is simply "%s", we can avoid an expensive call to printf.
931 // This happens fairly often in codegen so it is worth simplifying.
932 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400933 } else {
934 // String formatting must occur dynamically, so have the C++ declaration
935 // use SkStringPrintf with the format args that were accumulated
936 // when the expression was written.
937 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
938 for (size_t i = 0; i < newArgs.size(); i++) {
939 cppExpr += ", " + newArgs[i];
940 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400941 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400942 }
943 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400944}
945
Ethan Nicholas762466e2017-06-29 10:03:38 -0400946bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
947 this->write(" void emitCode(EmitArgs& args) override {\n"
948 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
949 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
950 " (void) _outer;\n",
951 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400952 for (const auto& p : fProgram) {
953 if (ProgramElement::kVar_Kind == p.fKind) {
954 const VarDeclarations& decls = (const VarDeclarations&) p;
955 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000956 VarDeclaration& decl = (VarDeclaration&) *raw;
957 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400958 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000959 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
960 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400961 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400962 " (void) %s;\n",
963 name, name, name);
964 }
965 }
966 }
967 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400968 this->writePrivateVarValues();
969 for (const auto u : uniforms) {
970 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400971 }
John Stiles02b11282020-08-10 15:25:24 -0400972 this->writeSection(kEmitCodeSection);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400973
974 // Save original buffer as the CPP buffer for flushEmittedCode()
975 fCPPBuffer = fOut;
976 StringStream skslBuffer;
977 fOut = &skslBuffer;
978
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400979 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400980 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400981 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400982
983 // Then restore the original CPP buffer and close the function
984 fOut = fCPPBuffer;
985 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400986 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400987 return result;
988}
989
990void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
991 const char* fullName = fFullName.c_str();
John Stiles02b11282020-08-10 15:25:24 -0400992 const Section* section = fSectionAndParameterHelper.getSection(kSetDataSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -0400993 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400994 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
995 "const GrFragmentProcessor& _proc) override {\n",
996 pdman);
997 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400998 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400999 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001000 if (!wroteProcessor) {
1001 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
1002 wroteProcessor = true;
1003 this->writef(" {\n");
1004 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001005
1006 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
1007 SkASSERT(mapper);
1008
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001009 String nameString(u->fName);
1010 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -04001011
1012 // Switches for setData behavior in the generated code
1013 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
1014 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
1015 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
1016
1017 String uniformName = HCodeGenerator::FieldName(name) + "Var";
1018
1019 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
1020 if (conditionalUniform) {
1021 // Add a pre-check to make sure the uniform was emitted
1022 // before trying to send any data to the GPU
1023 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
1024 indent += " ";
1025 }
1026
1027 String valueVar = "";
1028 if (needsValueDeclaration) {
1029 valueVar.appendf("%sValue", name);
1030 // Use AccessType since that will match the return type of _outer's public API.
1031 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1032 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001033 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001034 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001035 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001036 // Not tracked and the mapper only needs to use the value once
1037 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001038 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001039 }
1040
1041 if (isTracked) {
1042 SkASSERT(mapper->supportsTracking());
1043
1044 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1045 this->writef("%sif (%s) {\n"
1046 "%s %s;\n"
1047 "%s %s;\n"
1048 "%s}\n", indent.c_str(),
1049 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1050 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1051 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1052 } else {
1053 this->writef("%s%s;\n", indent.c_str(),
1054 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1055 }
1056
1057 if (conditionalUniform) {
1058 // Close the earlier precheck block
1059 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001060 }
1061 }
1062 }
1063 if (wroteProcessor) {
1064 this->writef(" }\n");
1065 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001066 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001067 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001068 for (const auto& p : fProgram) {
1069 if (ProgramElement::kVar_Kind == p.fKind) {
1070 const VarDeclarations& decls = (const VarDeclarations&) p;
John Stiles06f3d082020-06-04 11:07:21 -04001071 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
1072 const VarDeclaration& decl = static_cast<VarDeclaration&>(*raw);
1073 const Variable& variable = *decl.fVar;
1074 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001075 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001076 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001077 this->writef(" const GrSurfaceProxyView& %sView = "
1078 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001079 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001080 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001081 name, name);
1082 this->writef(" (void) %s;\n", name);
1083 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001084 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001085 this->writef(" UniformHandle& %s = %sVar;\n"
1086 " (void) %s;\n",
1087 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001088 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1089 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001090 if (!wroteProcessor) {
1091 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1092 fullName);
1093 wroteProcessor = true;
1094 }
John Stiles06f3d082020-06-04 11:07:21 -04001095
1096 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1097 this->writef(" auto %s = _outer.%s;\n"
1098 " (void) %s;\n",
1099 name, name, name);
1100 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001101 }
1102 }
1103 }
1104 }
John Stiles02b11282020-08-10 15:25:24 -04001105 this->writeSection(kSetDataSection);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001106 }
1107 this->write(" }\n");
1108}
1109
Brian Salomonf7dcd762018-07-30 14:48:15 -04001110void CPPCodeGenerator::writeOnTextureSampler() {
1111 bool foundSampler = false;
1112 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1113 if (param->fType.kind() == Type::kSampler_Kind) {
1114 if (!foundSampler) {
1115 this->writef(
1116 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1117 "index) const {\n",
1118 fFullName.c_str());
1119 this->writef(" return IthTextureSampler(index, %s",
1120 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1121 foundSampler = true;
1122 } else {
1123 this->writef(", %s",
1124 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1125 }
1126 }
1127 }
1128 if (foundSampler) {
1129 this->write(");\n}\n");
1130 }
1131}
1132
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001133void CPPCodeGenerator::writeClone() {
John Stiles02b11282020-08-10 15:25:24 -04001134 if (!this->writeSection(kCloneSection)) {
1135 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
John Stiles47b4e222020-08-12 09:56:50 -04001136 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1137 "custom @clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001138 }
1139 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001140 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1141 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
John Stiles06f3d082020-06-04 11:07:21 -04001142 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001143 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001144 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001145 this->writef("\n, %s(src.%s)",
1146 fieldName.c_str(),
1147 fieldName.c_str());
1148 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001149 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001150 this->writef(" {\n");
Brian Osman12c5d292020-07-13 16:11:35 -04001151 this->writef(" this->cloneAndRegisterAllChildProcessors(src);\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001152 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001153 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1154 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001155 ++samplerCount;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001156 }
1157 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001158 if (samplerCount) {
1159 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1160 }
Michael Ludwige88320b2020-06-24 09:04:56 -04001161 if (fAccessSampleCoordsDirectly) {
1162 this->writef(" this->setUsesSampleCoordsDirectly();\n");
1163 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001164 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001165 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1166 fFullName.c_str());
John Stilesfbd050b2020-08-03 13:21:46 -04001167 this->writef(" return std::make_unique<%s>(*this);\n",
Brian Salomonaff329b2017-08-11 09:40:37 -04001168 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001169 this->write("}\n");
1170 }
1171}
1172
John Stiles47b4e222020-08-12 09:56:50 -04001173void CPPCodeGenerator::writeDumpInfo() {
John Stiles8d9bf642020-08-12 15:07:45 -04001174 this->writef("#if GR_TEST_UTILS\n"
John Stilescab58862020-08-12 15:47:06 -04001175 "SkString %s::onDumpInfo() const {\n", fFullName.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001176
1177 if (!this->writeSection(kDumpInfoSection)) {
1178 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
1179 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1180 "custom @dumpInfo");
1181 }
1182
John Stiles47b4e222020-08-12 09:56:50 -04001183 String formatString;
1184 std::vector<String> argumentList;
1185
1186 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
1187 // dumpInfo() doesn't need to log child FPs.
1188 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1189 continue;
1190 }
1191
1192 // Add this field onto the format string and argument list.
1193 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1194 String runtimeValue = this->formatRuntimeValue(param->fType, param->fModifiers.fLayout,
1195 param->fName, &argumentList);
1196 formatString.appendf("%s%s=%s",
1197 formatString.empty() ? "" : ", ",
1198 fieldName.c_str(),
1199 runtimeValue.c_str());
1200 }
1201
John Stiles47b4e222020-08-12 09:56:50 -04001202 if (!formatString.empty()) {
John Stilescab58862020-08-12 15:47:06 -04001203 // Emit the finished format string and associated arguments.
1204 this->writef(" return SkStringPrintf(\"(%s)\"", formatString.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001205
John Stilescab58862020-08-12 15:47:06 -04001206 for (const String& argument : argumentList) {
1207 this->writef(", %s", argument.c_str());
1208 }
John Stiles47b4e222020-08-12 09:56:50 -04001209
John Stilescab58862020-08-12 15:47:06 -04001210 this->write(");");
1211 } else {
1212 // No fields to dump at all; just return an empty string.
1213 this->write(" return SkString();");
1214 }
John Stiles47b4e222020-08-12 09:56:50 -04001215 }
1216
John Stilescab58862020-08-12 15:47:06 -04001217 this->write("\n"
1218 "}\n"
John Stiles47b4e222020-08-12 09:56:50 -04001219 "#endif\n");
1220}
1221
Ethan Nicholas762466e2017-06-29 10:03:38 -04001222void CPPCodeGenerator::writeTest() {
John Stiles02b11282020-08-10 15:25:24 -04001223 const Section* test = fSectionAndParameterHelper.getSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001224 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001225 this->writef(
1226 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1227 "#if GR_TEST_UTILS\n"
1228 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1229 fFullName.c_str(),
1230 fFullName.c_str(),
1231 test->fArgument.c_str());
John Stiles02b11282020-08-10 15:25:24 -04001232 this->writeSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001233 this->write("}\n"
1234 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001235 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001236}
1237
1238void CPPCodeGenerator::writeGetKey() {
1239 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1240 "GrProcessorKeyBuilder* b) const {\n",
1241 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001242 for (const auto& p : fProgram) {
1243 if (ProgramElement::kVar_Kind == p.fKind) {
1244 const VarDeclarations& decls = (const VarDeclarations&) p;
1245 for (const auto& raw : decls.fVars) {
1246 const VarDeclaration& decl = (VarDeclaration&) *raw;
1247 const Variable& var = *decl.fVar;
1248 String nameString(var.fName);
1249 const char* name = nameString.c_str();
1250 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1251 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1252 fErrors.error(var.fOffset,
1253 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001254 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001255 switch (var.fModifiers.fLayout.fKey) {
1256 case Layout::kKey_Key:
1257 if (is_private(var)) {
1258 this->writef("%s %s =",
1259 HCodeGenerator::FieldType(fContext, var.fType,
1260 var.fModifiers.fLayout).c_str(),
1261 String(var.fName).c_str());
1262 if (decl.fValue) {
1263 fCPPMode = true;
1264 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1265 fCPPMode = false;
1266 } else {
1267 this->writef("%s", default_value(var).c_str());
1268 }
1269 this->write(";\n");
1270 }
1271 if (var.fModifiers.fLayout.fWhen.fLength) {
1272 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1273 }
John Stilesb3038f82020-07-27 17:33:25 -04001274 if (var.fType == *fContext.fHalf4_Type) {
Ethan Nicholascab767f2019-07-01 13:32:07 -04001275 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1276 HCodeGenerator::FieldName(name).c_str());
1277 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1278 HCodeGenerator::FieldName(name).c_str());
1279 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1280 HCodeGenerator::FieldName(name).c_str());
1281 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1282 HCodeGenerator::FieldName(name).c_str());
1283 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1284 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
John Stiles45f5b032020-07-27 17:31:29 -04001285 } else if (var.fType == *fContext.fHalf_Type ||
1286 var.fType == *fContext.fFloat_Type) {
1287 this->writef(" b->add32(sk_bit_cast<uint32_t>(%s));\n",
Ethan Nicholascab767f2019-07-01 13:32:07 -04001288 HCodeGenerator::FieldName(name).c_str());
John Stiles45f5b032020-07-27 17:31:29 -04001289 } else if (var.fType.isInteger() || var.fType == *fContext.fBool_Type ||
1290 var.fType.kind() == Type::kEnum_Kind) {
1291 this->writef(" b->add32((uint32_t) %s);\n",
1292 HCodeGenerator::FieldName(name).c_str());
1293 } else {
1294 ABORT("NOT YET IMPLEMENTED: automatic key handling for %s\n",
1295 var.fType.displayName().c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001296 }
1297 if (var.fModifiers.fLayout.fWhen.fLength) {
1298 this->write("}");
1299 }
1300 break;
1301 case Layout::kIdentity_Key:
1302 if (var.fType.kind() != Type::kMatrix_Kind) {
1303 fErrors.error(var.fOffset,
1304 "layout(key=identity) requires matrix type");
1305 }
1306 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1307 HCodeGenerator::FieldName(name).c_str());
1308 break;
1309 case Layout::kNo_Key:
1310 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001311 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001312 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001313 }
1314 }
1315 this->write("}\n");
1316}
1317
1318bool CPPCodeGenerator::generateCode() {
1319 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001320 for (const auto& p : fProgram) {
1321 if (ProgramElement::kVar_Kind == p.fKind) {
1322 const VarDeclarations& decls = (const VarDeclarations&) p;
1323 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001324 VarDeclaration& decl = (VarDeclaration&) *raw;
1325 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1326 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1327 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001328 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001329
1330 if (is_uniform_in(*decl.fVar)) {
1331 // Validate the "uniform in" declarations to make sure they are fully supported,
1332 // instead of generating surprising C++
1333 const UniformCTypeMapper* mapper =
1334 UniformCTypeMapper::Get(fContext, *decl.fVar);
1335 if (mapper == nullptr) {
1336 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1337 + "'s type is not supported for use as a 'uniform in'");
1338 return false;
1339 }
1340 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1341 if (!mapper->supportsTracking()) {
1342 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1343 + "'s type does not support state tracking");
1344 return false;
1345 }
1346 }
1347
1348 } else {
1349 // If it's not a uniform_in, it's an error to be tracked
1350 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1351 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1352 return false;
1353 }
1354 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001355 }
1356 }
1357 }
1358 const char* baseName = fName.c_str();
1359 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001360 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001361 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001362 this->writef("#include \"%s.h\"\n\n", fullName);
John Stiles02b11282020-08-10 15:25:24 -04001363 this->writeSection(kCppSection);
John Stiles45f5b032020-07-27 17:31:29 -04001364 this->writef("#include \"src/core/SkUtils.h\"\n"
1365 "#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001366 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1367 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1368 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1369 "#include \"src/sksl/SkSLCPP.h\"\n"
1370 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001371 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1372 "public:\n"
1373 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001374 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001375 bool result = this->writeEmitCode(uniforms);
1376 this->write("private:\n");
1377 this->writeSetData(uniforms);
1378 this->writePrivateVars();
1379 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001380 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001381 this->writef(" UniformHandle %sVar;\n",
1382 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001383 }
1384 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001385 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001386 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001387 this->writef(" UniformHandle %sVar;\n",
1388 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001389 }
1390 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001391 this->writef("};\n"
1392 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1393 " return new GrGLSL%s();\n"
1394 "}\n",
1395 fullName, baseName);
1396 this->writeGetKey();
1397 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1398 " const %s& that = other.cast<%s>();\n"
1399 " (void) that;\n",
1400 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001401 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001402 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001403 continue;
1404 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001405 String nameString(param->fName);
1406 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001407 this->writef(" if (%s != that.%s) return false;\n",
1408 HCodeGenerator::FieldName(name).c_str(),
1409 HCodeGenerator::FieldName(name).c_str());
1410 }
1411 this->write(" return true;\n"
1412 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001413 this->writeClone();
John Stiles47b4e222020-08-12 09:56:50 -04001414 this->writeDumpInfo();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001415 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001416 this->writeTest();
John Stiles02b11282020-08-10 15:25:24 -04001417 this->writeSection(kCppEndSection);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001418
Ethan Nicholas762466e2017-06-29 10:03:38 -04001419 result &= 0 == fErrors.errorCount();
1420 return result;
1421}
1422
John Stilesa6841be2020-08-06 14:11:56 -04001423} // namespace SkSL
Ethan Nicholasbc6fb272020-08-18 16:29:45 -04001424
1425#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)