1/*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "GrCCCubicShader.h"
9
10#include "glsl/GrGLSLFragmentShaderBuilder.h"
11#include "glsl/GrGLSLVertexGeoBuilder.h"
12
13using Shader = GrCCCoverageProcessor::Shader;
14
15void GrCCCubicShader::emitSetupCode(GrGLSLVertexGeoBuilder* s, const char* pts,
16                                    const char* repetitionID, const char* wind,
17                                    GeometryVars* vars) const {
18    // Find the cubic's power basis coefficients.
19    s->codeAppendf("float2x4 C = float4x4(-1,  3, -3,  1, "
20                                         " 3, -6,  3,  0, "
21                                         "-3,  3,  0,  0, "
22                                         " 1,  0,  0,  0) * transpose(%s);", pts);
23
24    // Find the cubic's inflection function.
25    s->codeAppend ("float D3 = +determinant(float2x2(C[0].yz, C[1].yz));");
26    s->codeAppend ("float D2 = -determinant(float2x2(C[0].xz, C[1].xz));");
27    s->codeAppend ("float D1 = +determinant(float2x2(C));");
28
29    // Calculate the KLM matrix.
30    s->declareGlobal(fKLMMatrix);
31    s->codeAppend ("float discr = 3*D2*D2 - 4*D1*D3;");
32    s->codeAppend ("float x = discr >= 0 ? 3 : 1;");
33    s->codeAppend ("float q = sqrt(x * abs(discr));");
34    s->codeAppend ("q = x*D2 + (D2 >= 0 ? q : -q);");
35
36    s->codeAppend ("float2 l, m;");
37    s->codeAppend ("l.ts = normalize(float2(q, 2*x * D1));");
38    s->codeAppend ("m.ts = normalize(float2(2, q) * (discr >= 0 ? float2(D3, 1) "
39                                                               ": float2(D2*D2 - D3*D1, D1)));");
40
41    s->codeAppend ("float4 K;");
42    s->codeAppend ("float4 lm = l.sstt * m.stst;");
43    s->codeAppend ("K = float4(0, lm.x, -lm.y - lm.z, lm.w);");
44
45    s->codeAppend ("float4 L, M;");
46    s->codeAppend ("lm.yz += 2*lm.zy;");
47    s->codeAppend ("L = float4(-1,x,-x,1) * l.sstt * (discr >= 0 ? l.ssst * l.sttt : lm);");
48    s->codeAppend ("M = float4(-1,x,-x,1) * m.sstt * (discr >= 0 ? m.ssst * m.sttt : lm.xzyw);");
49
50    s->codeAppend ("short middlerow = abs(D2) > abs(D1) ? 2 : 1;");
51    s->codeAppend ("float3x3 CI = inverse(float3x3(C[0][0], C[0][middlerow], C[0][3], "
52                                                  "C[1][0], C[1][middlerow], C[1][3], "
53                                                  "      0,               0,       1));");
54    s->codeAppendf("%s = CI * float3x3(K[0], K[middlerow], K[3], "
55                                      "L[0], L[middlerow], L[3], "
56                                      "M[0], M[middlerow], M[3]);", fKLMMatrix.c_str());
57
58    // Evaluate the cubic at T=.5 for a mid-ish point.
59    s->codeAppendf("float2 midpoint = %s * float4(.125, .375, .375, .125);", pts);
60
61    // Orient the KLM matrix so L & M have matching signs on the side of the curve we wish to fill.
62    // We give L & M both the same sign as wind, in order to pass this value to the fragment shader.
63    // (Cubics are pre-chopped such that L & M do not change sign within any individual segment).
64    s->codeAppendf("float2 orientation = sign(float3(midpoint, 1) * float2x3(%s[1], %s[2]));",
65                   fKLMMatrix.c_str(), fKLMMatrix.c_str());
66    s->codeAppendf("%s *= float3x3(orientation[0] * orientation[1], 0, 0, "
67                                  "0, orientation[0] * %s, 0, "
68                                  "0, 0, orientation[1] * %s);", fKLMMatrix.c_str(), wind, wind);
69
70    // Determine the amount of additional coverage to subtract out for the flat edge (P3 -> P0).
71    s->declareGlobal(fEdgeDistanceEquation);
72    s->codeAppendf("short edgeidx0 = %s > 0 ? 3 : 0;", wind);
73    s->codeAppendf("float2 edgept0 = %s[edgeidx0];", pts);
74    s->codeAppendf("float2 edgept1 = %s[3 - edgeidx0];", pts);
75    Shader::EmitEdgeDistanceEquation(s, "edgept0", "edgept1", fEdgeDistanceEquation.c_str());
76
77    this->onEmitSetupCode(s, pts, repetitionID, vars);
78}
79
80void GrCCCubicShader::onEmitVaryings(GrGLSLVaryingHandler* varyingHandler,
81                                     GrGLSLVarying::Scope scope, SkString* code,
82                                     const char* position, const char* inputCoverage,
83                                     const char* /*wind*/) {
84    SkASSERT(!inputCoverage);
85
86    fKLMD.reset(kFloat4_GrSLType, scope);
87    varyingHandler->addVarying("klmd", &fKLMD);
88    code->appendf("float3 klm = float3(%s, 1) * %s;", position, fKLMMatrix.c_str());
89    code->appendf("float d = dot(float3(%s, 1), %s);", position, fEdgeDistanceEquation.c_str());
90    code->appendf("%s = float4(klm, d);", OutName(fKLMD));
91
92    this->onEmitVaryings(varyingHandler, scope, code);
93}
94
95void GrCCCubicShader::onEmitFragmentCode(GrGLSLPPFragmentBuilder* f,
96                                         const char* outputCoverage) const {
97    f->codeAppendf("float k = %s.x, l = %s.y, m = %s.z, d = %s.w;",
98                   fKLMD.fsIn(), fKLMD.fsIn(), fKLMD.fsIn(), fKLMD.fsIn());
99
100    this->emitCoverage(f, outputCoverage);
101
102    // Wind is the sign of both L and/or M. Take the sign of whichever has the larger magnitude.
103    // (In reality, either would be fine because we chop cubics with more than a half pixel of
104    // padding around the L & M lines, so neither should approach zero.)
105    f->codeAppend ("half wind = sign(l + m);");
106    f->codeAppendf("%s *= wind;", outputCoverage);
107}
108
109void GrCCCubicHullShader::onEmitVaryings(GrGLSLVaryingHandler* varyingHandler,
110                                         GrGLSLVarying::Scope scope, SkString* code) {
111    fGradMatrix.reset(kFloat2x2_GrSLType, scope);
112    varyingHandler->addVarying("grad_matrix", &fGradMatrix);
113    // "klm" was just defined by the base class.
114    code->appendf("%s[0] = 3 * klm[0] * %s[0].xy;", OutName(fGradMatrix), fKLMMatrix.c_str());
115    code->appendf("%s[1] = -klm[1] * %s[2].xy - klm[2] * %s[1].xy;",
116                    OutName(fGradMatrix), fKLMMatrix.c_str(), fKLMMatrix.c_str());
117}
118
119void GrCCCubicHullShader::emitCoverage(GrGLSLPPFragmentBuilder* f,
120                                       const char* outputCoverage) const {
121    // k,l,m,d are defined by the base class.
122    f->codeAppend ("float f = k*k*k - l*m;");
123    f->codeAppendf("float2 grad_f = %s * float2(k, 1);", fGradMatrix.fsIn());
124    f->codeAppendf("%s = clamp(0.5 - f * inversesqrt(dot(grad_f, grad_f)), 0, 1);", outputCoverage);
125    f->codeAppendf("%s += min(d, 0);", outputCoverage); // Flat edge opposite the curve.
126}
127
128void GrCCCubicCornerShader::onEmitSetupCode(GrGLSLVertexGeoBuilder* s, const char* pts,
129                                            const char* repetitionID, GeometryVars* vars) const {
130    s->codeAppendf("float2 corner = %s[%s * 3];", pts, repetitionID);
131    vars->fCornerVars.fPoint = "corner";
132}
133
134void GrCCCubicCornerShader::onEmitVaryings(GrGLSLVaryingHandler* varyingHandler,
135                                           GrGLSLVarying::Scope scope, SkString* code) {
136    fdKLMDdx.reset(kFloat4_GrSLType, scope);
137    varyingHandler->addFlatVarying("dklmddx", &fdKLMDdx);
138    code->appendf("%s = float4(%s[0].x, %s[1].x, %s[2].x, %s.x);",
139                  OutName(fdKLMDdx), fKLMMatrix.c_str(), fKLMMatrix.c_str(),
140                  fKLMMatrix.c_str(), fEdgeDistanceEquation.c_str());
141
142    fdKLMDdy.reset(kFloat4_GrSLType, scope);
143    varyingHandler->addFlatVarying("dklmddy", &fdKLMDdy);
144    code->appendf("%s = float4(%s[0].y, %s[1].y, %s[2].y, %s.y);",
145                  OutName(fdKLMDdy), fKLMMatrix.c_str(), fKLMMatrix.c_str(),
146                  fKLMMatrix.c_str(), fEdgeDistanceEquation.c_str());
147}
148
149void GrCCCubicCornerShader::emitCoverage(GrGLSLPPFragmentBuilder* f,
150                                         const char* outputCoverage) const {
151    f->codeAppendf("float2x4 grad_klmd = float2x4(%s, %s);", fdKLMDdx.fsIn(), fdKLMDdy.fsIn());
152
153    // Erase what the previous hull shader wrote. We don't worry about the two corners falling on
154    // the same pixel because those cases should have been weeded out by this point.
155    // k,l,m,d are defined by the base class.
156    f->codeAppend ("float f = k*k*k - l*m;");
157    f->codeAppend ("float2 grad_f = float3(3*k*k, -m, -l) * float2x3(grad_klmd);");
158    f->codeAppendf("%s = -clamp(0.5 - f * inversesqrt(dot(grad_f, grad_f)), 0, 1);",
159                   outputCoverage);
160    f->codeAppendf("%s -= d;", outputCoverage);
161
162    // Use software msaa to estimate actual coverage at the corner pixels.
163    const int sampleCount = Shader::DefineSoftSampleLocations(f, "samples");
164    f->codeAppendf("float4 klmd_center = float4(%s.xyz, %s.w + 0.5);",
165                   fKLMD.fsIn(), fKLMD.fsIn());
166    f->codeAppendf("for (int i = 0; i < %i; ++i) {", sampleCount);
167    f->codeAppend (    "float4 klmd = grad_klmd * samples[i] + klmd_center;");
168    f->codeAppend (    "half f = klmd.y * klmd.z - klmd.x * klmd.x * klmd.x;");
169    f->codeAppendf(    "%s += all(greaterThan(half4(f, klmd.y, klmd.z, klmd.w), "
170                                             "half4(0))) ? %f : 0;",
171                       outputCoverage, 1.0 / sampleCount);
172    f->codeAppend ("}");
173}
174