blob: e1ea72c0355cd55184194c870fdfc9d64ef63386 [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 Osman061a5cf2020-06-24 14:50:25 -040010#include "include/private/SkSLSampleMatrix.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 Nicholas762466e2017-06-29 10:03:38 -040018namespace SkSL {
19
20static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050021 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
22 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040023}
24
25CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
26 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040027 : INHERITED(context, program, errors, out)
28 , fName(std::move(name))
29 , fFullName(String::printf("Gr%s", fName.c_str()))
30 , fSectionAndParameterHelper(program, *errors) {
31 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040032 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040033}
34
35void CPPCodeGenerator::writef(const char* s, va_list va) {
36 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040037 va_list copy;
38 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040039 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040040 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040041 if (length < BUFFER_SIZE) {
42 fOut->write(buffer, length);
43 } else {
44 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040045 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040046 fOut->write(heap.get(), length);
47 }
z102.zhangd74f2c82018-08-10 09:08:47 +080048 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040049}
50
51void CPPCodeGenerator::writef(const char* s, ...) {
52 va_list va;
53 va_start(va, s);
54 this->writef(s, va);
55 va_end(va);
56}
57
58void CPPCodeGenerator::writeHeader() {
59}
60
Ethan Nicholasf7b88202017-09-18 14:10:39 -040061bool CPPCodeGenerator::usesPrecisionModifiers() const {
62 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040063}
64
Ethan Nicholasf7b88202017-09-18 14:10:39 -040065String CPPCodeGenerator::getTypeName(const Type& type) {
66 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040067}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040068
Ethan Nicholas762466e2017-06-29 10:03:38 -040069void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
70 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040071 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040072 // need to use "%%" instead of "%" b/c the code will be inside of a printf
73 Precedence precedence = GetBinaryPrecedence(b.fOperator);
74 if (precedence >= parentPrecedence) {
75 this->write("(");
76 }
77 this->writeExpression(*b.fLeft, precedence);
78 this->write(" %% ");
79 this->writeExpression(*b.fRight, precedence);
80 if (precedence >= parentPrecedence) {
81 this->write(")");
82 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050083 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
84 b.fRight->fKind == Expression::kNullLiteral_Kind) {
85 const Variable* var;
86 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
87 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
88 var = &((VariableReference&) *b.fLeft).fVariable;
89 } else {
90 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
91 var = &((VariableReference&) *b.fRight).fVariable;
92 }
93 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
94 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
95 this->write("%s");
96 const char* op;
97 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040098 case Token::Kind::TK_EQEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050099 op = "<";
100 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400101 case Token::Kind::TK_NEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500102 op = ">=";
103 break;
104 default:
105 SkASSERT(false);
106 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400107 fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500108 ": \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400109 } else {
110 INHERITED::writeBinaryExpression(b, parentPrecedence);
111 }
112}
113
114void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
115 const Expression& base = *i.fBase;
116 if (base.fKind == Expression::kVariableReference_Kind) {
117 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
118 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
119 this->write("%s");
120 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700121 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400122 "index into sk_TransformedCoords2D must be an integer literal");
123 return;
124 }
125 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
Michael Ludwig9aba6252020-06-22 14:46:36 -0400126 if (index != 0) {
127 fErrors.error(i.fIndex->fOffset, "Only sk_TransformedCoords2D[0] is allowed");
128 return;
129 }
Michael Ludwige88320b2020-06-24 09:04:56 -0400130 fAccessSampleCoordsDirectly = true;
131 fFormatArgs.push_back("args.fSampleCoord");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400132 return;
133 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
134 this->write("%s");
135 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700136 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400137 "index into sk_TextureSamplers must be an integer literal");
138 return;
139 }
140 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
141 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400142 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400143 return;
144 }
145 }
146 INHERITED::writeIndexExpression(i);
147}
148
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400149static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500150 if (type.fName == "bool") {
151 return "false";
152 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400153 switch (type.kind()) {
154 case Type::kScalar_Kind: return "0";
155 case Type::kVector_Kind: return type.name() + "(0)";
156 case Type::kMatrix_Kind: return type.name() + "(1)";
157 default: ABORT("unsupported default_value type\n");
158 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400159}
160
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500161static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400162 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400163 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500164 }
165 return default_value(var.fType);
166}
167
Ethan Nicholas762466e2017-06-29 10:03:38 -0400168static bool is_private(const Variable& var) {
169 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
170 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
171 var.fStorage == Variable::kGlobal_Storage &&
172 var.fModifiers.fLayout.fBuiltin == -1;
173}
174
Michael Ludwiga4275592018-08-31 10:52:47 -0400175static bool is_uniform_in(const Variable& var) {
176 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
177 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
178 var.fType.kind() != Type::kSampler_Kind;
179}
180
Ethan Nicholasd608c092017-10-26 09:30:08 -0400181void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
182 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400183 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400184 this->write("%f");
185 fFormatArgs.push_back(cppCode);
186 } else if (type == *fContext.fInt_Type) {
187 this->write("%d");
188 fFormatArgs.push_back(cppCode);
189 } else if (type == *fContext.fBool_Type) {
190 this->write("%s");
191 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400192 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
193 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400194 fFormatArgs.push_back(cppCode + ".fX");
195 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400196 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
197 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400198 switch (layout.fCType) {
199 case Layout::CType::kSkPMColor:
200 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
201 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
202 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
203 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
204 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400205 case Layout::CType::kSkPMColor4f:
206 fFormatArgs.push_back(cppCode + ".fR");
207 fFormatArgs.push_back(cppCode + ".fG");
208 fFormatArgs.push_back(cppCode + ".fB");
209 fFormatArgs.push_back(cppCode + ".fA");
210 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500211 case Layout::CType::kSkV4:
212 fFormatArgs.push_back(cppCode + ".x");
213 fFormatArgs.push_back(cppCode + ".y");
214 fFormatArgs.push_back(cppCode + ".z");
215 fFormatArgs.push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400216 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400217 case Layout::CType::kSkRect: // fall through
218 case Layout::CType::kDefault:
219 fFormatArgs.push_back(cppCode + ".left()");
220 fFormatArgs.push_back(cppCode + ".top()");
221 fFormatArgs.push_back(cppCode + ".right()");
222 fFormatArgs.push_back(cppCode + ".bottom()");
223 break;
224 default:
225 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400226 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500227 } else if (type.kind() == Type::kEnum_Kind) {
228 this->write("%d");
229 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400230 } else if (type == *fContext.fInt4_Type ||
231 type == *fContext.fShort4_Type ||
232 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500233 this->write(type.name() + "(%d, %d, %d, %d)");
234 fFormatArgs.push_back(cppCode + ".left()");
235 fFormatArgs.push_back(cppCode + ".top()");
236 fFormatArgs.push_back(cppCode + ".right()");
237 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400238 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400239 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400240 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400241 }
242}
243
244void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
245 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400246 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400247 } else {
248 this->writeExpression(value, kTopLevel_Precedence);
249 }
250}
251
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400252String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
253 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400254 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400255 if (&var == param) {
256 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
257 }
258 if (param->fType.kind() == Type::kSampler_Kind) {
259 ++samplerCount;
260 }
261 }
262 ABORT("should have found sampler in parameters\n");
263}
264
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400265void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
266 this->write(to_string((int32_t) i.fValue));
267}
268
Ethan Nicholas82399462017-10-16 12:35:44 -0400269void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
270 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400271 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400272 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
273 switch (swizzle.fComponents[0]) {
274 case 0: this->write(".left()"); break;
275 case 1: this->write(".top()"); break;
276 case 2: this->write(".right()"); break;
277 case 3: this->write(".bottom()"); break;
278 }
279 } else {
280 INHERITED::writeSwizzle(swizzle);
281 }
282}
283
Ethan Nicholas762466e2017-06-29 10:03:38 -0400284void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400285 if (fCPPMode) {
286 this->write(ref.fVariable.fName);
287 return;
288 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400289 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
290 case SK_INCOLOR_BUILTIN:
291 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400292 // EmitArgs.fInputColor is automatically set to half4(1) if
293 // no input was specified
294 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400295 break;
296 case SK_OUTCOLOR_BUILTIN:
297 this->write("%s");
298 fFormatArgs.push_back(String("args.fOutputColor"));
299 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400300 case SK_WIDTH_BUILTIN:
301 this->write("sk_Width");
302 break;
303 case SK_HEIGHT_BUILTIN:
304 this->write("sk_Height");
305 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400306 default:
307 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400308 this->write("%s");
309 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400310 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400311 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400312 }
313 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
314 this->write("%s");
315 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400316 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
317 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400318 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400319 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400320 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
321 HCodeGenerator::FieldName(name.c_str()).c_str(),
322 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400323 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400324 } else {
325 code = var;
326 }
327 fFormatArgs.push_back(code);
328 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700329 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400330 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400331 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400332 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700333 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400334 }
335 }
336}
337
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400338void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
339 if (s.fIsStatic) {
340 this->write("@");
341 }
342 INHERITED::writeIfStatement(s);
343}
344
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400345void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
346 if (fInMain) {
347 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
348 }
349 INHERITED::writeReturnStatement(s);
350}
351
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400352void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
353 if (s.fIsStatic) {
354 this->write("@");
355 }
356 INHERITED::writeSwitchStatement(s);
357}
358
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400359void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
360 if (access.fBase->fType.name() == "fragmentProcessor") {
361 // Special field access on fragment processors are converted into function calls on
362 // GrFragmentProcessor's getters.
363 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
364 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
365 return;
366 }
367
368 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500369 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400370 String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500371 String(var.fName).c_str(),
372 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400373
374 if (fCPPMode) {
375 this->write(cppAccess.c_str());
376 } else {
377 writeRuntimeValue(*field.fType, Layout(), cppAccess);
378 }
379 return;
380 }
381 INHERITED::writeFieldAccess(access);
382}
383
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500384int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400385 int index = 0;
386 bool found = false;
387 for (const auto& p : fProgram) {
388 if (ProgramElement::kVar_Kind == p.fKind) {
389 const VarDeclarations& decls = (const VarDeclarations&) p;
390 for (const auto& raw : decls.fVars) {
391 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500392 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400393 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500394 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400395 ++index;
396 }
397 }
398 }
399 if (found) {
400 break;
401 }
402 }
403 SkASSERT(found);
404 return index;
405}
406
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400407void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400408 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
409 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400410 // Sanity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400411 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500412 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
413 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400414
415 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400416 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400417 // special function that impacts code emission.
418 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
419 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400420 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400421 return;
422 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500423 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400424
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400425 // Start a new extra emit code section so that the emitted child processor can depend on
426 // sksl variables defined in earlier sksl code.
427 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400428
Michael Ludwige88320b2020-06-24 09:04:56 -0400429 String inputColorName; // the sksl variable/expression, referenced later for null child FPs
430 String inputColor;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400431 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400432 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400433 // argument's expression into C++ code that produces sksl stored in an SkString.
John Stilesd060c9d2020-06-08 11:44:25 -0400434 inputColorName = "_input" + to_string(c.fOffset);
435 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400436
Michael Ludwige88320b2020-06-24 09:04:56 -0400437 // invokeChild() needs a char* and a pre-pended comma
438 inputColor = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400439 }
440
Michael Ludwige88320b2020-06-24 09:04:56 -0400441 String inputCoord;
442 String invokeFunction = "invokeChild";
443 if (c.fArguments.back()->fType.name() == "float2") {
444 // Invoking child with explicit coordinates at this call site
445 inputCoord = "_coords" + to_string(c.fOffset);
446 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
447 inputCoord.append(".c_str()");
448 } else if (c.fArguments.back()->fType.name() == "float3x3") {
449 // Invoking child with a matrix, sampling relative to the input coords.
450 invokeFunction = "invokeChildWithMatrix";
Michael Ludwig8f3a8362020-06-29 17:27:00 -0400451 SampleMatrix matrix = Analysis::GetSampleMatrix(fProgram, child);
Michael Ludwige88320b2020-06-24 09:04:56 -0400452
453 if (!matrix.isConstUniform()) {
454 inputCoord = "_matrix" + to_string(c.fOffset);
455 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
456 inputCoord.append(".c_str()");
457 }
458 // else pass in the empty string to rely on invokeChildWithMatrix's automatic uniform
459 // resolution
460 }
461 if (!inputCoord.empty()) {
462 inputCoord = ", " + inputCoord;
463 }
464
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400465 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400466 String childName = "_sample" + to_string(c.fOffset);
Brian Osman978693c2020-01-24 14:52:10 -0500467 addExtraEmitCodeLine("SkString " + childName + ";");
Michael Ludwige88320b2020-06-24 09:04:56 -0400468
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500469 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400470 addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500471 }
Michael Ludwige88320b2020-06-24 09:04:56 -0400472 addExtraEmitCodeLine(childName + " = this->" + invokeFunction + "(_outer." +
473 String(child.fName) + "_index" + inputColor + ", args" +
474 inputCoord + ");");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400475
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500476 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000477 // Null FPs are not emitted, but their output can still be referenced in dependent
Brian Osman978693c2020-01-24 14:52:10 -0500478 // expressions - thus we always fill the variable with something.
John Stilesd060c9d2020-06-08 11:44:25 -0400479 // Sampling from a null fragment processor will provide in the input color as-is. This
480 // defaults to half4(1) if no color is specified.
John Stiles50819422020-06-18 13:00:38 -0400481 if (!inputColorName.empty()) {
482 addExtraEmitCodeLine(
483 "} else {"
484 " " + childName + ".swap(" + inputColorName + ");"
485 "}");
486 } else {
487 addExtraEmitCodeLine(
488 "} else {"
489 " " + childName + " = \"half4(1)\";"
490 "}");
491 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500492 }
John Stiles50819422020-06-18 13:00:38 -0400493
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000494 this->write("%s");
495 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400496 return;
497 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400498 if (c.fFunction.fBuiltin) {
499 INHERITED::writeFunctionCall(c);
500 } else {
501 this->write("%s");
502 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
503 this->write("(");
504 const char* separator = "";
505 for (const auto& arg : c.fArguments) {
506 this->write(separator);
507 separator = ", ";
508 this->writeExpression(*arg, kSequence_Precedence);
509 }
510 this->write(")");
511 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400512 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400513 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400514 SkASSERT(c.fArguments.size() >= 1);
515 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400516 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
517 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500518 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400519 }
520}
521
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400522static const char* glsltype_string(const Context& context, const Type& type) {
523 if (type == *context.fFloat_Type) {
524 return "kFloat_GrSLType";
525 } else if (type == *context.fHalf_Type) {
526 return "kHalf_GrSLType";
527 } else if (type == *context.fFloat2_Type) {
528 return "kFloat2_GrSLType";
529 } else if (type == *context.fHalf2_Type) {
530 return "kHalf2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500531 } else if (type == *context.fFloat3_Type) {
532 return "kFloat3_GrSLType";
533 } else if (type == *context.fHalf3_Type) {
534 return "kHalf3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400535 } else if (type == *context.fFloat4_Type) {
536 return "kFloat4_GrSLType";
537 } else if (type == *context.fHalf4_Type) {
538 return "kHalf4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400539 } else if (type == *context.fFloat2x2_Type) {
540 return "kFloat2x2_GrSLType";
541 } else if (type == *context.fHalf2x2_Type) {
542 return "kHalf2x2_GrSLType";
543 } else if (type == *context.fFloat3x3_Type) {
544 return "kFloat3x3_GrSLType";
545 } else if (type == *context.fHalf3x3_Type) {
546 return "kHalf3x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400547 } else if (type == *context.fFloat4x4_Type) {
548 return "kFloat4x4_GrSLType";
549 } else if (type == *context.fHalf4x4_Type) {
550 return "kHalf4x4_GrSLType";
551 } else if (type == *context.fVoid_Type) {
552 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500553 } else if (type.kind() == Type::kEnum_Kind) {
554 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400555 }
556 SkASSERT(false);
557 return nullptr;
558}
559
Ethan Nicholas762466e2017-06-29 10:03:38 -0400560void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400561 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400562 if (decl.fBuiltin) {
563 return;
564 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400565 fFunctionHeader = "";
566 OutputStream* oldOut = fOut;
567 StringStream buffer;
568 fOut = &buffer;
569 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400570 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400571 for (const auto& s : ((Block&) *f.fBody).fStatements) {
572 this->writeStatement(*s);
573 this->writeLine();
574 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400575 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400576
577 fOut = oldOut;
578 this->write(fFunctionHeader);
579 this->write(buffer.str());
580 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400581 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
582 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
583 const char* separator = "";
584 for (const auto& param : decl.fParameters) {
585 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
586 glsltype_string(fContext, param->fType) + ")";
587 separator = ", ";
588 }
589 args += "};";
590 this->addExtraEmitCodeLine(args.c_str());
591 for (const auto& s : ((Block&) *f.fBody).fStatements) {
592 this->writeStatement(*s);
593 this->writeLine();
594 }
595
596 fOut = oldOut;
597 String emit = "fragBuilder->emitFunction(";
598 emit += glsltype_string(fContext, decl.fReturnType);
599 emit += ", \"" + decl.fName + "\"";
600 emit += ", " + to_string((int64_t) decl.fParameters.size());
601 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400602 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400603 emit += ", &" + decl.fName + "_name);";
604 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400605 }
606}
607
608void CPPCodeGenerator::writeSetting(const Setting& s) {
609 static constexpr const char* kPrefix = "sk_Args.";
610 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
611 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400612 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400613 } else {
614 this->write(s.fName.c_str());
615 }
616}
617
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400618bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400619 const Section* s = fSectionAndParameterHelper.getSection(name);
620 if (s) {
621 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400622 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400623 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400624 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400625}
626
627void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
628 if (p.fKind == ProgramElement::kSection_Kind) {
629 return;
630 }
631 if (p.fKind == ProgramElement::kVar_Kind) {
632 const VarDeclarations& decls = (const VarDeclarations&) p;
633 if (!decls.fVars.size()) {
634 return;
635 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000636 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400637 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
638 -1 != var.fModifiers.fLayout.fBuiltin) {
639 return;
640 }
641 }
642 INHERITED::writeProgramElement(p);
643}
644
645void CPPCodeGenerator::addUniform(const Variable& var) {
646 if (!needs_uniform_var(var)) {
647 return;
648 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400649 if (var.fModifiers.fLayout.fWhen.fLength) {
650 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400651 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400652 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700653 String name(var.fName);
Ethan Nicholas16464c32020-04-06 13:53:05 -0400654 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
655 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700656 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400657 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400658 this->write(" }\n");
659 }
660}
661
Ethan Nicholascd700e92018-08-24 16:43:57 -0400662void CPPCodeGenerator::writeInputVars() {
663}
664
Ethan Nicholas762466e2017-06-29 10:03:38 -0400665void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400666 for (const auto& p : fProgram) {
667 if (ProgramElement::kVar_Kind == p.fKind) {
668 const VarDeclarations& decls = (const VarDeclarations&) p;
669 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000670 VarDeclaration& decl = (VarDeclaration&) *raw;
671 if (is_private(*decl.fVar)) {
672 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
673 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400674 "fragmentProcessor variables must be declared 'in'");
675 return;
676 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500677 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000678 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
679 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500680 String(decl.fVar->fName).c_str(),
681 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400682 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
683 // An auto-tracked uniform in variable, so add a field to hold onto the prior
684 // state. Note that tracked variables must be uniform in's and that is validated
685 // before writePrivateVars() is called.
686 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
687 SkASSERT(mapper && mapper->supportsTracking());
688
689 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
690 // The member statement is different if the mapper reports a default value
691 if (mapper->defaultValue().size() > 0) {
692 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400693 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400694 mapper->defaultValue().c_str());
695 } else {
696 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400697 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400698 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400699 }
700 }
701 }
702 }
703}
704
705void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400706 for (const auto& p : fProgram) {
707 if (ProgramElement::kVar_Kind == p.fKind) {
708 const VarDeclarations& decls = (const VarDeclarations&) p;
709 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000710 VarDeclaration& decl = (VarDeclaration&) *raw;
711 if (is_private(*decl.fVar) && decl.fValue) {
712 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400713 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000714 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400715 fCPPMode = false;
716 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400717 }
718 }
719 }
720 }
721}
722
Ethan Nicholas82399462017-10-16 12:35:44 -0400723static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500724 const Type& type = var.fType.nonnullable();
725 return Type::kSampler_Kind != type.kind() &&
726 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400727}
728
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400729void CPPCodeGenerator::newExtraEmitCodeBlock() {
730 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
731 // cpp buffer is not null, and the cpp buffer is not the current output.
732 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
733
734 // Start a new block as an empty string
735 fExtraEmitCodeBlocks.push_back("");
736 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
737 // valid sksl and makes detection trivial.
738 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
739}
740
741void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
742 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
743 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
744 // Automatically add indentation and newline
745 currentBlock += " " + toAppend + "\n";
746}
747
748void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400749 if (fCPPBuffer == nullptr) {
750 // Not actually within writeEmitCode() so nothing to flush
751 return;
752 }
753
754 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
755
756 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400757 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400758 skslBuffer->reset();
759
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400760 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000761 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400762
763 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
764 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
765 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
766 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
767 // statement left off (minus the encountered token).
768 size_t i = 0;
769 int flushPoint = -1;
770 int tokenStart = -1;
771 while (i < sksl.size()) {
772 if (tokenStart >= 0) {
773 // Looking for the end of the token
774 if (sksl[i] == '}') {
775 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
776 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
777 String toFlush = String(sksl.c_str(), flushPoint + 1);
778 // writeCodeAppend automatically removes the format args that it consumed, so
779 // fFormatArgs will be in a valid state for any future sksl
780 this->writeCodeAppend(toFlush);
781
782 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
783 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
784 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
785 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
786 }
787
788 // Now reset the sksl buffer to start after the flush point, but remove the token.
789 String compacted = String(sksl.c_str() + flushPoint + 1,
790 tokenStart - flushPoint - 1);
791 if (i < sksl.size() - 1) {
792 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
793 }
794 sksl = compacted;
795
796 // And reset iteration
797 i = -1;
798 flushPoint = -1;
799 tokenStart = -1;
800 }
801 } else {
802 // Looking for the start of extra emit block tokens, and tracking when statements end
803 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
804 flushPoint = i;
805 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
806 // found an extra emit code block token
807 tokenStart = i++;
808 }
809 }
810 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000811 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400812
813 // Once we've gone through the sksl string to this point, there are no remaining extra emit
814 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400815 this->writeCodeAppend(sksl);
816
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400817 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400818 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400819 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400820}
821
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400822void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400823 if (!code.empty()) {
824 // Count % format specifiers.
825 size_t argCount = 0;
826 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400827 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400828 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400829 break;
830 }
831 if (code[index + 1] != '%') {
832 ++argCount;
833 }
834 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400835 }
John Stiles50819422020-06-18 13:00:38 -0400836
837 // Emit the code string.
838 this->writef(" fragBuilder->codeAppendf(\n"
839 "R\"SkSL(%s)SkSL\"\n", code.c_str());
840 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400841 this->writef(", %s", fFormatArgs[i].c_str());
842 }
843 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400844
John Stiles50819422020-06-18 13:00:38 -0400845 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
846 // removed from the list.
847 if (argCount > 0) {
848 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
849 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400850 }
851}
852
853String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
854 const String& cppVar) {
855 // To do this conversion, we temporarily switch the sksl output stream
856 // to an empty stringstream and reset the format args to empty.
857 OutputStream* oldSKSL = fOut;
858 StringStream exprBuffer;
859 fOut = &exprBuffer;
860
861 std::vector<String> oldArgs(fFormatArgs);
862 fFormatArgs.clear();
863
864 // Convert the argument expression into a format string and args
865 this->writeExpression(e, Precedence::kTopLevel_Precedence);
866 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400867 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400868
869 // After generating, restore the original output stream and format args
870 fFormatArgs = oldArgs;
871 fOut = oldSKSL;
872
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400873 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
874 // block tokens won't get handled. So we need to strip them from the expression and stick them
875 // to the end of the original sksl stream.
876 String exprFormat = "";
877 int tokenStart = -1;
878 for (size_t i = 0; i < expr.size(); i++) {
879 if (tokenStart >= 0) {
880 if (expr[i] == '}') {
881 // End of the token, so append the token to fOut
882 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
883 tokenStart = -1;
884 }
885 } else {
886 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
887 tokenStart = i++;
888 } else {
889 exprFormat += expr[i];
890 }
891 }
892 }
893
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400894 // Now build the final C++ code snippet from the format string and args
895 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400896 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400897 // This was a static expression, so we can simplify the input
898 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400899 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400900 } else if (newArgs.size() == 1 && exprFormat == "%s") {
901 // If the format expression is simply "%s", we can avoid an expensive call to printf.
902 // This happens fairly often in codegen so it is worth simplifying.
903 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400904 } else {
905 // String formatting must occur dynamically, so have the C++ declaration
906 // use SkStringPrintf with the format args that were accumulated
907 // when the expression was written.
908 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
909 for (size_t i = 0; i < newArgs.size(); i++) {
910 cppExpr += ", " + newArgs[i];
911 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400912 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400913 }
914 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400915}
916
Ethan Nicholas762466e2017-06-29 10:03:38 -0400917bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
918 this->write(" void emitCode(EmitArgs& args) override {\n"
919 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
920 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
921 " (void) _outer;\n",
922 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400923 for (const auto& p : fProgram) {
924 if (ProgramElement::kVar_Kind == p.fKind) {
925 const VarDeclarations& decls = (const VarDeclarations&) p;
926 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000927 VarDeclaration& decl = (VarDeclaration&) *raw;
928 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400929 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000930 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
931 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400932 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400933 " (void) %s;\n",
934 name, name, name);
935 }
936 }
937 }
938 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400939 this->writePrivateVarValues();
940 for (const auto u : uniforms) {
941 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400942 }
943 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400944
945 // Save original buffer as the CPP buffer for flushEmittedCode()
946 fCPPBuffer = fOut;
947 StringStream skslBuffer;
948 fOut = &skslBuffer;
949
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400950 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400951 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400952 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400953
954 // Then restore the original CPP buffer and close the function
955 fOut = fCPPBuffer;
956 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400957 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400958 return result;
959}
960
961void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
962 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400963 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
964 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400965 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
966 "const GrFragmentProcessor& _proc) override {\n",
967 pdman);
968 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400969 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400970 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400971 if (!wroteProcessor) {
972 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
973 wroteProcessor = true;
974 this->writef(" {\n");
975 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400976
977 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
978 SkASSERT(mapper);
979
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700980 String nameString(u->fName);
981 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400982
983 // Switches for setData behavior in the generated code
984 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
985 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
986 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
987
988 String uniformName = HCodeGenerator::FieldName(name) + "Var";
989
990 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
991 if (conditionalUniform) {
992 // Add a pre-check to make sure the uniform was emitted
993 // before trying to send any data to the GPU
994 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
995 indent += " ";
996 }
997
998 String valueVar = "";
999 if (needsValueDeclaration) {
1000 valueVar.appendf("%sValue", name);
1001 // Use AccessType since that will match the return type of _outer's public API.
1002 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1003 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001004 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001005 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001006 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001007 // Not tracked and the mapper only needs to use the value once
1008 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001009 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001010 }
1011
1012 if (isTracked) {
1013 SkASSERT(mapper->supportsTracking());
1014
1015 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1016 this->writef("%sif (%s) {\n"
1017 "%s %s;\n"
1018 "%s %s;\n"
1019 "%s}\n", indent.c_str(),
1020 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1021 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1022 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1023 } else {
1024 this->writef("%s%s;\n", indent.c_str(),
1025 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1026 }
1027
1028 if (conditionalUniform) {
1029 // Close the earlier precheck block
1030 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001031 }
1032 }
1033 }
1034 if (wroteProcessor) {
1035 this->writef(" }\n");
1036 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001037 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001038 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001039 for (const auto& p : fProgram) {
1040 if (ProgramElement::kVar_Kind == p.fKind) {
1041 const VarDeclarations& decls = (const VarDeclarations&) p;
John Stiles06f3d082020-06-04 11:07:21 -04001042 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
1043 const VarDeclaration& decl = static_cast<VarDeclaration&>(*raw);
1044 const Variable& variable = *decl.fVar;
1045 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001046 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001047 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001048 this->writef(" const GrSurfaceProxyView& %sView = "
1049 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001050 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001051 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001052 name, name);
1053 this->writef(" (void) %s;\n", name);
1054 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001055 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001056 this->writef(" UniformHandle& %s = %sVar;\n"
1057 " (void) %s;\n",
1058 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001059 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1060 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001061 if (!wroteProcessor) {
1062 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1063 fullName);
1064 wroteProcessor = true;
1065 }
John Stiles06f3d082020-06-04 11:07:21 -04001066
1067 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1068 this->writef(" auto %s = _outer.%s;\n"
1069 " (void) %s;\n",
1070 name, name, name);
1071 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001072 }
1073 }
1074 }
1075 }
1076 this->writeSection(SET_DATA_SECTION);
1077 }
1078 this->write(" }\n");
1079}
1080
Brian Salomonf7dcd762018-07-30 14:48:15 -04001081void CPPCodeGenerator::writeOnTextureSampler() {
1082 bool foundSampler = false;
1083 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1084 if (param->fType.kind() == Type::kSampler_Kind) {
1085 if (!foundSampler) {
1086 this->writef(
1087 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1088 "index) const {\n",
1089 fFullName.c_str());
1090 this->writef(" return IthTextureSampler(index, %s",
1091 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1092 foundSampler = true;
1093 } else {
1094 this->writef(", %s",
1095 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1096 }
1097 }
1098 }
1099 if (foundSampler) {
1100 this->write(");\n}\n");
1101 }
1102}
1103
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001104void CPPCodeGenerator::writeClone() {
1105 if (!this->writeSection(CLONE_SECTION)) {
1106 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001107 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1108 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001109 }
1110 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001111 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1112 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001113 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
1114 for (size_t i = 0; i < transforms.size(); ++i) {
1115 const Section& s = *transforms[i];
1116 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1117 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
1118 }
John Stiles06f3d082020-06-04 11:07:21 -04001119 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001120 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001121 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001122 this->writef("\n, %s(src.%s)",
1123 fieldName.c_str(),
1124 fieldName.c_str());
1125 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001126 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001127 this->writef(" {\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001128 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001129 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1130 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001131 ++samplerCount;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001132 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1133 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1134 if (param->fType.kind() == Type::kNullable_Kind) {
John Stiles88183902020-06-10 16:40:38 -04001135 this->writef(" if (src.%s_index >= 0) {\n", fieldName.c_str());
Brian Salomonb243b432020-02-20 14:41:47 -05001136 } else {
1137 this->write(" {\n");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001138 }
John Stiles3779f442020-06-15 10:48:49 -04001139 this->writef(" %s_index = this->cloneAndRegisterChildProcessor("
1140 "src.childProcessor(src.%s_index));\n"
1141 " }\n",
1142 fieldName.c_str(), fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001143 }
1144 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001145 if (samplerCount) {
1146 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1147 }
Ethan Nicholas929a6812018-08-06 14:56:59 -04001148 for (size_t i = 0; i < transforms.size(); ++i) {
1149 const Section& s = *transforms[i];
1150 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1151 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001152 }
Michael Ludwige88320b2020-06-24 09:04:56 -04001153 if (fAccessSampleCoordsDirectly) {
1154 this->writef(" this->setUsesSampleCoordsDirectly();\n");
1155 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001156 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001157 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1158 fFullName.c_str());
1159 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1160 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001161 this->write("}\n");
1162 }
1163}
1164
Ethan Nicholas762466e2017-06-29 10:03:38 -04001165void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001166 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1167 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001168 this->writef(
1169 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1170 "#if GR_TEST_UTILS\n"
1171 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1172 fFullName.c_str(),
1173 fFullName.c_str(),
1174 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001175 this->writeSection(TEST_CODE_SECTION);
1176 this->write("}\n"
1177 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001178 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001179}
1180
1181void CPPCodeGenerator::writeGetKey() {
1182 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1183 "GrProcessorKeyBuilder* b) const {\n",
1184 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001185 for (const auto& p : fProgram) {
1186 if (ProgramElement::kVar_Kind == p.fKind) {
1187 const VarDeclarations& decls = (const VarDeclarations&) p;
1188 for (const auto& raw : decls.fVars) {
1189 const VarDeclaration& decl = (VarDeclaration&) *raw;
1190 const Variable& var = *decl.fVar;
1191 String nameString(var.fName);
1192 const char* name = nameString.c_str();
1193 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1194 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1195 fErrors.error(var.fOffset,
1196 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001197 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001198 switch (var.fModifiers.fLayout.fKey) {
1199 case Layout::kKey_Key:
1200 if (is_private(var)) {
1201 this->writef("%s %s =",
1202 HCodeGenerator::FieldType(fContext, var.fType,
1203 var.fModifiers.fLayout).c_str(),
1204 String(var.fName).c_str());
1205 if (decl.fValue) {
1206 fCPPMode = true;
1207 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1208 fCPPMode = false;
1209 } else {
1210 this->writef("%s", default_value(var).c_str());
1211 }
1212 this->write(";\n");
1213 }
1214 if (var.fModifiers.fLayout.fWhen.fLength) {
1215 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1216 }
1217 if (var.fType == *fContext.fFloat4x4_Type) {
1218 ABORT("no automatic key handling for float4x4\n");
1219 } else if (var.fType == *fContext.fFloat2_Type) {
1220 this->writef(" b->add32(%s.fX);\n",
1221 HCodeGenerator::FieldName(name).c_str());
1222 this->writef(" b->add32(%s.fY);\n",
1223 HCodeGenerator::FieldName(name).c_str());
1224 } else if (var.fType == *fContext.fFloat4_Type) {
1225 this->writef(" b->add32(%s.x());\n",
1226 HCodeGenerator::FieldName(name).c_str());
1227 this->writef(" b->add32(%s.y());\n",
1228 HCodeGenerator::FieldName(name).c_str());
1229 this->writef(" b->add32(%s.width());\n",
1230 HCodeGenerator::FieldName(name).c_str());
1231 this->writef(" b->add32(%s.height());\n",
1232 HCodeGenerator::FieldName(name).c_str());
1233 } else if (var.fType == *fContext.fHalf4_Type) {
1234 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1235 HCodeGenerator::FieldName(name).c_str());
1236 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1237 HCodeGenerator::FieldName(name).c_str());
1238 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1239 HCodeGenerator::FieldName(name).c_str());
1240 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1241 HCodeGenerator::FieldName(name).c_str());
1242 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1243 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
1244 } else {
1245 this->writef(" b->add32((int32_t) %s);\n",
1246 HCodeGenerator::FieldName(name).c_str());
1247 }
1248 if (var.fModifiers.fLayout.fWhen.fLength) {
1249 this->write("}");
1250 }
1251 break;
1252 case Layout::kIdentity_Key:
1253 if (var.fType.kind() != Type::kMatrix_Kind) {
1254 fErrors.error(var.fOffset,
1255 "layout(key=identity) requires matrix type");
1256 }
1257 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1258 HCodeGenerator::FieldName(name).c_str());
1259 break;
1260 case Layout::kNo_Key:
1261 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001262 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001263 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001264 }
1265 }
1266 this->write("}\n");
1267}
1268
1269bool CPPCodeGenerator::generateCode() {
1270 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001271 for (const auto& p : fProgram) {
1272 if (ProgramElement::kVar_Kind == p.fKind) {
1273 const VarDeclarations& decls = (const VarDeclarations&) p;
1274 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001275 VarDeclaration& decl = (VarDeclaration&) *raw;
1276 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1277 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1278 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001279 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001280
1281 if (is_uniform_in(*decl.fVar)) {
1282 // Validate the "uniform in" declarations to make sure they are fully supported,
1283 // instead of generating surprising C++
1284 const UniformCTypeMapper* mapper =
1285 UniformCTypeMapper::Get(fContext, *decl.fVar);
1286 if (mapper == nullptr) {
1287 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1288 + "'s type is not supported for use as a 'uniform in'");
1289 return false;
1290 }
1291 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1292 if (!mapper->supportsTracking()) {
1293 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1294 + "'s type does not support state tracking");
1295 return false;
1296 }
1297 }
1298
1299 } else {
1300 // If it's not a uniform_in, it's an error to be tracked
1301 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1302 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1303 return false;
1304 }
1305 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001306 }
1307 }
1308 }
1309 const char* baseName = fName.c_str();
1310 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001311 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001312 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001313 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001314 this->writeSection(CPP_SECTION);
Greg Daniel456f9b52020-03-05 19:14:18 +00001315 this->writef("#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001316 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1317 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1318 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1319 "#include \"src/sksl/SkSLCPP.h\"\n"
1320 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001321 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1322 "public:\n"
1323 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001324 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001325 bool result = this->writeEmitCode(uniforms);
1326 this->write("private:\n");
1327 this->writeSetData(uniforms);
1328 this->writePrivateVars();
1329 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001330 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001331 this->writef(" UniformHandle %sVar;\n",
1332 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001333 }
1334 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001335 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001336 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001337 this->writef(" UniformHandle %sVar;\n",
1338 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001339 }
1340 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001341 this->writef("};\n"
1342 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1343 " return new GrGLSL%s();\n"
1344 "}\n",
1345 fullName, baseName);
1346 this->writeGetKey();
1347 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1348 " const %s& that = other.cast<%s>();\n"
1349 " (void) that;\n",
1350 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001351 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001352 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001353 continue;
1354 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001355 String nameString(param->fName);
1356 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001357 this->writef(" if (%s != that.%s) return false;\n",
1358 HCodeGenerator::FieldName(name).c_str(),
1359 HCodeGenerator::FieldName(name).c_str());
1360 }
1361 this->write(" return true;\n"
1362 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001363 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001364 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001365 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001366 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001367
Ethan Nicholas762466e2017-06-29 10:03:38 -04001368 result &= 0 == fErrors.errorCount();
1369 return result;
1370}
1371
1372} // namespace