blob: 5878b12cf64f1c7e6978b3bdf5e6b7a80517134d [file] [log] [blame]
Ethan Nicholas762466e2017-06-29 10:03:38 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCPPCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCPPUniformCTypes.h"
11#include "src/sksl/SkSLCompiler.h"
12#include "src/sksl/SkSLHCodeGenerator.h"
Ethan Nicholas58430122020-04-14 09:54:02 -040013#include "src/sksl/SkSLSampleMatrix.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040014
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040015#include <algorithm>
16
Ethan Nicholas762466e2017-06-29 10:03:38 -040017namespace SkSL {
18
19static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050020 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
21 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040022}
23
24CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
25 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040026 : INHERITED(context, program, errors, out)
27 , fName(std::move(name))
28 , fFullName(String::printf("Gr%s", fName.c_str()))
29 , fSectionAndParameterHelper(program, *errors) {
30 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040031 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040032}
33
34void CPPCodeGenerator::writef(const char* s, va_list va) {
35 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040036 va_list copy;
37 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040038 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040039 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040040 if (length < BUFFER_SIZE) {
41 fOut->write(buffer, length);
42 } else {
43 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040044 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040045 fOut->write(heap.get(), length);
46 }
z102.zhangd74f2c82018-08-10 09:08:47 +080047 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040048}
49
50void CPPCodeGenerator::writef(const char* s, ...) {
51 va_list va;
52 va_start(va, s);
53 this->writef(s, va);
54 va_end(va);
55}
56
57void CPPCodeGenerator::writeHeader() {
58}
59
Ethan Nicholasf7b88202017-09-18 14:10:39 -040060bool CPPCodeGenerator::usesPrecisionModifiers() const {
61 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040062}
63
Ethan Nicholasf7b88202017-09-18 14:10:39 -040064String CPPCodeGenerator::getTypeName(const Type& type) {
65 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040066}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040067
Ethan Nicholas762466e2017-06-29 10:03:38 -040068void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
69 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040070 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040071 // need to use "%%" instead of "%" b/c the code will be inside of a printf
72 Precedence precedence = GetBinaryPrecedence(b.fOperator);
73 if (precedence >= parentPrecedence) {
74 this->write("(");
75 }
76 this->writeExpression(*b.fLeft, precedence);
77 this->write(" %% ");
78 this->writeExpression(*b.fRight, precedence);
79 if (precedence >= parentPrecedence) {
80 this->write(")");
81 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050082 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
83 b.fRight->fKind == Expression::kNullLiteral_Kind) {
84 const Variable* var;
85 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
86 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
87 var = &((VariableReference&) *b.fLeft).fVariable;
88 } else {
89 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
90 var = &((VariableReference&) *b.fRight).fVariable;
91 }
92 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
93 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
94 this->write("%s");
95 const char* op;
96 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040097 case Token::Kind::TK_EQEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050098 op = "<";
99 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400100 case Token::Kind::TK_NEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500101 op = ">=";
102 break;
103 default:
104 SkASSERT(false);
105 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400106 fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500107 ": \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400108 } else {
109 INHERITED::writeBinaryExpression(b, parentPrecedence);
110 }
111}
112
113void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
114 const Expression& base = *i.fBase;
115 if (base.fKind == Expression::kVariableReference_Kind) {
116 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
117 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
118 this->write("%s");
119 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700120 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400121 "index into sk_TransformedCoords2D must be an integer literal");
122 return;
123 }
124 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
125 String name = "sk_TransformedCoords2D_" + to_string(index);
Brian Salomonbf5c0c02019-11-11 14:55:28 -0500126 fFormatArgs.push_back(name + ".c_str()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400127 if (fWrittenTransformedCoords.find(index) == fWrittenTransformedCoords.end()) {
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400128 addExtraEmitCodeLine("SkString " + name +
129 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
Ethan Nicholas58430122020-04-14 09:54:02 -0400130 to_string(index) + "].fVaryingPoint, _outer.sampleMatrix());");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400131 fWrittenTransformedCoords.insert(index);
132 }
133 return;
134 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
135 this->write("%s");
136 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700137 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400138 "index into sk_TextureSamplers must be an integer literal");
139 return;
140 }
141 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
142 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400143 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400144 return;
145 }
146 }
147 INHERITED::writeIndexExpression(i);
148}
149
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400150static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500151 if (type.fName == "bool") {
152 return "false";
153 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400154 switch (type.kind()) {
155 case Type::kScalar_Kind: return "0";
156 case Type::kVector_Kind: return type.name() + "(0)";
157 case Type::kMatrix_Kind: return type.name() + "(1)";
158 default: ABORT("unsupported default_value type\n");
159 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400160}
161
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500162static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400163 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400164 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500165 }
166 return default_value(var.fType);
167}
168
Ethan Nicholas762466e2017-06-29 10:03:38 -0400169static bool is_private(const Variable& var) {
170 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
171 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
172 var.fStorage == Variable::kGlobal_Storage &&
173 var.fModifiers.fLayout.fBuiltin == -1;
174}
175
Michael Ludwiga4275592018-08-31 10:52:47 -0400176static bool is_uniform_in(const Variable& var) {
177 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
178 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
179 var.fType.kind() != Type::kSampler_Kind;
180}
181
Ethan Nicholasd608c092017-10-26 09:30:08 -0400182void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
183 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400184 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400185 this->write("%f");
186 fFormatArgs.push_back(cppCode);
187 } else if (type == *fContext.fInt_Type) {
188 this->write("%d");
189 fFormatArgs.push_back(cppCode);
190 } else if (type == *fContext.fBool_Type) {
191 this->write("%s");
192 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400193 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
194 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400195 fFormatArgs.push_back(cppCode + ".fX");
196 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400197 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
198 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400199 switch (layout.fCType) {
200 case Layout::CType::kSkPMColor:
201 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
202 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
203 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
204 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
205 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400206 case Layout::CType::kSkPMColor4f:
207 fFormatArgs.push_back(cppCode + ".fR");
208 fFormatArgs.push_back(cppCode + ".fG");
209 fFormatArgs.push_back(cppCode + ".fB");
210 fFormatArgs.push_back(cppCode + ".fA");
211 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500212 case Layout::CType::kSkV4:
213 fFormatArgs.push_back(cppCode + ".x");
214 fFormatArgs.push_back(cppCode + ".y");
215 fFormatArgs.push_back(cppCode + ".z");
216 fFormatArgs.push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400217 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400218 case Layout::CType::kSkRect: // fall through
219 case Layout::CType::kDefault:
220 fFormatArgs.push_back(cppCode + ".left()");
221 fFormatArgs.push_back(cppCode + ".top()");
222 fFormatArgs.push_back(cppCode + ".right()");
223 fFormatArgs.push_back(cppCode + ".bottom()");
224 break;
225 default:
226 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400227 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500228 } else if (type.kind() == Type::kEnum_Kind) {
229 this->write("%d");
230 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400231 } else if (type == *fContext.fInt4_Type ||
232 type == *fContext.fShort4_Type ||
233 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500234 this->write(type.name() + "(%d, %d, %d, %d)");
235 fFormatArgs.push_back(cppCode + ".left()");
236 fFormatArgs.push_back(cppCode + ".top()");
237 fFormatArgs.push_back(cppCode + ".right()");
238 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400239 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400240 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400241 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400242 }
243}
244
245void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
246 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400247 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400248 } else {
249 this->writeExpression(value, kTopLevel_Precedence);
250 }
251}
252
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400253String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
254 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400255 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400256 if (&var == param) {
257 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
258 }
259 if (param->fType.kind() == Type::kSampler_Kind) {
260 ++samplerCount;
261 }
262 }
263 ABORT("should have found sampler in parameters\n");
264}
265
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400266void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
267 this->write(to_string((int32_t) i.fValue));
268}
269
Ethan Nicholas82399462017-10-16 12:35:44 -0400270void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
271 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400272 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400273 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
274 switch (swizzle.fComponents[0]) {
275 case 0: this->write(".left()"); break;
276 case 1: this->write(".top()"); break;
277 case 2: this->write(".right()"); break;
278 case 3: this->write(".bottom()"); break;
279 }
280 } else {
281 INHERITED::writeSwizzle(swizzle);
282 }
283}
284
Ethan Nicholas762466e2017-06-29 10:03:38 -0400285void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400286 if (fCPPMode) {
287 this->write(ref.fVariable.fName);
288 return;
289 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400290 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
291 case SK_INCOLOR_BUILTIN:
292 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400293 // EmitArgs.fInputColor is automatically set to half4(1) if
294 // no input was specified
295 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400296 break;
297 case SK_OUTCOLOR_BUILTIN:
298 this->write("%s");
299 fFormatArgs.push_back(String("args.fOutputColor"));
300 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400301 case SK_WIDTH_BUILTIN:
302 this->write("sk_Width");
303 break;
304 case SK_HEIGHT_BUILTIN:
305 this->write("sk_Height");
306 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400307 default:
308 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400309 this->write("%s");
310 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400311 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400312 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400313 }
314 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
315 this->write("%s");
316 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400317 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
318 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400319 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400320 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400321 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
322 HCodeGenerator::FieldName(name.c_str()).c_str(),
323 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400324 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 } else {
326 code = var;
327 }
328 fFormatArgs.push_back(code);
329 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700330 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400331 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400332 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400333 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700334 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400335 }
336 }
337}
338
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400339void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
340 if (s.fIsStatic) {
341 this->write("@");
342 }
343 INHERITED::writeIfStatement(s);
344}
345
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400346void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
347 if (fInMain) {
348 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
349 }
350 INHERITED::writeReturnStatement(s);
351}
352
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400353void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
354 if (s.fIsStatic) {
355 this->write("@");
356 }
357 INHERITED::writeSwitchStatement(s);
358}
359
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400360void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
361 if (access.fBase->fType.name() == "fragmentProcessor") {
362 // Special field access on fragment processors are converted into function calls on
363 // GrFragmentProcessor's getters.
364 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
365 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
366 return;
367 }
368
369 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500370 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400371 String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500372 String(var.fName).c_str(),
373 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400374
375 if (fCPPMode) {
376 this->write(cppAccess.c_str());
377 } else {
378 writeRuntimeValue(*field.fType, Layout(), cppAccess);
379 }
380 return;
381 }
382 INHERITED::writeFieldAccess(access);
383}
384
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500385int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386 int index = 0;
387 bool found = false;
388 for (const auto& p : fProgram) {
389 if (ProgramElement::kVar_Kind == p.fKind) {
390 const VarDeclarations& decls = (const VarDeclarations&) p;
391 for (const auto& raw : decls.fVars) {
392 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500393 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400394 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500395 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400396 ++index;
397 }
398 }
399 }
400 if (found) {
401 break;
402 }
403 }
404 SkASSERT(found);
405 return index;
406}
407
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400408void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400409 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
410 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400411 // Sanity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400412 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500413 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
414 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400415
416 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400417 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400418 // special function that impacts code emission.
419 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
420 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400421 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400422 return;
423 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500424 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400425
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400426 // Start a new extra emit code section so that the emitted child processor can depend on
427 // sksl variables defined in earlier sksl code.
428 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400429
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400430 // Set to the empty string when no input color parameter should be emitted, which means this
431 // must be properly formatted with a prefixed comma when the parameter should be inserted
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400432 // into the invokeChild() parameter list.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400433 String inputArg;
John Stiles50819422020-06-18 13:00:38 -0400434 String inputColorName;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400435 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400436 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400437 // argument's expression into C++ code that produces sksl stored in an SkString.
John Stilesd060c9d2020-06-08 11:44:25 -0400438 inputColorName = "_input" + to_string(c.fOffset);
439 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400440
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400441 // invokeChild() needs a char*
John Stilesd060c9d2020-06-08 11:44:25 -0400442 inputArg = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400443 }
444
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400445 bool hasCoords = c.fArguments.back()->fType.name() == "float2";
Brian Osman5ee90ff2020-06-10 16:08:54 -0400446 SampleMatrix matrix = SampleMatrix::Make(fProgram, child);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400447 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400448 String childName = "_sample" + to_string(c.fOffset);
Brian Osman978693c2020-01-24 14:52:10 -0500449 addExtraEmitCodeLine("SkString " + childName + ";");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400450 String coordsName;
Ethan Nicholas58430122020-04-14 09:54:02 -0400451 String matrixName;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400452 if (hasCoords) {
453 coordsName = "_coords" + to_string(c.fOffset);
454 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), coordsName));
455 }
Ethan Nicholas58430122020-04-14 09:54:02 -0400456 if (matrix.fKind == SampleMatrix::Kind::kVariable) {
457 matrixName = "_matrix" + to_string(c.fOffset);
458 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), matrixName));
459 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500460 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400461 addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500462 }
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400463 if (hasCoords) {
Brian Osman978693c2020-01-24 14:52:10 -0500464 addExtraEmitCodeLine(childName + " = this->invokeChild(_outer." + String(child.fName) +
465 "_index" + inputArg + ", args, " + coordsName + ".c_str());");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400466 } else {
Ethan Nicholas58430122020-04-14 09:54:02 -0400467 switch (matrix.fKind) {
468 case SampleMatrix::Kind::kMixed:
469 case SampleMatrix::Kind::kVariable:
470 addExtraEmitCodeLine(childName + " = this->invokeChildWithMatrix(_outer." +
471 String(child.fName) + "_index" + inputArg + ", args, " +
472 matrixName + ".c_str());");
473 break;
474 case SampleMatrix::Kind::kConstantOrUniform:
475 case SampleMatrix::Kind::kNone:
476 addExtraEmitCodeLine(childName + " = this->invokeChild(_outer." +
477 String(child.fName) + "_index" + inputArg + ", args);");
478 break;
479 }
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400480 }
481
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500482 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000483 // Null FPs are not emitted, but their output can still be referenced in dependent
Brian Osman978693c2020-01-24 14:52:10 -0500484 // expressions - thus we always fill the variable with something.
John Stilesd060c9d2020-06-08 11:44:25 -0400485 // Sampling from a null fragment processor will provide in the input color as-is. This
486 // defaults to half4(1) if no color is specified.
John Stiles50819422020-06-18 13:00:38 -0400487 if (!inputColorName.empty()) {
488 addExtraEmitCodeLine(
489 "} else {"
490 " " + childName + ".swap(" + inputColorName + ");"
491 "}");
492 } else {
493 addExtraEmitCodeLine(
494 "} else {"
495 " " + childName + " = \"half4(1)\";"
496 "}");
497 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500498 }
John Stiles50819422020-06-18 13:00:38 -0400499
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000500 this->write("%s");
501 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400502 return;
503 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400504 if (c.fFunction.fBuiltin) {
505 INHERITED::writeFunctionCall(c);
506 } else {
507 this->write("%s");
508 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
509 this->write("(");
510 const char* separator = "";
511 for (const auto& arg : c.fArguments) {
512 this->write(separator);
513 separator = ", ";
514 this->writeExpression(*arg, kSequence_Precedence);
515 }
516 this->write(")");
517 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400518 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400519 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400520 SkASSERT(c.fArguments.size() >= 1);
521 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400522 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
523 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500524 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400525 }
526}
527
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400528static const char* glsltype_string(const Context& context, const Type& type) {
529 if (type == *context.fFloat_Type) {
530 return "kFloat_GrSLType";
531 } else if (type == *context.fHalf_Type) {
532 return "kHalf_GrSLType";
533 } else if (type == *context.fFloat2_Type) {
534 return "kFloat2_GrSLType";
535 } else if (type == *context.fHalf2_Type) {
536 return "kHalf2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500537 } else if (type == *context.fFloat3_Type) {
538 return "kFloat3_GrSLType";
539 } else if (type == *context.fHalf3_Type) {
540 return "kHalf3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400541 } else if (type == *context.fFloat4_Type) {
542 return "kFloat4_GrSLType";
543 } else if (type == *context.fHalf4_Type) {
544 return "kHalf4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400545 } else if (type == *context.fFloat2x2_Type) {
546 return "kFloat2x2_GrSLType";
547 } else if (type == *context.fHalf2x2_Type) {
548 return "kHalf2x2_GrSLType";
549 } else if (type == *context.fFloat3x3_Type) {
550 return "kFloat3x3_GrSLType";
551 } else if (type == *context.fHalf3x3_Type) {
552 return "kHalf3x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400553 } else if (type == *context.fFloat4x4_Type) {
554 return "kFloat4x4_GrSLType";
555 } else if (type == *context.fHalf4x4_Type) {
556 return "kHalf4x4_GrSLType";
557 } else if (type == *context.fVoid_Type) {
558 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500559 } else if (type.kind() == Type::kEnum_Kind) {
560 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400561 }
562 SkASSERT(false);
563 return nullptr;
564}
565
Ethan Nicholas762466e2017-06-29 10:03:38 -0400566void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400567 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400568 if (decl.fBuiltin) {
569 return;
570 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400571 fFunctionHeader = "";
572 OutputStream* oldOut = fOut;
573 StringStream buffer;
574 fOut = &buffer;
575 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400576 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400577 for (const auto& s : ((Block&) *f.fBody).fStatements) {
578 this->writeStatement(*s);
579 this->writeLine();
580 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400581 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400582
583 fOut = oldOut;
584 this->write(fFunctionHeader);
585 this->write(buffer.str());
586 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400587 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
588 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
589 const char* separator = "";
590 for (const auto& param : decl.fParameters) {
591 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
592 glsltype_string(fContext, param->fType) + ")";
593 separator = ", ";
594 }
595 args += "};";
596 this->addExtraEmitCodeLine(args.c_str());
597 for (const auto& s : ((Block&) *f.fBody).fStatements) {
598 this->writeStatement(*s);
599 this->writeLine();
600 }
601
602 fOut = oldOut;
603 String emit = "fragBuilder->emitFunction(";
604 emit += glsltype_string(fContext, decl.fReturnType);
605 emit += ", \"" + decl.fName + "\"";
606 emit += ", " + to_string((int64_t) decl.fParameters.size());
607 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400608 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400609 emit += ", &" + decl.fName + "_name);";
610 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400611 }
612}
613
614void CPPCodeGenerator::writeSetting(const Setting& s) {
615 static constexpr const char* kPrefix = "sk_Args.";
616 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
617 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400618 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400619 } else {
620 this->write(s.fName.c_str());
621 }
622}
623
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400624bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400625 const Section* s = fSectionAndParameterHelper.getSection(name);
626 if (s) {
627 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400628 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400629 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400630 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400631}
632
633void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
634 if (p.fKind == ProgramElement::kSection_Kind) {
635 return;
636 }
637 if (p.fKind == ProgramElement::kVar_Kind) {
638 const VarDeclarations& decls = (const VarDeclarations&) p;
639 if (!decls.fVars.size()) {
640 return;
641 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000642 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400643 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
644 -1 != var.fModifiers.fLayout.fBuiltin) {
645 return;
646 }
647 }
648 INHERITED::writeProgramElement(p);
649}
650
651void CPPCodeGenerator::addUniform(const Variable& var) {
652 if (!needs_uniform_var(var)) {
653 return;
654 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400655 if (var.fModifiers.fLayout.fWhen.fLength) {
656 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400657 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400658 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700659 String name(var.fName);
Ethan Nicholas16464c32020-04-06 13:53:05 -0400660 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
661 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700662 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400663 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400664 this->write(" }\n");
665 }
666}
667
Ethan Nicholascd700e92018-08-24 16:43:57 -0400668void CPPCodeGenerator::writeInputVars() {
669}
670
Ethan Nicholas762466e2017-06-29 10:03:38 -0400671void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400672 for (const auto& p : fProgram) {
673 if (ProgramElement::kVar_Kind == p.fKind) {
674 const VarDeclarations& decls = (const VarDeclarations&) p;
675 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000676 VarDeclaration& decl = (VarDeclaration&) *raw;
677 if (is_private(*decl.fVar)) {
678 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
679 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400680 "fragmentProcessor variables must be declared 'in'");
681 return;
682 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500683 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000684 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
685 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500686 String(decl.fVar->fName).c_str(),
687 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400688 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
689 // An auto-tracked uniform in variable, so add a field to hold onto the prior
690 // state. Note that tracked variables must be uniform in's and that is validated
691 // before writePrivateVars() is called.
692 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
693 SkASSERT(mapper && mapper->supportsTracking());
694
695 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
696 // The member statement is different if the mapper reports a default value
697 if (mapper->defaultValue().size() > 0) {
698 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400699 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400700 mapper->defaultValue().c_str());
701 } else {
702 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400703 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400704 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400705 }
706 }
707 }
708 }
709}
710
711void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400712 for (const auto& p : fProgram) {
713 if (ProgramElement::kVar_Kind == p.fKind) {
714 const VarDeclarations& decls = (const VarDeclarations&) p;
715 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000716 VarDeclaration& decl = (VarDeclaration&) *raw;
717 if (is_private(*decl.fVar) && decl.fValue) {
718 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400719 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000720 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400721 fCPPMode = false;
722 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400723 }
724 }
725 }
726 }
727}
728
Ethan Nicholas82399462017-10-16 12:35:44 -0400729static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500730 const Type& type = var.fType.nonnullable();
731 return Type::kSampler_Kind != type.kind() &&
732 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400733}
734
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400735void CPPCodeGenerator::newExtraEmitCodeBlock() {
736 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
737 // cpp buffer is not null, and the cpp buffer is not the current output.
738 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
739
740 // Start a new block as an empty string
741 fExtraEmitCodeBlocks.push_back("");
742 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
743 // valid sksl and makes detection trivial.
744 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
745}
746
747void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
748 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
749 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
750 // Automatically add indentation and newline
751 currentBlock += " " + toAppend + "\n";
752}
753
754void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400755 if (fCPPBuffer == nullptr) {
756 // Not actually within writeEmitCode() so nothing to flush
757 return;
758 }
759
760 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
761
762 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400763 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400764 skslBuffer->reset();
765
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400766 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000767 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400768
769 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
770 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
771 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
772 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
773 // statement left off (minus the encountered token).
774 size_t i = 0;
775 int flushPoint = -1;
776 int tokenStart = -1;
777 while (i < sksl.size()) {
778 if (tokenStart >= 0) {
779 // Looking for the end of the token
780 if (sksl[i] == '}') {
781 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
782 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
783 String toFlush = String(sksl.c_str(), flushPoint + 1);
784 // writeCodeAppend automatically removes the format args that it consumed, so
785 // fFormatArgs will be in a valid state for any future sksl
786 this->writeCodeAppend(toFlush);
787
788 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
789 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
790 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
791 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
792 }
793
794 // Now reset the sksl buffer to start after the flush point, but remove the token.
795 String compacted = String(sksl.c_str() + flushPoint + 1,
796 tokenStart - flushPoint - 1);
797 if (i < sksl.size() - 1) {
798 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
799 }
800 sksl = compacted;
801
802 // And reset iteration
803 i = -1;
804 flushPoint = -1;
805 tokenStart = -1;
806 }
807 } else {
808 // Looking for the start of extra emit block tokens, and tracking when statements end
809 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
810 flushPoint = i;
811 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
812 // found an extra emit code block token
813 tokenStart = i++;
814 }
815 }
816 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000817 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400818
819 // Once we've gone through the sksl string to this point, there are no remaining extra emit
820 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400821 this->writeCodeAppend(sksl);
822
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400823 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400824 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400825 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400826}
827
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400828void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400829 if (!code.empty()) {
830 // Count % format specifiers.
831 size_t argCount = 0;
832 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400833 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400834 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400835 break;
836 }
837 if (code[index + 1] != '%') {
838 ++argCount;
839 }
840 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400841 }
John Stiles50819422020-06-18 13:00:38 -0400842
843 // Emit the code string.
844 this->writef(" fragBuilder->codeAppendf(\n"
845 "R\"SkSL(%s)SkSL\"\n", code.c_str());
846 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400847 this->writef(", %s", fFormatArgs[i].c_str());
848 }
849 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400850
John Stiles50819422020-06-18 13:00:38 -0400851 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
852 // removed from the list.
853 if (argCount > 0) {
854 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
855 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400856 }
857}
858
859String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
860 const String& cppVar) {
861 // To do this conversion, we temporarily switch the sksl output stream
862 // to an empty stringstream and reset the format args to empty.
863 OutputStream* oldSKSL = fOut;
864 StringStream exprBuffer;
865 fOut = &exprBuffer;
866
867 std::vector<String> oldArgs(fFormatArgs);
868 fFormatArgs.clear();
869
870 // Convert the argument expression into a format string and args
871 this->writeExpression(e, Precedence::kTopLevel_Precedence);
872 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400873 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400874
875 // After generating, restore the original output stream and format args
876 fFormatArgs = oldArgs;
877 fOut = oldSKSL;
878
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400879 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
880 // block tokens won't get handled. So we need to strip them from the expression and stick them
881 // to the end of the original sksl stream.
882 String exprFormat = "";
883 int tokenStart = -1;
884 for (size_t i = 0; i < expr.size(); i++) {
885 if (tokenStart >= 0) {
886 if (expr[i] == '}') {
887 // End of the token, so append the token to fOut
888 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
889 tokenStart = -1;
890 }
891 } else {
892 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
893 tokenStart = i++;
894 } else {
895 exprFormat += expr[i];
896 }
897 }
898 }
899
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400900 // Now build the final C++ code snippet from the format string and args
901 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400902 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400903 // This was a static expression, so we can simplify the input
904 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400905 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400906 } else if (newArgs.size() == 1 && exprFormat == "%s") {
907 // If the format expression is simply "%s", we can avoid an expensive call to printf.
908 // This happens fairly often in codegen so it is worth simplifying.
909 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400910 } else {
911 // String formatting must occur dynamically, so have the C++ declaration
912 // use SkStringPrintf with the format args that were accumulated
913 // when the expression was written.
914 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
915 for (size_t i = 0; i < newArgs.size(); i++) {
916 cppExpr += ", " + newArgs[i];
917 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400918 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400919 }
920 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400921}
922
Ethan Nicholas762466e2017-06-29 10:03:38 -0400923bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
924 this->write(" void emitCode(EmitArgs& args) override {\n"
925 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
926 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
927 " (void) _outer;\n",
928 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400929 for (const auto& p : fProgram) {
930 if (ProgramElement::kVar_Kind == p.fKind) {
931 const VarDeclarations& decls = (const VarDeclarations&) p;
932 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000933 VarDeclaration& decl = (VarDeclaration&) *raw;
934 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400935 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000936 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
937 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400938 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400939 " (void) %s;\n",
940 name, name, name);
941 }
942 }
943 }
944 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400945 this->writePrivateVarValues();
946 for (const auto u : uniforms) {
947 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400948 }
949 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400950
951 // Save original buffer as the CPP buffer for flushEmittedCode()
952 fCPPBuffer = fOut;
953 StringStream skslBuffer;
954 fOut = &skslBuffer;
955
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400956 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400957 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400958 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400959
960 // Then restore the original CPP buffer and close the function
961 fOut = fCPPBuffer;
962 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400963 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400964 return result;
965}
966
967void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
968 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400969 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
970 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400971 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
972 "const GrFragmentProcessor& _proc) override {\n",
973 pdman);
974 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400975 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400976 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400977 if (!wroteProcessor) {
978 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
979 wroteProcessor = true;
980 this->writef(" {\n");
981 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400982
983 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
984 SkASSERT(mapper);
985
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700986 String nameString(u->fName);
987 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400988
989 // Switches for setData behavior in the generated code
990 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
991 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
992 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
993
994 String uniformName = HCodeGenerator::FieldName(name) + "Var";
995
996 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
997 if (conditionalUniform) {
998 // Add a pre-check to make sure the uniform was emitted
999 // before trying to send any data to the GPU
1000 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
1001 indent += " ";
1002 }
1003
1004 String valueVar = "";
1005 if (needsValueDeclaration) {
1006 valueVar.appendf("%sValue", name);
1007 // Use AccessType since that will match the return type of _outer's public API.
1008 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1009 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001010 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001011 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001012 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001013 // Not tracked and the mapper only needs to use the value once
1014 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001015 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001016 }
1017
1018 if (isTracked) {
1019 SkASSERT(mapper->supportsTracking());
1020
1021 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1022 this->writef("%sif (%s) {\n"
1023 "%s %s;\n"
1024 "%s %s;\n"
1025 "%s}\n", indent.c_str(),
1026 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1027 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1028 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1029 } else {
1030 this->writef("%s%s;\n", indent.c_str(),
1031 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1032 }
1033
1034 if (conditionalUniform) {
1035 // Close the earlier precheck block
1036 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001037 }
1038 }
1039 }
1040 if (wroteProcessor) {
1041 this->writef(" }\n");
1042 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001043 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001044 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001045 for (const auto& p : fProgram) {
1046 if (ProgramElement::kVar_Kind == p.fKind) {
1047 const VarDeclarations& decls = (const VarDeclarations&) p;
John Stiles06f3d082020-06-04 11:07:21 -04001048 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
1049 const VarDeclaration& decl = static_cast<VarDeclaration&>(*raw);
1050 const Variable& variable = *decl.fVar;
1051 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001052 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001053 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001054 this->writef(" const GrSurfaceProxyView& %sView = "
1055 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001056 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001057 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001058 name, name);
1059 this->writef(" (void) %s;\n", name);
1060 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001061 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001062 this->writef(" UniformHandle& %s = %sVar;\n"
1063 " (void) %s;\n",
1064 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001065 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1066 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001067 if (!wroteProcessor) {
1068 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1069 fullName);
1070 wroteProcessor = true;
1071 }
John Stiles06f3d082020-06-04 11:07:21 -04001072
1073 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1074 this->writef(" auto %s = _outer.%s;\n"
1075 " (void) %s;\n",
1076 name, name, name);
1077 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001078 }
1079 }
1080 }
1081 }
1082 this->writeSection(SET_DATA_SECTION);
1083 }
1084 this->write(" }\n");
1085}
1086
Brian Salomonf7dcd762018-07-30 14:48:15 -04001087void CPPCodeGenerator::writeOnTextureSampler() {
1088 bool foundSampler = false;
1089 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1090 if (param->fType.kind() == Type::kSampler_Kind) {
1091 if (!foundSampler) {
1092 this->writef(
1093 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1094 "index) const {\n",
1095 fFullName.c_str());
1096 this->writef(" return IthTextureSampler(index, %s",
1097 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1098 foundSampler = true;
1099 } else {
1100 this->writef(", %s",
1101 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1102 }
1103 }
1104 }
1105 if (foundSampler) {
1106 this->write(");\n}\n");
1107 }
1108}
1109
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001110void CPPCodeGenerator::writeClone() {
1111 if (!this->writeSection(CLONE_SECTION)) {
1112 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001113 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1114 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001115 }
1116 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001117 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1118 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001119 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
1120 for (size_t i = 0; i < transforms.size(); ++i) {
1121 const Section& s = *transforms[i];
1122 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1123 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
1124 }
John Stiles06f3d082020-06-04 11:07:21 -04001125 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001126 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001127 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001128 this->writef("\n, %s(src.%s)",
1129 fieldName.c_str(),
1130 fieldName.c_str());
1131 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001132 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001133 this->writef(" {\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001134 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001135 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1136 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001137 ++samplerCount;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001138 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1139 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1140 if (param->fType.kind() == Type::kNullable_Kind) {
John Stiles88183902020-06-10 16:40:38 -04001141 this->writef(" if (src.%s_index >= 0) {\n", fieldName.c_str());
Brian Salomonb243b432020-02-20 14:41:47 -05001142 } else {
1143 this->write(" {\n");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001144 }
John Stiles3779f442020-06-15 10:48:49 -04001145 this->writef(" %s_index = this->cloneAndRegisterChildProcessor("
1146 "src.childProcessor(src.%s_index));\n"
1147 " }\n",
1148 fieldName.c_str(), fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001149 }
1150 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001151 if (samplerCount) {
1152 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1153 }
Ethan Nicholas929a6812018-08-06 14:56:59 -04001154 for (size_t i = 0; i < transforms.size(); ++i) {
1155 const Section& s = *transforms[i];
1156 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1157 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001158 }
1159 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001160 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1161 fFullName.c_str());
1162 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1163 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001164 this->write("}\n");
1165 }
1166}
1167
Ethan Nicholas762466e2017-06-29 10:03:38 -04001168void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001169 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1170 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001171 this->writef(
1172 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1173 "#if GR_TEST_UTILS\n"
1174 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1175 fFullName.c_str(),
1176 fFullName.c_str(),
1177 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001178 this->writeSection(TEST_CODE_SECTION);
1179 this->write("}\n"
1180 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001181 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001182}
1183
1184void CPPCodeGenerator::writeGetKey() {
1185 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1186 "GrProcessorKeyBuilder* b) const {\n",
1187 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001188 for (const auto& p : fProgram) {
1189 if (ProgramElement::kVar_Kind == p.fKind) {
1190 const VarDeclarations& decls = (const VarDeclarations&) p;
1191 for (const auto& raw : decls.fVars) {
1192 const VarDeclaration& decl = (VarDeclaration&) *raw;
1193 const Variable& var = *decl.fVar;
1194 String nameString(var.fName);
1195 const char* name = nameString.c_str();
1196 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1197 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1198 fErrors.error(var.fOffset,
1199 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001200 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001201 switch (var.fModifiers.fLayout.fKey) {
1202 case Layout::kKey_Key:
1203 if (is_private(var)) {
1204 this->writef("%s %s =",
1205 HCodeGenerator::FieldType(fContext, var.fType,
1206 var.fModifiers.fLayout).c_str(),
1207 String(var.fName).c_str());
1208 if (decl.fValue) {
1209 fCPPMode = true;
1210 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1211 fCPPMode = false;
1212 } else {
1213 this->writef("%s", default_value(var).c_str());
1214 }
1215 this->write(";\n");
1216 }
1217 if (var.fModifiers.fLayout.fWhen.fLength) {
1218 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1219 }
1220 if (var.fType == *fContext.fFloat4x4_Type) {
1221 ABORT("no automatic key handling for float4x4\n");
1222 } else if (var.fType == *fContext.fFloat2_Type) {
1223 this->writef(" b->add32(%s.fX);\n",
1224 HCodeGenerator::FieldName(name).c_str());
1225 this->writef(" b->add32(%s.fY);\n",
1226 HCodeGenerator::FieldName(name).c_str());
1227 } else if (var.fType == *fContext.fFloat4_Type) {
1228 this->writef(" b->add32(%s.x());\n",
1229 HCodeGenerator::FieldName(name).c_str());
1230 this->writef(" b->add32(%s.y());\n",
1231 HCodeGenerator::FieldName(name).c_str());
1232 this->writef(" b->add32(%s.width());\n",
1233 HCodeGenerator::FieldName(name).c_str());
1234 this->writef(" b->add32(%s.height());\n",
1235 HCodeGenerator::FieldName(name).c_str());
1236 } else if (var.fType == *fContext.fHalf4_Type) {
1237 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1238 HCodeGenerator::FieldName(name).c_str());
1239 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1240 HCodeGenerator::FieldName(name).c_str());
1241 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1242 HCodeGenerator::FieldName(name).c_str());
1243 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1244 HCodeGenerator::FieldName(name).c_str());
1245 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1246 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
1247 } else {
1248 this->writef(" b->add32((int32_t) %s);\n",
1249 HCodeGenerator::FieldName(name).c_str());
1250 }
1251 if (var.fModifiers.fLayout.fWhen.fLength) {
1252 this->write("}");
1253 }
1254 break;
1255 case Layout::kIdentity_Key:
1256 if (var.fType.kind() != Type::kMatrix_Kind) {
1257 fErrors.error(var.fOffset,
1258 "layout(key=identity) requires matrix type");
1259 }
1260 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1261 HCodeGenerator::FieldName(name).c_str());
1262 break;
1263 case Layout::kNo_Key:
1264 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001265 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001266 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001267 }
1268 }
1269 this->write("}\n");
1270}
1271
1272bool CPPCodeGenerator::generateCode() {
1273 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001274 for (const auto& p : fProgram) {
1275 if (ProgramElement::kVar_Kind == p.fKind) {
1276 const VarDeclarations& decls = (const VarDeclarations&) p;
1277 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001278 VarDeclaration& decl = (VarDeclaration&) *raw;
1279 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1280 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1281 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001282 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001283
1284 if (is_uniform_in(*decl.fVar)) {
1285 // Validate the "uniform in" declarations to make sure they are fully supported,
1286 // instead of generating surprising C++
1287 const UniformCTypeMapper* mapper =
1288 UniformCTypeMapper::Get(fContext, *decl.fVar);
1289 if (mapper == nullptr) {
1290 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1291 + "'s type is not supported for use as a 'uniform in'");
1292 return false;
1293 }
1294 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1295 if (!mapper->supportsTracking()) {
1296 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1297 + "'s type does not support state tracking");
1298 return false;
1299 }
1300 }
1301
1302 } else {
1303 // If it's not a uniform_in, it's an error to be tracked
1304 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1305 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1306 return false;
1307 }
1308 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001309 }
1310 }
1311 }
1312 const char* baseName = fName.c_str();
1313 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001314 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001315 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001316 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001317 this->writeSection(CPP_SECTION);
Greg Daniel456f9b52020-03-05 19:14:18 +00001318 this->writef("#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001319 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1320 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1321 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1322 "#include \"src/sksl/SkSLCPP.h\"\n"
1323 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001324 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1325 "public:\n"
1326 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001327 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001328 bool result = this->writeEmitCode(uniforms);
1329 this->write("private:\n");
1330 this->writeSetData(uniforms);
1331 this->writePrivateVars();
1332 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001333 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001334 this->writef(" UniformHandle %sVar;\n",
1335 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001336 }
1337 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001338 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001339 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001340 this->writef(" UniformHandle %sVar;\n",
1341 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001342 }
1343 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001344 this->writef("};\n"
1345 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1346 " return new GrGLSL%s();\n"
1347 "}\n",
1348 fullName, baseName);
1349 this->writeGetKey();
1350 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1351 " const %s& that = other.cast<%s>();\n"
1352 " (void) that;\n",
1353 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001354 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001355 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001356 continue;
1357 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001358 String nameString(param->fName);
1359 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001360 this->writef(" if (%s != that.%s) return false;\n",
1361 HCodeGenerator::FieldName(name).c_str(),
1362 HCodeGenerator::FieldName(name).c_str());
1363 }
1364 this->write(" return true;\n"
1365 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001366 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001367 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001368 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001369 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001370
Ethan Nicholas762466e2017-06-29 10:03:38 -04001371 result &= 0 == fErrors.errorCount();
1372 return result;
1373}
1374
1375} // namespace