blob: 090c7ba3e71fd3d70aaa75d7233a63caa54212eb [file] [log] [blame]
ethannicholasf789b382016-08-03 12:43:36 -07001/*
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 */
Greg Daniel64773e62016-11-22 09:44:03 -05007
ethannicholasf789b382016-08-03 12:43:36 -07008#include "SkSLGLSLCodeGenerator.h"
9
Ethan Nicholas941e7e22016-12-12 15:33:30 -050010#include "SkSLCompiler.h"
ethannicholasf789b382016-08-03 12:43:36 -070011#include "ir/SkSLExpressionStatement.h"
12#include "ir/SkSLExtension.h"
13#include "ir/SkSLIndexExpression.h"
ethannicholas5961bc92016-10-12 06:39:56 -070014#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040015#include "ir/SkSLNop.h"
ethannicholasf789b382016-08-03 12:43:36 -070016#include "ir/SkSLVariableReference.h"
17
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -040018#ifndef SKSL_STANDALONE
19#include "SkOnce.h"
20#endif
21
ethannicholasf789b382016-08-03 12:43:36 -070022namespace SkSL {
23
24void GLSLCodeGenerator::write(const char* s) {
25 if (s[0] == 0) {
26 return;
27 }
28 if (fAtLineStart) {
29 for (int i = 0; i < fIndentation; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -050030 fOut->writeText(" ");
ethannicholasf789b382016-08-03 12:43:36 -070031 }
32 }
Ethan Nicholas9e1138d2016-11-21 10:39:35 -050033 fOut->writeText(s);
ethannicholasf789b382016-08-03 12:43:36 -070034 fAtLineStart = false;
35}
36
37void GLSLCodeGenerator::writeLine(const char* s) {
38 this->write(s);
Ethan Nicholas762466e2017-06-29 10:03:38 -040039 fOut->writeText(fLineEnding);
ethannicholasf789b382016-08-03 12:43:36 -070040 fAtLineStart = true;
41}
42
Ethan Nicholas0df1b042017-03-31 13:56:23 -040043void GLSLCodeGenerator::write(const String& s) {
ethannicholasf789b382016-08-03 12:43:36 -070044 this->write(s.c_str());
45}
46
Ethan Nicholas5b5f0962017-09-11 13:50:14 -070047void GLSLCodeGenerator::write(StringFragment s) {
48 if (!s.fLength) {
49 return;
50 }
51 if (fAtLineStart) {
52 for (int i = 0; i < fIndentation; i++) {
53 fOut->writeText(" ");
54 }
55 }
56 fOut->write(s.fChars, s.fLength);
57 fAtLineStart = false;
58}
59
Ethan Nicholas0df1b042017-03-31 13:56:23 -040060void GLSLCodeGenerator::writeLine(const String& s) {
ethannicholasf789b382016-08-03 12:43:36 -070061 this->writeLine(s.c_str());
62}
63
64void GLSLCodeGenerator::writeLine() {
65 this->writeLine("");
66}
67
Ethan Nicholas88f6d372018-07-27 10:03:46 -040068void GLSLCodeGenerator::writeExtension(const String& name) {
69 this->writeExtension(name, true);
70}
71
72void GLSLCodeGenerator::writeExtension(const String& name, bool require) {
73 fExtensions.writeText("#extension ");
74 fExtensions.write(name.c_str(), name.length());
75 fExtensions.writeText(require ? " : require\n" : " : enable\n");
ethannicholasf789b382016-08-03 12:43:36 -070076}
77
Ethan Nicholasf7b88202017-09-18 14:10:39 -040078bool GLSLCodeGenerator::usesPrecisionModifiers() const {
79 return fProgram.fSettings.fCaps->usesPrecisionModifiers();
80}
81
82String GLSLCodeGenerator::getTypeName(const Type& type) {
83 switch (type.kind()) {
84 case Type::kVector_Kind: {
85 Type component = type.componentType();
86 String result;
87 if (component == *fContext.fFloat_Type || component == *fContext.fHalf_Type) {
88 result = "vec";
89 }
90 else if (component == *fContext.fDouble_Type) {
91 result = "dvec";
92 }
Ethan Nicholase1f55022019-02-05 17:17:40 -050093 else if (component.isSigned()) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -040094 result = "ivec";
95 }
Ethan Nicholase1f55022019-02-05 17:17:40 -050096 else if (component.isUnsigned()) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -040097 result = "uvec";
98 }
99 else if (component == *fContext.fBool_Type) {
100 result = "bvec";
101 }
102 else {
103 ABORT("unsupported vector type");
104 }
105 result += to_string(type.columns());
106 return result;
107 }
108 case Type::kMatrix_Kind: {
109 String result;
110 Type component = type.componentType();
111 if (component == *fContext.fFloat_Type || component == *fContext.fHalf_Type) {
112 result = "mat";
113 }
114 else if (component == *fContext.fDouble_Type) {
115 result = "dmat";
116 }
117 else {
118 ABORT("unsupported matrix type");
119 }
120 result += to_string(type.columns());
121 if (type.columns() != type.rows()) {
122 result += "x";
123 result += to_string(type.rows());
124 }
125 return result;
126 }
127 case Type::kArray_Kind: {
128 String result = this->getTypeName(type.componentType()) + "[";
129 if (type.columns() != -1) {
130 result += to_string(type.columns());
131 }
132 result += "]";
133 return result;
134 }
135 case Type::kScalar_Kind: {
136 if (type == *fContext.fHalf_Type) {
137 return "float";
138 }
139 else if (type == *fContext.fShort_Type) {
140 return "int";
141 }
142 else if (type == *fContext.fUShort_Type) {
143 return "uint";
144 }
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400145 else if (type == *fContext.fByte_Type) {
146 return "int";
147 }
148 else if (type == *fContext.fUByte_Type) {
149 return "uint";
150 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400151 else {
152 return type.name();
153 }
154 break;
155 }
156 default:
157 return type.name();
158 }
159}
160
ethannicholasf789b382016-08-03 12:43:36 -0700161void GLSLCodeGenerator::writeType(const Type& type) {
162 if (type.kind() == Type::kStruct_Kind) {
163 for (const Type* search : fWrittenStructs) {
164 if (*search == type) {
165 // already written
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700166 this->write(type.fName);
ethannicholasf789b382016-08-03 12:43:36 -0700167 return;
168 }
169 }
170 fWrittenStructs.push_back(&type);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700171 this->write("struct ");
172 this->write(type.fName);
173 this->writeLine(" {");
ethannicholasf789b382016-08-03 12:43:36 -0700174 fIndentation++;
175 for (const auto& f : type.fields()) {
ethannicholas5961bc92016-10-12 06:39:56 -0700176 this->writeModifiers(f.fModifiers, false);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400177 this->writeTypePrecision(*f.fType);
ethannicholasf789b382016-08-03 12:43:36 -0700178 // sizes (which must be static in structs) are part of the type name here
ethannicholas0730be72016-09-01 07:59:02 -0700179 this->writeType(*f.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700180 this->write(" ");
181 this->write(f.fName);
182 this->writeLine(";");
ethannicholasf789b382016-08-03 12:43:36 -0700183 }
184 fIndentation--;
Ethan Nicholas19671772016-11-28 16:30:17 -0500185 this->write("}");
ethannicholasf789b382016-08-03 12:43:36 -0700186 } else {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400187 this->write(this->getTypeName(type));
ethannicholasf789b382016-08-03 12:43:36 -0700188 }
189}
190
191void GLSLCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
192 switch (expr.fKind) {
193 case Expression::kBinary_Kind:
194 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
195 break;
196 case Expression::kBoolLiteral_Kind:
197 this->writeBoolLiteral((BoolLiteral&) expr);
198 break;
199 case Expression::kConstructor_Kind:
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400200 this->writeConstructor((Constructor&) expr, parentPrecedence);
ethannicholasf789b382016-08-03 12:43:36 -0700201 break;
202 case Expression::kIntLiteral_Kind:
203 this->writeIntLiteral((IntLiteral&) expr);
204 break;
205 case Expression::kFieldAccess_Kind:
206 this->writeFieldAccess(((FieldAccess&) expr));
207 break;
208 case Expression::kFloatLiteral_Kind:
209 this->writeFloatLiteral(((FloatLiteral&) expr));
210 break;
211 case Expression::kFunctionCall_Kind:
212 this->writeFunctionCall((FunctionCall&) expr);
213 break;
214 case Expression::kPrefix_Kind:
215 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
216 break;
217 case Expression::kPostfix_Kind:
218 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
219 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400220 case Expression::kSetting_Kind:
221 this->writeSetting((Setting&) expr);
222 break;
ethannicholasf789b382016-08-03 12:43:36 -0700223 case Expression::kSwizzle_Kind:
224 this->writeSwizzle((Swizzle&) expr);
225 break;
226 case Expression::kVariableReference_Kind:
227 this->writeVariableReference((VariableReference&) expr);
228 break;
229 case Expression::kTernary_Kind:
230 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
231 break;
232 case Expression::kIndex_Kind:
233 this->writeIndexExpression((IndexExpression&) expr);
234 break;
235 default:
236 ABORT("unsupported expression: %s", expr.description().c_str());
237 }
238}
239
ethannicholas5961bc92016-10-12 06:39:56 -0700240static bool is_abs(Expression& expr) {
241 if (expr.fKind != Expression::kFunctionCall_Kind) {
242 return false;
243 }
244 return ((FunctionCall&) expr).fFunction.fName == "abs";
245}
246
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500247// turns min(abs(x), y) into ((tmpVar1 = abs(x)) < (tmpVar2 = y) ? tmpVar1 : tmpVar2) to avoid a
ethannicholas5961bc92016-10-12 06:39:56 -0700248// Tegra3 compiler bug.
249void GLSLCodeGenerator::writeMinAbsHack(Expression& absExpr, Expression& otherExpr) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400250 SkASSERT(!fProgram.fSettings.fCaps->canUseMinAndAbsTogether());
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400251 String tmpVar1 = "minAbsHackVar" + to_string(fVarCount++);
252 String tmpVar2 = "minAbsHackVar" + to_string(fVarCount++);
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400253 this->fFunctionHeader += String(" ") + this->getTypePrecision(absExpr.fType) +
254 this->getTypeName(absExpr.fType) + " " + tmpVar1 + ";\n";
255 this->fFunctionHeader += String(" ") + this->getTypePrecision(otherExpr.fType) +
256 this->getTypeName(otherExpr.fType) + " " + tmpVar2 + ";\n";
ethannicholas5961bc92016-10-12 06:39:56 -0700257 this->write("((" + tmpVar1 + " = ");
258 this->writeExpression(absExpr, kTopLevel_Precedence);
259 this->write(") < (" + tmpVar2 + " = ");
260 this->writeExpression(otherExpr, kAssignment_Precedence);
261 this->write(") ? " + tmpVar1 + " : " + tmpVar2 + ")");
262}
263
Ethan Nicholas6e6525c2018-01-03 17:03:56 -0500264void GLSLCodeGenerator::writeInverseSqrtHack(const Expression& x) {
265 this->write("(1.0 / sqrt(");
266 this->writeExpression(x, kTopLevel_Precedence);
267 this->write("))");
268}
269
270void GLSLCodeGenerator::writeDeterminantHack(const Expression& mat) {
271 String name;
272 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
273 name = "_determinant2";
274 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
275 fWrittenIntrinsics.insert(name);
276 fExtraFunctions.writeText((
277 "float " + name + "(mat2 m) {"
278 " return m[0][0] * m[1][1] - m[0][1] * m[1][0];"
279 "}"
280 ).c_str());
281 }
282 }
283 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
284 name = "_determinant3";
285 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
286 fWrittenIntrinsics.insert(name);
287 fExtraFunctions.writeText((
288 "float " + name + "(mat3 m) {"
289 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
290 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
291 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
292 " float b01 = a22 * a11 - a12 * a21;"
293 " float b11 = -a22 * a10 + a12 * a20;"
294 " float b21 = a21 * a10 - a11 * a20;"
295 " return a00 * b01 + a01 * b11 + a02 * b21;"
296 "}"
297 ).c_str());
298 }
299 }
300 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
301 name = "_determinant3";
302 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
303 fWrittenIntrinsics.insert(name);
304 fExtraFunctions.writeText((
305 "mat4 " + name + "(mat4 m) {"
306 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
307 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
308 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
309 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
310 " float b00 = a00 * a11 - a01 * a10;"
311 " float b01 = a00 * a12 - a02 * a10;"
312 " float b02 = a00 * a13 - a03 * a10;"
313 " float b03 = a01 * a12 - a02 * a11;"
314 " float b04 = a01 * a13 - a03 * a11;"
315 " float b05 = a02 * a13 - a03 * a12;"
316 " float b06 = a20 * a31 - a21 * a30;"
317 " float b07 = a20 * a32 - a22 * a30;"
318 " float b08 = a20 * a33 - a23 * a30;"
319 " float b09 = a21 * a32 - a22 * a31;"
320 " float b10 = a21 * a33 - a23 * a31;"
321 " float b11 = a22 * a33 - a23 * a32;"
322 " return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;"
323 "}"
324 ).c_str());
325 }
326 }
327 else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400328 SkASSERT(false);
Ethan Nicholas6e6525c2018-01-03 17:03:56 -0500329 }
330 this->write(name + "(");
331 this->writeExpression(mat, kTopLevel_Precedence);
332 this->write(")");
333}
334
335void GLSLCodeGenerator::writeInverseHack(const Expression& mat) {
336 String name;
337 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
338 name = "_inverse2";
339 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
340 fWrittenIntrinsics.insert(name);
341 fExtraFunctions.writeText((
342 "mat2 " + name + "(mat2 m) {"
343 " return mat2(m[1][1], -m[0][1], -m[1][0], m[0][0]) / "
344 "(m[0][0] * m[1][1] - m[0][1] * m[1][0]);"
345 "}"
346 ).c_str());
347 }
348 }
349 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
350 name = "_inverse3";
351 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
352 fWrittenIntrinsics.insert(name);
353 fExtraFunctions.writeText((
354 "mat3 " + name + "(mat3 m) {"
355 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
356 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
357 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
358 " float b01 = a22 * a11 - a12 * a21;"
359 " float b11 = -a22 * a10 + a12 * a20;"
360 " float b21 = a21 * a10 - a11 * a20;"
361 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
362 " return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
363 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
364 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;"
365 "}"
366 ).c_str());
367 }
368 }
369 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
370 name = "_inverse4";
371 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
372 fWrittenIntrinsics.insert(name);
373 fExtraFunctions.writeText((
374 "mat4 " + name + "(mat4 m) {"
375 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
376 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
377 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
378 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
379 " float b00 = a00 * a11 - a01 * a10;"
380 " float b01 = a00 * a12 - a02 * a10;"
381 " float b02 = a00 * a13 - a03 * a10;"
382 " float b03 = a01 * a12 - a02 * a11;"
383 " float b04 = a01 * a13 - a03 * a11;"
384 " float b05 = a02 * a13 - a03 * a12;"
385 " float b06 = a20 * a31 - a21 * a30;"
386 " float b07 = a20 * a32 - a22 * a30;"
387 " float b08 = a20 * a33 - a23 * a30;"
388 " float b09 = a21 * a32 - a22 * a31;"
389 " float b10 = a21 * a33 - a23 * a31;"
390 " float b11 = a22 * a33 - a23 * a32;"
391 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
392 " b04 * b07 + b05 * b06;"
393 " return mat4("
394 " a11 * b11 - a12 * b10 + a13 * b09,"
395 " a02 * b10 - a01 * b11 - a03 * b09,"
396 " a31 * b05 - a32 * b04 + a33 * b03,"
397 " a22 * b04 - a21 * b05 - a23 * b03,"
398 " a12 * b08 - a10 * b11 - a13 * b07,"
399 " a00 * b11 - a02 * b08 + a03 * b07,"
400 " a32 * b02 - a30 * b05 - a33 * b01,"
401 " a20 * b05 - a22 * b02 + a23 * b01,"
402 " a10 * b10 - a11 * b08 + a13 * b06,"
403 " a01 * b08 - a00 * b10 - a03 * b06,"
404 " a30 * b04 - a31 * b02 + a33 * b00,"
405 " a21 * b02 - a20 * b04 - a23 * b00,"
406 " a11 * b07 - a10 * b09 - a12 * b06,"
407 " a00 * b09 - a01 * b07 + a02 * b06,"
408 " a31 * b01 - a30 * b03 - a32 * b00,"
409 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
410 "}"
411 ).c_str());
412 }
413 }
414 else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400415 SkASSERT(false);
Ethan Nicholas6e6525c2018-01-03 17:03:56 -0500416 }
417 this->write(name + "(");
418 this->writeExpression(mat, kTopLevel_Precedence);
419 this->write(")");
420}
421
422void GLSLCodeGenerator::writeTransposeHack(const Expression& mat) {
423 String name = "transpose" + to_string(mat.fType.columns()) + to_string(mat.fType.rows());
424 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
425 fWrittenIntrinsics.insert(name);
426 String type = this->getTypeName(mat.fType);
427 const Type& base = mat.fType.componentType();
428 String transposed = this->getTypeName(base.toCompound(fContext,
429 mat.fType.rows(),
430 mat.fType.columns()));
431 fExtraFunctions.writeText((transposed + " " + name + "(" + type + " m) {\nreturn " +
432 transposed + "(").c_str());
433 const char* separator = "";
434 for (int row = 0; row < mat.fType.rows(); ++row) {
435 for (int column = 0; column < mat.fType.columns(); ++column) {
436 fExtraFunctions.writeText(separator);
437 fExtraFunctions.writeText(("m[" + to_string(column) + "][" + to_string(row) +
438 "]").c_str());
439 separator = ", ";
440 }
441 }
442 fExtraFunctions.writeText("); }");
443 }
444 this->write(name + "(");
445 this->writeExpression(mat, kTopLevel_Precedence);
446 this->write(")");
447}
448
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400449std::unordered_map<StringFragment, GLSLCodeGenerator::FunctionClass>*
450 GLSLCodeGenerator::fFunctionClasses = nullptr;
451
ethannicholasf789b382016-08-03 12:43:36 -0700452void GLSLCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400453#ifdef SKSL_STANDALONE
454 if (!fFunctionClasses) {
455#else
456 static SkOnce once;
457 once([] {
458#endif
459 fFunctionClasses = new std::unordered_map<StringFragment, FunctionClass>();
Adrienne Walker92b161f2018-08-22 10:41:52 -0700460 (*fFunctionClasses)["abs"] = FunctionClass::kAbs;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400461 (*fFunctionClasses)["atan"] = FunctionClass::kAtan;
462 (*fFunctionClasses)["determinant"] = FunctionClass::kDeterminant;
463 (*fFunctionClasses)["dFdx"] = FunctionClass::kDerivative;
464 (*fFunctionClasses)["dFdy"] = FunctionClass::kDerivative;
Chris Dalton09212192018-11-13 15:07:24 -0500465 (*fFunctionClasses)["fwidth"] = FunctionClass::kDerivative;
Chris Daltona7086182018-11-16 09:33:43 -0500466 (*fFunctionClasses)["fma"] = FunctionClass::kFMA;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400467 (*fFunctionClasses)["fract"] = FunctionClass::kFract;
468 (*fFunctionClasses)["inverse"] = FunctionClass::kInverse;
469 (*fFunctionClasses)["inverseSqrt"] = FunctionClass::kInverseSqrt;
470 (*fFunctionClasses)["min"] = FunctionClass::kMin;
Adrienne Walker2f4c09b2018-08-22 16:04:57 -0700471 (*fFunctionClasses)["pow"] = FunctionClass::kPow;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400472 (*fFunctionClasses)["saturate"] = FunctionClass::kSaturate;
473 (*fFunctionClasses)["texture"] = FunctionClass::kTexture;
474 (*fFunctionClasses)["transpose"] = FunctionClass::kTranspose;
ethannicholas5961bc92016-10-12 06:39:56 -0700475 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400476#ifndef SKSL_STANDALONE
477 );
478#endif
479 const auto found = c.fFunction.fBuiltin ? fFunctionClasses->find(c.fFunction.fName) :
480 fFunctionClasses->end();
Brian Osman8a83ca42018-02-12 14:32:17 -0500481 bool isTextureFunctionWithBias = false;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400482 bool nameWritten = false;
483 if (found != fFunctionClasses->end()) {
484 switch (found->second) {
Adrienne Walker92b161f2018-08-22 10:41:52 -0700485 case FunctionClass::kAbs: {
486 if (!fProgram.fSettings.fCaps->emulateAbsIntFunction())
487 break;
488 SkASSERT(c.fArguments.size() == 1);
489 if (c.fArguments[0]->fType != *fContext.fInt_Type)
490 break;
491 // abs(int) on Intel OSX is incorrect, so emulate it:
492 String name = "_absemulation";
493 this->write(name);
494 nameWritten = true;
495 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
496 fWrittenIntrinsics.insert(name);
497 fExtraFunctions.writeText((
498 "int " + name + "(int x) {\n"
499 " return x * sign(x);\n"
500 "}\n"
501 ).c_str());
502 }
503 break;
504 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400505 case FunctionClass::kAtan:
506 if (fProgram.fSettings.fCaps->mustForceNegatedAtanParamToFloat() &&
507 c.fArguments.size() == 2 &&
508 c.fArguments[1]->fKind == Expression::kPrefix_Kind) {
509 const PrefixExpression& p = (PrefixExpression&) *c.fArguments[1];
510 if (p.fOperator == Token::MINUS) {
511 this->write("atan(");
512 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
513 this->write(", -1.0 * ");
514 this->writeExpression(*p.fOperand, kMultiplicative_Precedence);
515 this->write(")");
516 return;
517 }
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500518 }
519 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400520 case FunctionClass::kDerivative:
521 if (!fFoundDerivatives &&
522 fProgram.fSettings.fCaps->shaderDerivativeExtensionString()) {
523 SkASSERT(fProgram.fSettings.fCaps->shaderDerivativeSupport());
524 this->writeExtension(fProgram.fSettings.fCaps->shaderDerivativeExtensionString());
525 fFoundDerivatives = true;
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500526 }
527 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400528 case FunctionClass::kDeterminant:
529 if (fProgram.fSettings.fCaps->generation() < k150_GrGLSLGeneration) {
530 SkASSERT(c.fArguments.size() == 1);
531 this->writeDeterminantHack(*c.fArguments[0]);
532 return;
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500533 }
534 break;
Chris Daltona7086182018-11-16 09:33:43 -0500535 case FunctionClass::kFMA:
536 if (!fProgram.fSettings.fCaps->builtinFMASupport()) {
537 SkASSERT(c.fArguments.size() == 3);
538 this->write("((");
539 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
540 this->write(") * (");
541 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
542 this->write(") + (");
543 this->writeExpression(*c.fArguments[2], kSequence_Precedence);
544 this->write("))");
545 return;
546 }
547 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400548 case FunctionClass::kFract:
549 if (!fProgram.fSettings.fCaps->canUseFractForNegativeValues()) {
550 SkASSERT(c.fArguments.size() == 1);
551 this->write("(0.5 - sign(");
552 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
553 this->write(") * (0.5 - fract(abs(");
554 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
555 this->write("))))");
556 return;
557 }
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500558 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400559 case FunctionClass::kInverse:
560 if (fProgram.fSettings.fCaps->generation() < k140_GrGLSLGeneration) {
561 SkASSERT(c.fArguments.size() == 1);
562 this->writeInverseHack(*c.fArguments[0]);
563 return;
564 }
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500565 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400566 case FunctionClass::kInverseSqrt:
567 if (fProgram.fSettings.fCaps->generation() < k130_GrGLSLGeneration) {
568 SkASSERT(c.fArguments.size() == 1);
569 this->writeInverseSqrtHack(*c.fArguments[0]);
570 return;
571 }
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500572 break;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400573 case FunctionClass::kMin:
574 if (!fProgram.fSettings.fCaps->canUseMinAndAbsTogether()) {
575 SkASSERT(c.fArguments.size() == 2);
576 if (is_abs(*c.fArguments[0])) {
577 this->writeMinAbsHack(*c.fArguments[0], *c.fArguments[1]);
578 return;
579 }
580 if (is_abs(*c.fArguments[1])) {
581 // note that this violates the GLSL left-to-right evaluation semantics.
582 // I doubt it will ever end up mattering, but it's worth calling out.
583 this->writeMinAbsHack(*c.fArguments[1], *c.fArguments[0]);
584 return;
585 }
586 }
587 break;
Adrienne Walker2f4c09b2018-08-22 16:04:57 -0700588 case FunctionClass::kPow:
589 if (!fProgram.fSettings.fCaps->removePowWithConstantExponent()) {
590 break;
591 }
592 // pow(x, y) on some NVIDIA drivers causes crashes if y is a
593 // constant. It's hard to tell what constitutes "constant" here
594 // so just replace in all cases.
595
596 // Change pow(x, y) into exp2(y * log2(x))
597 this->write("exp2(");
598 this->writeExpression(*c.fArguments[1], kMultiplicative_Precedence);
599 this->write(" * log2(");
600 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
601 this->write("))");
602 return;
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400603 case FunctionClass::kSaturate:
604 SkASSERT(c.fArguments.size() == 1);
605 this->write("clamp(");
606 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
607 this->write(", 0.0, 1.0)");
608 return;
609 case FunctionClass::kTexture: {
610 const char* dim = "";
611 bool proj = false;
612 switch (c.fArguments[0]->fType.dimensions()) {
613 case SpvDim1D:
614 dim = "1D";
615 isTextureFunctionWithBias = true;
616 if (c.fArguments[1]->fType == *fContext.fFloat_Type) {
617 proj = false;
618 } else {
619 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
620 proj = true;
621 }
622 break;
623 case SpvDim2D:
624 dim = "2D";
625 if (c.fArguments[0]->fType != *fContext.fSamplerExternalOES_Type) {
626 isTextureFunctionWithBias = true;
627 }
628 if (c.fArguments[1]->fType == *fContext.fFloat2_Type) {
629 proj = false;
630 } else {
631 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat3_Type);
632 proj = true;
633 }
634 break;
635 case SpvDim3D:
636 dim = "3D";
637 isTextureFunctionWithBias = true;
638 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
639 proj = false;
640 } else {
641 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat4_Type);
642 proj = true;
643 }
644 break;
645 case SpvDimCube:
646 dim = "Cube";
647 isTextureFunctionWithBias = true;
648 proj = false;
649 break;
650 case SpvDimRect:
651 dim = "Rect";
652 proj = false;
653 break;
654 case SpvDimBuffer:
655 SkASSERT(false); // doesn't exist
656 dim = "Buffer";
657 proj = false;
658 break;
659 case SpvDimSubpassData:
660 SkASSERT(false); // doesn't exist
661 dim = "SubpassData";
662 proj = false;
663 break;
664 }
665 this->write("texture");
666 if (fProgram.fSettings.fCaps->generation() < k130_GrGLSLGeneration) {
667 this->write(dim);
668 }
669 if (proj) {
670 this->write("Proj");
671 }
672 nameWritten = true;
673 break;
674 }
675 case FunctionClass::kTranspose:
676 if (fProgram.fSettings.fCaps->generation() < k130_GrGLSLGeneration) {
677 SkASSERT(c.fArguments.size() == 1);
678 this->writeTransposeHack(*c.fArguments[0]);
679 return;
680 }
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500681 break;
682 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -0400683 }
684 if (!nameWritten) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500685 this->write(c.fFunction.fName);
686 }
687 this->write("(");
ethannicholasf789b382016-08-03 12:43:36 -0700688 const char* separator = "";
689 for (const auto& arg : c.fArguments) {
690 this->write(separator);
691 separator = ", ";
692 this->writeExpression(*arg, kSequence_Precedence);
693 }
Brian Osman8a83ca42018-02-12 14:32:17 -0500694 if (fProgram.fSettings.fSharpenTextures && isTextureFunctionWithBias) {
695 this->write(", -0.5");
696 }
ethannicholasf789b382016-08-03 12:43:36 -0700697 this->write(")");
698}
699
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400700void GLSLCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
701 if (c.fArguments.size() == 1 &&
Ethan Nicholase1f55022019-02-05 17:17:40 -0500702 (this->getTypeName(c.fType) == this->getTypeName(c.fArguments[0]->fType) ||
703 (c.fType.kind() == Type::kScalar_Kind &&
704 c.fArguments[0]->fType == *fContext.fFloatLiteral_Type))) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400705 // in cases like half(float), they're different types as far as SkSL is concerned but the
706 // same type as far as GLSL is concerned. We avoid a redundant float(float) by just writing
707 // out the inner expression here.
708 this->writeExpression(*c.fArguments[0], parentPrecedence);
709 return;
710 }
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400711 this->writeType(c.fType);
712 this->write("(");
ethannicholasf789b382016-08-03 12:43:36 -0700713 const char* separator = "";
714 for (const auto& arg : c.fArguments) {
715 this->write(separator);
716 separator = ", ";
717 this->writeExpression(*arg, kSequence_Precedence);
718 }
719 this->write(")");
720}
721
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500722void GLSLCodeGenerator::writeFragCoord() {
Brian Osmancd3261a2018-01-16 13:52:29 +0000723 if (!fProgram.fSettings.fCaps->canUseFragCoord()) {
Brian Salomondba65f92018-01-22 08:43:38 -0500724 if (!fSetupFragCoordWorkaround) {
725 const char* precision = usesPrecisionModifiers() ? "highp " : "";
726 fFunctionHeader += precision;
727 fFunctionHeader += " float sk_FragCoord_InvW = 1. / sk_FragCoord_Workaround.w;\n";
728 fFunctionHeader += precision;
729 fFunctionHeader += " vec4 sk_FragCoord_Resolved = "
730 "vec4(sk_FragCoord_Workaround.xyz * sk_FragCoord_InvW, sk_FragCoord_InvW);\n";
731 // Ensure that we get exact .5 values for x and y.
732 fFunctionHeader += " sk_FragCoord_Resolved.xy = floor(sk_FragCoord_Resolved.xy) + "
733 "vec2(.5);\n";
734 fSetupFragCoordWorkaround = true;
735 }
736 this->write("sk_FragCoord_Resolved");
Brian Osmancd3261a2018-01-16 13:52:29 +0000737 return;
738 }
739
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500740 // We only declare "gl_FragCoord" when we're in the case where we want to use layout qualifiers
741 // to reverse y. Otherwise it isn't necessary and whether the "in" qualifier appears in the
742 // declaration varies in earlier GLSL specs. So it is simpler to omit it.
743 if (!fProgram.fSettings.fFlipY) {
744 this->write("gl_FragCoord");
745 } else if (const char* extension =
Ethan Nicholascd700e92018-08-24 16:43:57 -0400746 fProgram.fSettings.fCaps->fragCoordConventionsExtensionString()) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500747 if (!fSetupFragPositionGlobal) {
748 if (fProgram.fSettings.fCaps->generation() < k150_GrGLSLGeneration) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -0400749 this->writeExtension(extension);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500750 }
Ethan Nicholas88f6d372018-07-27 10:03:46 -0400751 fGlobals.writeText("layout(origin_upper_left) in vec4 gl_FragCoord;\n");
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500752 fSetupFragPositionGlobal = true;
Greg Daniele8e4a3e2016-12-12 17:20:42 +0000753 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500754 this->write("gl_FragCoord");
Greg Daniele8e4a3e2016-12-12 17:20:42 +0000755 } else {
Ethan Nicholascd700e92018-08-24 16:43:57 -0400756 if (!fSetupFragPositionLocal) {
Michael Ludwig5e1f6ea2018-12-03 15:14:50 -0500757 fFunctionHeader += usesPrecisionModifiers() ? "highp " : "";
Michael Ludwigf0b60442018-12-10 14:43:38 +0000758 fFunctionHeader += " vec4 sk_FragCoord = vec4(gl_FragCoord.x, " SKSL_RTHEIGHT_NAME
759 " - gl_FragCoord.y, gl_FragCoord.z, gl_FragCoord.w);\n";
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500760 fSetupFragPositionLocal = true;
761 }
762 this->write("sk_FragCoord");
763 }
764}
765
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500766void GLSLCodeGenerator::writeVariableReference(const VariableReference& ref) {
767 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
768 case SK_FRAGCOLOR_BUILTIN:
769 if (fProgram.fSettings.fCaps->mustDeclareFragmentShaderOutput()) {
770 this->write("sk_FragColor");
771 } else {
772 this->write("gl_FragColor");
773 }
774 break;
775 case SK_FRAGCOORD_BUILTIN:
776 this->writeFragCoord();
777 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400778 case SK_WIDTH_BUILTIN:
779 this->write("u_skRTWidth");
780 break;
781 case SK_HEIGHT_BUILTIN:
782 this->write("u_skRTHeight");
783 break;
Chris Dalton49d14e92018-07-27 12:38:35 -0600784 case SK_CLOCKWISE_BUILTIN:
Chris Daltonc8ece3d2018-07-30 15:03:45 -0600785 this->write(fProgram.fSettings.fFlipY ? "(!gl_FrontFacing)" : "gl_FrontFacing");
Chris Dalton49d14e92018-07-27 12:38:35 -0600786 break;
Ethan Nicholasa51740c2017-02-07 14:53:32 -0500787 case SK_VERTEXID_BUILTIN:
788 this->write("gl_VertexID");
789 break;
Chris Dalton8580d512017-10-14 22:12:33 -0600790 case SK_INSTANCEID_BUILTIN:
791 this->write("gl_InstanceID");
792 break;
Ethan Nicholas67d64602017-02-09 10:15:25 -0500793 case SK_CLIPDISTANCE_BUILTIN:
794 this->write("gl_ClipDistance");
795 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -0500796 case SK_IN_BUILTIN:
797 this->write("gl_in");
798 break;
799 case SK_INVOCATIONID_BUILTIN:
800 this->write("gl_InvocationID");
801 break;
Ethan Nicholaseab2baa2018-04-13 15:16:27 -0400802 case SK_LASTFRAGCOLOR_BUILTIN:
803 this->write(fProgram.fSettings.fCaps->fbFetchColorName());
804 break;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500805 default:
806 this->write(ref.fVariable.fName);
ethannicholas5961bc92016-10-12 06:39:56 -0700807 }
ethannicholasf789b382016-08-03 12:43:36 -0700808}
809
810void GLSLCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
811 this->writeExpression(*expr.fBase, kPostfix_Precedence);
812 this->write("[");
813 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
814 this->write("]");
815}
816
Brian Osmancd3261a2018-01-16 13:52:29 +0000817bool is_sk_position(const FieldAccess& f) {
818 return "sk_Position" == f.fBase->fType.fields()[f.fFieldIndex].fName;
819}
820
ethannicholasf789b382016-08-03 12:43:36 -0700821void GLSLCodeGenerator::writeFieldAccess(const FieldAccess& f) {
822 if (f.fOwnerKind == FieldAccess::kDefault_OwnerKind) {
823 this->writeExpression(*f.fBase, kPostfix_Precedence);
824 this->write(".");
825 }
Ethan Nicholas67d64602017-02-09 10:15:25 -0500826 switch (f.fBase->fType.fields()[f.fFieldIndex].fModifiers.fLayout.fBuiltin) {
827 case SK_CLIPDISTANCE_BUILTIN:
828 this->write("gl_ClipDistance");
829 break;
830 default:
Ethan Nicholasbed683a2017-09-26 14:23:59 -0400831 StringFragment name = f.fBase->fType.fields()[f.fFieldIndex].fName;
832 if (name == "sk_Position") {
833 this->write("gl_Position");
834 } else if (name == "sk_PointSize") {
835 this->write("gl_PointSize");
836 } else {
837 this->write(f.fBase->fType.fields()[f.fFieldIndex].fName);
838 }
Ethan Nicholas67d64602017-02-09 10:15:25 -0500839 }
ethannicholasf789b382016-08-03 12:43:36 -0700840}
841
842void GLSLCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
843 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
844 this->write(".");
845 for (int c : swizzle.fComponents) {
846 this->write(&("x\0y\0z\0w\0"[c * 2]));
847 }
848}
849
Ethan Nicholas762466e2017-06-29 10:03:38 -0400850GLSLCodeGenerator::Precedence GLSLCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
ethannicholasf789b382016-08-03 12:43:36 -0700851 switch (op) {
852 case Token::STAR: // fall through
853 case Token::SLASH: // fall through
854 case Token::PERCENT: return GLSLCodeGenerator::kMultiplicative_Precedence;
855 case Token::PLUS: // fall through
856 case Token::MINUS: return GLSLCodeGenerator::kAdditive_Precedence;
857 case Token::SHL: // fall through
858 case Token::SHR: return GLSLCodeGenerator::kShift_Precedence;
859 case Token::LT: // fall through
860 case Token::GT: // fall through
861 case Token::LTEQ: // fall through
862 case Token::GTEQ: return GLSLCodeGenerator::kRelational_Precedence;
863 case Token::EQEQ: // fall through
864 case Token::NEQ: return GLSLCodeGenerator::kEquality_Precedence;
865 case Token::BITWISEAND: return GLSLCodeGenerator::kBitwiseAnd_Precedence;
866 case Token::BITWISEXOR: return GLSLCodeGenerator::kBitwiseXor_Precedence;
867 case Token::BITWISEOR: return GLSLCodeGenerator::kBitwiseOr_Precedence;
868 case Token::LOGICALAND: return GLSLCodeGenerator::kLogicalAnd_Precedence;
869 case Token::LOGICALXOR: return GLSLCodeGenerator::kLogicalXor_Precedence;
870 case Token::LOGICALOR: return GLSLCodeGenerator::kLogicalOr_Precedence;
871 case Token::EQ: // fall through
872 case Token::PLUSEQ: // fall through
873 case Token::MINUSEQ: // fall through
874 case Token::STAREQ: // fall through
875 case Token::SLASHEQ: // fall through
876 case Token::PERCENTEQ: // fall through
877 case Token::SHLEQ: // fall through
878 case Token::SHREQ: // fall through
879 case Token::LOGICALANDEQ: // fall through
880 case Token::LOGICALXOREQ: // fall through
881 case Token::LOGICALOREQ: // fall through
882 case Token::BITWISEANDEQ: // fall through
883 case Token::BITWISEXOREQ: // fall through
884 case Token::BITWISEOREQ: return GLSLCodeGenerator::kAssignment_Precedence;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400885 case Token::COMMA: return GLSLCodeGenerator::kSequence_Precedence;
ethannicholasf789b382016-08-03 12:43:36 -0700886 default: ABORT("unsupported binary operator");
887 }
888}
889
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400890void GLSLCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
ethannicholasf789b382016-08-03 12:43:36 -0700891 Precedence parentPrecedence) {
Adrienne Walkerc02165f2018-08-21 11:08:11 -0700892 if (fProgram.fSettings.fCaps->unfoldShortCircuitAsTernary() &&
893 (b.fOperator == Token::LOGICALAND || b.fOperator == Token::LOGICALOR)) {
894 this->writeShortCircuitWorkaroundExpression(b, parentPrecedence);
895 return;
896 }
897
Ethan Nicholas762466e2017-06-29 10:03:38 -0400898 Precedence precedence = GetBinaryPrecedence(b.fOperator);
ethannicholasf789b382016-08-03 12:43:36 -0700899 if (precedence >= parentPrecedence) {
900 this->write("(");
901 }
Ethan Nicholas0b631962018-07-24 13:41:11 -0400902 bool positionWorkaround = fProgramKind == Program::Kind::kVertex_Kind &&
903 Compiler::IsAssignment(b.fOperator) &&
Brian Osmancd3261a2018-01-16 13:52:29 +0000904 Expression::kFieldAccess_Kind == b.fLeft->fKind &&
905 is_sk_position((FieldAccess&) *b.fLeft) &&
906 !strstr(b.fRight->description().c_str(), "sk_RTAdjust") &&
907 !fProgram.fSettings.fCaps->canUseFragCoord();
908 if (positionWorkaround) {
909 this->write("sk_FragCoord_Workaround = (");
910 }
ethannicholasf789b382016-08-03 12:43:36 -0700911 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700912 this->write(" ");
913 this->write(Compiler::OperatorName(b.fOperator));
914 this->write(" ");
ethannicholasf789b382016-08-03 12:43:36 -0700915 this->writeExpression(*b.fRight, precedence);
Brian Osmancd3261a2018-01-16 13:52:29 +0000916 if (positionWorkaround) {
917 this->write(")");
918 }
ethannicholasf789b382016-08-03 12:43:36 -0700919 if (precedence >= parentPrecedence) {
920 this->write(")");
921 }
922}
923
Adrienne Walkerc02165f2018-08-21 11:08:11 -0700924void GLSLCodeGenerator::writeShortCircuitWorkaroundExpression(const BinaryExpression& b,
925 Precedence parentPrecedence) {
926 if (kTernary_Precedence >= parentPrecedence) {
927 this->write("(");
928 }
929
930 // Transform:
931 // a && b => a ? b : false
932 // a || b => a ? true : b
933 this->writeExpression(*b.fLeft, kTernary_Precedence);
934 this->write(" ? ");
935 if (b.fOperator == Token::LOGICALAND) {
936 this->writeExpression(*b.fRight, kTernary_Precedence);
937 } else {
938 BoolLiteral boolTrue(fContext, -1, true);
939 this->writeBoolLiteral(boolTrue);
940 }
941 this->write(" : ");
942 if (b.fOperator == Token::LOGICALAND) {
943 BoolLiteral boolFalse(fContext, -1, false);
944 this->writeBoolLiteral(boolFalse);
945 } else {
946 this->writeExpression(*b.fRight, kTernary_Precedence);
947 }
948 if (kTernary_Precedence >= parentPrecedence) {
949 this->write(")");
950 }
951}
952
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400953void GLSLCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
ethannicholasf789b382016-08-03 12:43:36 -0700954 Precedence parentPrecedence) {
955 if (kTernary_Precedence >= parentPrecedence) {
956 this->write("(");
957 }
958 this->writeExpression(*t.fTest, kTernary_Precedence);
959 this->write(" ? ");
960 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
961 this->write(" : ");
962 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
963 if (kTernary_Precedence >= parentPrecedence) {
964 this->write(")");
965 }
966}
967
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400968void GLSLCodeGenerator::writePrefixExpression(const PrefixExpression& p,
ethannicholasf789b382016-08-03 12:43:36 -0700969 Precedence parentPrecedence) {
970 if (kPrefix_Precedence >= parentPrecedence) {
971 this->write("(");
972 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700973 this->write(Compiler::OperatorName(p.fOperator));
ethannicholasf789b382016-08-03 12:43:36 -0700974 this->writeExpression(*p.fOperand, kPrefix_Precedence);
975 if (kPrefix_Precedence >= parentPrecedence) {
976 this->write(")");
977 }
978}
979
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400980void GLSLCodeGenerator::writePostfixExpression(const PostfixExpression& p,
ethannicholasf789b382016-08-03 12:43:36 -0700981 Precedence parentPrecedence) {
982 if (kPostfix_Precedence >= parentPrecedence) {
983 this->write("(");
984 }
985 this->writeExpression(*p.fOperand, kPostfix_Precedence);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700986 this->write(Compiler::OperatorName(p.fOperator));
ethannicholasf789b382016-08-03 12:43:36 -0700987 if (kPostfix_Precedence >= parentPrecedence) {
988 this->write(")");
989 }
990}
991
992void GLSLCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
993 this->write(b.fValue ? "true" : "false");
994}
995
996void GLSLCodeGenerator::writeIntLiteral(const IntLiteral& i) {
ethannicholas5961bc92016-10-12 06:39:56 -0700997 if (i.fType == *fContext.fUInt_Type) {
998 this->write(to_string(i.fValue & 0xffffffff) + "u");
Ethan Nicholas58d56482017-12-19 09:29:22 -0500999 } else if (i.fType == *fContext.fUShort_Type) {
1000 this->write(to_string(i.fValue & 0xffff) + "u");
Ruiqi Maob609e6d2018-07-17 10:19:38 -04001001 } else if (i.fType == *fContext.fUByte_Type) {
1002 this->write(to_string(i.fValue & 0xff) + "u");
1003 } else {
ethannicholas5961bc92016-10-12 06:39:56 -07001004 this->write(to_string((int32_t) i.fValue));
1005 }
ethannicholasf789b382016-08-03 12:43:36 -07001006}
1007
1008void GLSLCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
1009 this->write(to_string(f.fValue));
1010}
1011
Ethan Nicholas762466e2017-06-29 10:03:38 -04001012void GLSLCodeGenerator::writeSetting(const Setting& s) {
1013 ABORT("internal error; setting was not folded to a constant during compilation\n");
1014}
1015
ethannicholasf789b382016-08-03 12:43:36 -07001016void GLSLCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001017 if (fProgramKind != Program::kPipelineStage_Kind) {
1018 this->writeTypePrecision(f.fDeclaration.fReturnType);
1019 this->writeType(f.fDeclaration.fReturnType);
1020 this->write(" " + f.fDeclaration.fName + "(");
1021 const char* separator = "";
1022 for (const auto& param : f.fDeclaration.fParameters) {
1023 this->write(separator);
1024 separator = ", ";
1025 this->writeModifiers(param->fModifiers, false);
1026 std::vector<int> sizes;
1027 const Type* type = &param->fType;
1028 while (type->kind() == Type::kArray_Kind) {
1029 sizes.push_back(type->columns());
1030 type = &type->componentType();
1031 }
1032 this->writeTypePrecision(*type);
1033 this->writeType(*type);
1034 this->write(" " + param->fName);
1035 for (int s : sizes) {
1036 if (s <= 0) {
1037 this->write("[]");
1038 } else {
1039 this->write("[" + to_string(s) + "]");
1040 }
ethannicholas5961bc92016-10-12 06:39:56 -07001041 }
1042 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001043 this->writeLine(") {");
1044 fIndentation++;
ethannicholasf789b382016-08-03 12:43:36 -07001045 }
ethannicholas5961bc92016-10-12 06:39:56 -07001046 fFunctionHeader = "";
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001047 OutputStream* oldOut = fOut;
1048 StringStream buffer;
ethannicholas5961bc92016-10-12 06:39:56 -07001049 fOut = &buffer;
Ethan Nicholascb670962017-04-20 19:31:52 -04001050 this->writeStatements(((Block&) *f.fBody).fStatements);
Ethan Nicholas00543112018-07-31 09:44:36 -04001051 if (fProgramKind != Program::kPipelineStage_Kind) {
1052 fIndentation--;
1053 this->writeLine("}");
1054 }
ethannicholas5961bc92016-10-12 06:39:56 -07001055
1056 fOut = oldOut;
1057 this->write(fFunctionHeader);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001058 this->write(buffer.str());
ethannicholasf789b382016-08-03 12:43:36 -07001059}
1060
Greg Daniel64773e62016-11-22 09:44:03 -05001061void GLSLCodeGenerator::writeModifiers(const Modifiers& modifiers,
ethannicholas5961bc92016-10-12 06:39:56 -07001062 bool globalContext) {
Brian Salomonf9f45122016-11-29 11:59:17 -05001063 if (modifiers.fFlags & Modifiers::kFlat_Flag) {
1064 this->write("flat ");
1065 }
ethannicholas5961bc92016-10-12 06:39:56 -07001066 if (modifiers.fFlags & Modifiers::kNoPerspective_Flag) {
1067 this->write("noperspective ");
1068 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001069 String layout = modifiers.fLayout.description();
Ethan Nicholas8da9e942017-03-09 16:35:09 -05001070 if (layout.size()) {
1071 this->write(layout + " ");
1072 }
Brian Salomonf9f45122016-11-29 11:59:17 -05001073 if (modifiers.fFlags & Modifiers::kReadOnly_Flag) {
1074 this->write("readonly ");
1075 }
1076 if (modifiers.fFlags & Modifiers::kWriteOnly_Flag) {
1077 this->write("writeonly ");
1078 }
1079 if (modifiers.fFlags & Modifiers::kCoherent_Flag) {
1080 this->write("coherent ");
1081 }
1082 if (modifiers.fFlags & Modifiers::kVolatile_Flag) {
1083 this->write("volatile ");
1084 }
1085 if (modifiers.fFlags & Modifiers::kRestrict_Flag) {
1086 this->write("restrict ");
ethannicholas5961bc92016-10-12 06:39:56 -07001087 }
Greg Daniel64773e62016-11-22 09:44:03 -05001088 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
ethannicholas5961bc92016-10-12 06:39:56 -07001089 (modifiers.fFlags & Modifiers::kOut_Flag)) {
1090 this->write("inout ");
1091 } else if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001092 if (globalContext &&
1093 fProgram.fSettings.fCaps->generation() < GrGLSLGeneration::k130_GrGLSLGeneration) {
ethannicholas5961bc92016-10-12 06:39:56 -07001094 this->write(fProgramKind == Program::kVertex_Kind ? "attribute "
1095 : "varying ");
1096 } else {
1097 this->write("in ");
1098 }
1099 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001100 if (globalContext &&
1101 fProgram.fSettings.fCaps->generation() < GrGLSLGeneration::k130_GrGLSLGeneration) {
ethannicholas5961bc92016-10-12 06:39:56 -07001102 this->write("varying ");
1103 } else {
1104 this->write("out ");
1105 }
1106 }
1107 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
1108 this->write("uniform ");
1109 }
1110 if (modifiers.fFlags & Modifiers::kConst_Flag) {
1111 this->write("const ");
1112 }
Ethan Nicholasa7ceb502019-01-11 10:31:48 -05001113 if (modifiers.fFlags & Modifiers::kPLS_Flag) {
1114 this->write("__pixel_localEXT ");
1115 }
1116 if (modifiers.fFlags & Modifiers::kPLSIn_Flag) {
1117 this->write("__pixel_local_inEXT ");
1118 }
1119 if (modifiers.fFlags & Modifiers::kPLSOut_Flag) {
1120 this->write("__pixel_local_outEXT ");
1121 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001122 if (usesPrecisionModifiers()) {
ethannicholas5961bc92016-10-12 06:39:56 -07001123 if (modifiers.fFlags & Modifiers::kLowp_Flag) {
1124 this->write("lowp ");
1125 }
1126 if (modifiers.fFlags & Modifiers::kMediump_Flag) {
1127 this->write("mediump ");
1128 }
1129 if (modifiers.fFlags & Modifiers::kHighp_Flag) {
1130 this->write("highp ");
1131 }
1132 }
ethannicholasf789b382016-08-03 12:43:36 -07001133}
1134
1135void GLSLCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholas52cad152017-02-16 16:37:32 -05001136 if (intf.fTypeName == "sk_PerVertex") {
ethannicholasf789b382016-08-03 12:43:36 -07001137 return;
1138 }
ethannicholas5961bc92016-10-12 06:39:56 -07001139 this->writeModifiers(intf.fVariable.fModifiers, true);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001140 this->writeLine(intf.fTypeName + " {");
ethannicholasf789b382016-08-03 12:43:36 -07001141 fIndentation++;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001142 const Type* structType = &intf.fVariable.fType;
1143 while (structType->kind() == Type::kArray_Kind) {
1144 structType = &structType->componentType();
1145 }
1146 for (const auto& f : structType->fields()) {
ethannicholas5961bc92016-10-12 06:39:56 -07001147 this->writeModifiers(f.fModifiers, false);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001148 this->writeTypePrecision(*f.fType);
ethannicholas0730be72016-09-01 07:59:02 -07001149 this->writeType(*f.fType);
ethannicholasf789b382016-08-03 12:43:36 -07001150 this->writeLine(" " + f.fName + ";");
1151 }
1152 fIndentation--;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001153 this->write("}");
1154 if (intf.fInstanceName.size()) {
1155 this->write(" ");
1156 this->write(intf.fInstanceName);
1157 for (const auto& size : intf.fSizes) {
1158 this->write("[");
1159 if (size) {
1160 this->writeExpression(*size, kTopLevel_Precedence);
1161 }
1162 this->write("]");
1163 }
1164 }
1165 this->writeLine(";");
ethannicholasf789b382016-08-03 12:43:36 -07001166}
1167
Ethan Nicholas762466e2017-06-29 10:03:38 -04001168void GLSLCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1169 this->writeExpression(value, kTopLevel_Precedence);
1170}
1171
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001172const char* GLSLCodeGenerator::getTypePrecision(const Type& type) {
1173 if (usesPrecisionModifiers()) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001174 switch (type.kind()) {
1175 case Type::kScalar_Kind:
Ruiqi Maob609e6d2018-07-17 10:19:38 -04001176 if (type == *fContext.fShort_Type || type == *fContext.fUShort_Type ||
1177 type == *fContext.fByte_Type || type == *fContext.fUByte_Type) {
Chris Daltonc2d0dd62018-03-07 07:46:10 -07001178 if (fProgram.fSettings.fForceHighPrecision ||
1179 fProgram.fSettings.fCaps->incompleteShortIntPrecision()) {
1180 return "highp ";
1181 }
1182 return "mediump ";
1183 }
1184 if (type == *fContext.fHalf_Type) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001185 return fProgram.fSettings.fForceHighPrecision ? "highp " : "mediump ";
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001186 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001187 if (type == *fContext.fFloat_Type || type == *fContext.fInt_Type ||
1188 type == *fContext.fUInt_Type) {
1189 return "highp ";
1190 }
1191 return "";
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001192 case Type::kVector_Kind: // fall through
1193 case Type::kMatrix_Kind:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001194 return this->getTypePrecision(type.componentType());
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001195 default:
1196 break;
1197 }
1198 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001199 return "";
1200}
1201
1202void GLSLCodeGenerator::writeTypePrecision(const Type& type) {
1203 this->write(this->getTypePrecision(type));
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001204}
1205
ethannicholas5961bc92016-10-12 06:39:56 -07001206void GLSLCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholas14efcbf2017-11-07 09:23:38 -05001207 if (!decl.fVars.size()) {
1208 return;
1209 }
Ethan Nicholasb4dc4192017-06-02 10:16:28 -04001210 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001211 for (const auto& stmt : decl.fVars) {
1212 VarDeclaration& var = (VarDeclaration&) *stmt;
Ethan Nicholasb4dc4192017-06-02 10:16:28 -04001213 if (wroteType) {
1214 this->write(", ");
1215 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001216 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001217 this->writeTypePrecision(decl.fBaseType);
Ethan Nicholasb4dc4192017-06-02 10:16:28 -04001218 this->writeType(decl.fBaseType);
1219 this->write(" ");
1220 wroteType = true;
1221 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001222 this->write(var.fVar->fName);
1223 for (const auto& size : var.fSizes) {
ethannicholasf789b382016-08-03 12:43:36 -07001224 this->write("[");
ethannicholas5961bc92016-10-12 06:39:56 -07001225 if (size) {
1226 this->writeExpression(*size, kTopLevel_Precedence);
1227 }
ethannicholasf789b382016-08-03 12:43:36 -07001228 this->write("]");
1229 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001230 if (var.fValue) {
ethannicholasf789b382016-08-03 12:43:36 -07001231 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001232 this->writeVarInitializer(*var.fVar, *var.fValue);
ethannicholasf789b382016-08-03 12:43:36 -07001233 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001234 if (!fFoundImageDecl && var.fVar->fType == *fContext.fImage2D_Type) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001235 if (fProgram.fSettings.fCaps->imageLoadStoreExtensionString()) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001236 this->writeExtension(fProgram.fSettings.fCaps->imageLoadStoreExtensionString());
Brian Salomon2a51de82016-11-16 12:06:01 -05001237 }
1238 fFoundImageDecl = true;
1239 }
Brian Osman4b2f9152018-04-17 11:19:57 -04001240 if (!fFoundExternalSamplerDecl && var.fVar->fType == *fContext.fSamplerExternalOES_Type) {
1241 if (fProgram.fSettings.fCaps->externalTextureExtensionString()) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001242 this->writeExtension(fProgram.fSettings.fCaps->externalTextureExtensionString());
Brian Osman4b2f9152018-04-17 11:19:57 -04001243 }
Brian Osman061020e2018-04-17 14:22:15 -04001244 if (fProgram.fSettings.fCaps->secondExternalTextureExtensionString()) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001245 this->writeExtension(
1246 fProgram.fSettings.fCaps->secondExternalTextureExtensionString());
Brian Osman061020e2018-04-17 14:22:15 -04001247 }
Brian Osman4b2f9152018-04-17 11:19:57 -04001248 fFoundExternalSamplerDecl = true;
1249 }
ethannicholasf789b382016-08-03 12:43:36 -07001250 }
Ethan Nicholasb4dc4192017-06-02 10:16:28 -04001251 if (wroteType) {
1252 this->write(";");
1253 }
ethannicholasf789b382016-08-03 12:43:36 -07001254}
1255
1256void GLSLCodeGenerator::writeStatement(const Statement& s) {
1257 switch (s.fKind) {
1258 case Statement::kBlock_Kind:
1259 this->writeBlock((Block&) s);
1260 break;
1261 case Statement::kExpression_Kind:
1262 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1263 this->write(";");
1264 break;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001265 case Statement::kReturn_Kind:
ethannicholasf789b382016-08-03 12:43:36 -07001266 this->writeReturnStatement((ReturnStatement&) s);
1267 break;
ethannicholas14fe8cc2016-09-07 13:37:16 -07001268 case Statement::kVarDeclarations_Kind:
ethannicholas5961bc92016-10-12 06:39:56 -07001269 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
ethannicholasf789b382016-08-03 12:43:36 -07001270 break;
1271 case Statement::kIf_Kind:
1272 this->writeIfStatement((IfStatement&) s);
1273 break;
1274 case Statement::kFor_Kind:
1275 this->writeForStatement((ForStatement&) s);
1276 break;
1277 case Statement::kWhile_Kind:
1278 this->writeWhileStatement((WhileStatement&) s);
1279 break;
1280 case Statement::kDo_Kind:
1281 this->writeDoStatement((DoStatement&) s);
1282 break;
Ethan Nicholasaf197692017-02-27 13:26:45 -05001283 case Statement::kSwitch_Kind:
1284 this->writeSwitchStatement((SwitchStatement&) s);
1285 break;
ethannicholasf789b382016-08-03 12:43:36 -07001286 case Statement::kBreak_Kind:
1287 this->write("break;");
1288 break;
1289 case Statement::kContinue_Kind:
1290 this->write("continue;");
1291 break;
1292 case Statement::kDiscard_Kind:
1293 this->write("discard;");
1294 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001295 case Statement::kNop_Kind:
1296 this->write(";");
1297 break;
ethannicholasf789b382016-08-03 12:43:36 -07001298 default:
1299 ABORT("unsupported statement: %s", s.description().c_str());
1300 }
1301}
1302
Ethan Nicholascb670962017-04-20 19:31:52 -04001303void GLSLCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1304 for (const auto& s : statements) {
1305 if (!s->isEmpty()) {
1306 this->writeStatement(*s);
1307 this->writeLine();
1308 }
1309 }
1310}
1311
ethannicholasf789b382016-08-03 12:43:36 -07001312void GLSLCodeGenerator::writeBlock(const Block& b) {
1313 this->writeLine("{");
1314 fIndentation++;
Ethan Nicholascb670962017-04-20 19:31:52 -04001315 this->writeStatements(b.fStatements);
ethannicholasf789b382016-08-03 12:43:36 -07001316 fIndentation--;
1317 this->write("}");
1318}
1319
1320void GLSLCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1321 this->write("if (");
1322 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1323 this->write(") ");
1324 this->writeStatement(*stmt.fIfTrue);
1325 if (stmt.fIfFalse) {
1326 this->write(" else ");
1327 this->writeStatement(*stmt.fIfFalse);
1328 }
1329}
1330
1331void GLSLCodeGenerator::writeForStatement(const ForStatement& f) {
1332 this->write("for (");
Ethan Nicholasb310fd52017-06-09 13:46:34 -04001333 if (f.fInitializer && !f.fInitializer->isEmpty()) {
ethannicholasf789b382016-08-03 12:43:36 -07001334 this->writeStatement(*f.fInitializer);
1335 } else {
1336 this->write("; ");
1337 }
1338 if (f.fTest) {
Adrienne Walkeree8295c2018-08-21 10:56:30 -07001339 if (fProgram.fSettings.fCaps->addAndTrueToLoopCondition()) {
1340 std::unique_ptr<Expression> and_true(new BinaryExpression(
1341 -1, f.fTest->clone(), Token::LOGICALAND,
1342 std::unique_ptr<BoolLiteral>(new BoolLiteral(fContext, -1,
1343 true)),
1344 *fContext.fBool_Type));
1345 this->writeExpression(*and_true, kTopLevel_Precedence);
1346 } else {
1347 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1348 }
ethannicholasf789b382016-08-03 12:43:36 -07001349 }
1350 this->write("; ");
1351 if (f.fNext) {
1352 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1353 }
1354 this->write(") ");
1355 this->writeStatement(*f.fStatement);
1356}
1357
1358void GLSLCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1359 this->write("while (");
1360 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1361 this->write(") ");
1362 this->writeStatement(*w.fStatement);
1363}
1364
1365void GLSLCodeGenerator::writeDoStatement(const DoStatement& d) {
Adrienne Walker8b23ca62018-08-22 10:45:41 -07001366 if (!fProgram.fSettings.fCaps->rewriteDoWhileLoops()) {
1367 this->write("do ");
1368 this->writeStatement(*d.fStatement);
1369 this->write(" while (");
1370 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1371 this->write(");");
1372 return;
1373 }
1374
1375 // Otherwise, do the do while loop workaround, to rewrite loops of the form:
1376 // do {
1377 // CODE;
1378 // } while (CONDITION)
1379 //
1380 // to loops of the form
1381 // bool temp = false;
1382 // while (true) {
1383 // if (temp) {
1384 // if (!CONDITION) {
1385 // break;
1386 // }
1387 // }
1388 // temp = true;
1389 // CODE;
1390 // }
1391 String tmpVar = "_tmpLoopSeenOnce" + to_string(fVarCount++);
1392 this->write("bool ");
1393 this->write(tmpVar);
1394 this->writeLine(" = false;");
1395 this->writeLine("while (true) {");
1396 fIndentation++;
1397 this->write("if (");
1398 this->write(tmpVar);
1399 this->writeLine(") {");
1400 fIndentation++;
1401 this->write("if (!");
1402 this->writeExpression(*d.fTest, kPrefix_Precedence);
1403 this->writeLine(") {");
1404 fIndentation++;
1405 this->writeLine("break;");
1406 fIndentation--;
1407 this->writeLine("}");
1408 fIndentation--;
1409 this->writeLine("}");
1410 this->write(tmpVar);
1411 this->writeLine(" = true;");
ethannicholasf789b382016-08-03 12:43:36 -07001412 this->writeStatement(*d.fStatement);
Adrienne Walker8b23ca62018-08-22 10:45:41 -07001413 this->writeLine();
1414 fIndentation--;
1415 this->write("}");
ethannicholasf789b382016-08-03 12:43:36 -07001416}
1417
Ethan Nicholasaf197692017-02-27 13:26:45 -05001418void GLSLCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1419 this->write("switch (");
1420 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1421 this->writeLine(") {");
1422 fIndentation++;
1423 for (const auto& c : s.fCases) {
1424 if (c->fValue) {
1425 this->write("case ");
1426 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1427 this->writeLine(":");
1428 } else {
1429 this->writeLine("default:");
1430 }
1431 fIndentation++;
1432 for (const auto& stmt : c->fStatements) {
1433 this->writeStatement(*stmt);
1434 this->writeLine();
1435 }
1436 fIndentation--;
1437 }
1438 fIndentation--;
1439 this->write("}");
1440}
1441
ethannicholasf789b382016-08-03 12:43:36 -07001442void GLSLCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1443 this->write("return");
1444 if (r.fExpression) {
1445 this->write(" ");
1446 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1447 }
1448 this->write(";");
1449}
1450
Ethan Nicholas762466e2017-06-29 10:03:38 -04001451void GLSLCodeGenerator::writeHeader() {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001452 this->write(fProgram.fSettings.fCaps->versionDeclString());
ethannicholasf789b382016-08-03 12:43:36 -07001453 this->writeLine();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001454}
1455
Ethan Nicholas762466e2017-06-29 10:03:38 -04001456void GLSLCodeGenerator::writeProgramElement(const ProgramElement& e) {
1457 switch (e.fKind) {
1458 case ProgramElement::kExtension_Kind:
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001459 this->writeExtension(((Extension&) e).fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001460 break;
1461 case ProgramElement::kVar_Kind: {
1462 VarDeclarations& decl = (VarDeclarations&) e;
1463 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001464 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001465 if (builtin == -1) {
1466 // normal var
1467 this->writeVarDeclarations(decl, true);
1468 this->writeLine();
1469 } else if (builtin == SK_FRAGCOLOR_BUILTIN &&
Ethan Nicholasa7ceb502019-01-11 10:31:48 -05001470 fProgram.fSettings.fCaps->mustDeclareFragmentShaderOutput() &&
1471 ((VarDeclaration&) *decl.fVars[0]).fVar->fWriteCount) {
Brian Salomondc092132018-04-04 10:14:16 -04001472 if (fProgram.fSettings.fFragColorIsInOut) {
1473 this->write("inout ");
1474 } else {
1475 this->write("out ");
1476 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001477 if (usesPrecisionModifiers()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001478 this->write("mediump ");
Mike Klein5ce39722017-06-27 22:52:03 +00001479 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001480 this->writeLine("vec4 sk_FragColor;");
Mike Klein5ce39722017-06-27 22:52:03 +00001481 }
Mike Klein5ce39722017-06-27 22:52:03 +00001482 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001483 break;
Mike Klein5ce39722017-06-27 22:52:03 +00001484 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001485 case ProgramElement::kInterfaceBlock_Kind:
1486 this->writeInterfaceBlock((InterfaceBlock&) e);
1487 break;
1488 case ProgramElement::kFunction_Kind:
1489 this->writeFunction((FunctionDefinition&) e);
1490 break;
Chris Daltonf1b47bb2017-10-06 11:57:51 -06001491 case ProgramElement::kModifiers_Kind: {
1492 const Modifiers& modifiers = ((ModifiersDeclaration&) e).fModifiers;
1493 if (!fFoundGSInvocations && modifiers.fLayout.fInvocations >= 0) {
1494 if (fProgram.fSettings.fCaps->gsInvocationsExtensionString()) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001495 this->writeExtension(fProgram.fSettings.fCaps->gsInvocationsExtensionString());
Chris Daltonf1b47bb2017-10-06 11:57:51 -06001496 }
1497 fFoundGSInvocations = true;
1498 }
1499 this->writeModifiers(modifiers, true);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001500 this->writeLine(";");
1501 break;
Chris Daltonf1b47bb2017-10-06 11:57:51 -06001502 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001503 case ProgramElement::kEnum_Kind:
1504 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001505 default:
1506 printf("%s\n", e.description().c_str());
1507 ABORT("unsupported program element");
Ethan Nicholasc0709392017-06-27 11:20:22 -04001508 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001509}
1510
Ethan Nicholascd700e92018-08-24 16:43:57 -04001511void GLSLCodeGenerator::writeInputVars() {
1512 if (fProgram.fInputs.fRTWidth) {
1513 const char* precision = usesPrecisionModifiers() ? "highp " : "";
1514 fGlobals.writeText("uniform ");
1515 fGlobals.writeText(precision);
1516 fGlobals.writeText("float " SKSL_RTWIDTH_NAME ";\n");
1517 }
1518 if (fProgram.fInputs.fRTHeight) {
1519 const char* precision = usesPrecisionModifiers() ? "highp " : "";
1520 fGlobals.writeText("uniform ");
1521 fGlobals.writeText(precision);
1522 fGlobals.writeText("float " SKSL_RTHEIGHT_NAME ";\n");
1523 }
1524}
1525
Ethan Nicholas762466e2017-06-29 10:03:38 -04001526bool GLSLCodeGenerator::generateCode() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001527 if (fProgramKind != Program::kPipelineStage_Kind) {
1528 this->writeHeader();
1529 }
Chris Dalton8fd79552018-01-11 00:46:14 -05001530 if (Program::kGeometry_Kind == fProgramKind &&
1531 fProgram.fSettings.fCaps->geometryShaderExtensionString()) {
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001532 this->writeExtension(fProgram.fSettings.fCaps->geometryShaderExtensionString());
Chris Dalton8fd79552018-01-11 00:46:14 -05001533 }
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001534 OutputStream* rawOut = fOut;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001535 StringStream body;
1536 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001537 for (const auto& e : fProgram) {
1538 this->writeProgramElement(e);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001539 }
1540 fOut = rawOut;
ethannicholasddb37d62016-10-20 09:54:00 -07001541
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001542 write_stringstream(fExtensions, *rawOut);
Ethan Nicholascd700e92018-08-24 16:43:57 -04001543 this->writeInputVars();
Ethan Nicholas88f6d372018-07-27 10:03:46 -04001544 write_stringstream(fGlobals, *rawOut);
Brian Osmancc10d792018-07-20 13:09:45 -04001545
1546 if (!fProgram.fSettings.fCaps->canUseFragCoord()) {
1547 Layout layout;
1548 switch (fProgram.fKind) {
1549 case Program::kVertex_Kind: {
1550 Modifiers modifiers(layout, Modifiers::kOut_Flag | Modifiers::kHighp_Flag);
1551 this->writeModifiers(modifiers, true);
1552 this->write("vec4 sk_FragCoord_Workaround;\n");
1553 break;
1554 }
1555 case Program::kFragment_Kind: {
1556 Modifiers modifiers(layout, Modifiers::kIn_Flag | Modifiers::kHighp_Flag);
1557 this->writeModifiers(modifiers, true);
1558 this->write("vec4 sk_FragCoord_Workaround;\n");
1559 break;
1560 }
1561 default:
1562 break;
1563 }
1564 }
1565
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001566 if (this->usesPrecisionModifiers()) {
1567 this->writeLine("precision mediump float;");
1568 }
Ethan Nicholas6e6525c2018-01-03 17:03:56 -05001569 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001570 write_stringstream(body, *rawOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001571 return true;
ethannicholasf789b382016-08-03 12:43:36 -07001572}
1573
1574}