1/*
2 * Copyright 2018 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 "src/gpu/effects/GrSkSLFP.h"
9
10#include "include/effects/SkRuntimeEffect.h"
11#include "include/private/GrContext_Base.h"
12#include "src/gpu/GrBaseContextPriv.h"
13#include "src/gpu/GrTexture.h"
14#include "src/sksl/SkSLUtil.h"
15
16#include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
17#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
18#include "src/gpu/glsl/GrGLSLProgramBuilder.h"
19
20class GrGLSLSkSLFP : public GrGLSLFragmentProcessor {
21public:
22 GrGLSLSkSLFP(SkSL::PipelineStageArgs&& args) : fArgs(std::move(args)) {}
23
24 SkSL::String expandFormatArgs(const SkSL::String& raw,
25 EmitArgs& args,
26 std::vector<SkSL::Compiler::FormatArg>::const_iterator& fmtArg,
27 const char* coordsName) {
28 SkSL::String result;
29 int substringStartIndex = 0;
30 for (size_t i = 0; i < raw.length(); ++i) {
31 char c = raw[i];
32 if (c == '%') {
33 result += SkSL::StringFragment(raw.c_str() + substringStartIndex,
34 i - substringStartIndex);
35 ++i;
36 c = raw[i];
37 switch (c) {
38 case 's': {
39 const SkSL::Compiler::FormatArg& arg = *fmtArg++;
40 switch (arg.fKind) {
41 case SkSL::Compiler::FormatArg::Kind::kInput:
42 result += args.fInputColor;
43 break;
44 case SkSL::Compiler::FormatArg::Kind::kOutput:
45 result += args.fOutputColor;
46 break;
47 case SkSL::Compiler::FormatArg::Kind::kCoords:
48 result += coordsName;
49 break;
50 case SkSL::Compiler::FormatArg::Kind::kUniform:
51 result += args.fUniformHandler->getUniformCStr(
52 fUniformHandles[arg.fIndex]);
53 break;
54 case SkSL::Compiler::FormatArg::Kind::kChildProcessor: {
55 SkSL::String coords = this->expandFormatArgs(arg.fCoords, args,
56 fmtArg, coordsName);
57 result += this->invokeChild(arg.fIndex, args, coords).c_str();
58 break;
59 }
60 case SkSL::Compiler::FormatArg::Kind::kFunctionName:
61 SkASSERT((int) fFunctionNames.size() > arg.fIndex);
62 result += fFunctionNames[arg.fIndex].c_str();
63 break;
64 }
65 break;
66 }
67 default:
68 result += c;
69 }
70 substringStartIndex = i + 1;
71 }
72 }
73 result += SkSL::StringFragment(raw.c_str() + substringStartIndex,
74 raw.length() - substringStartIndex);
75 return result;
76 }
77
78 void emitCode(EmitArgs& args) override {
79 const GrSkSLFP& fp = args.fFp.cast<GrSkSLFP>();
80 for (const auto& v : fp.fEffect->inputs()) {
81 if (v.fQualifier == SkRuntimeEffect::Variable::Qualifier::kUniform) {
82 auto handle = args.fUniformHandler->addUniformArray(&fp,
83 kFragment_GrShaderFlag,
84 v.fGPUType,
85 v.fName.c_str(),
86 v.isArray() ? v.fCount : 0);
87 fUniformHandles.push_back(handle);
88 }
89 }
90 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
91 SkASSERT(args.fTransformedCoords.count() == 1);
92 SkString coords = fragBuilder->ensureCoords2D(args.fTransformedCoords[0].fVaryingPoint);
93 std::vector<SkString> childNames;
94 // We need to ensure that we call invokeChild on each child FP at least once.
95 // Any child FP that isn't sampled won't trigger a call otherwise, leading to asserts later.
96 for (int i = 0; i < this->numChildProcessors(); ++i) {
97 (void)this->invokeChild(i, args, SkSL::String("_coords"));
98 }
99 for (const auto& f : fArgs.fFunctions) {
100 fFunctionNames.emplace_back();
101 auto fmtArgIter = f.fFormatArgs.cbegin();
102 SkSL::String body =
103 this->expandFormatArgs(f.fBody.c_str(), args, fmtArgIter, coords.c_str());
104 SkASSERT(fmtArgIter == f.fFormatArgs.cend());
105 fragBuilder->emitFunction(f.fReturnType,
106 f.fName.c_str(),
107 f.fParameters.size(),
108 f.fParameters.data(),
109 body.c_str(),
110 &fFunctionNames.back());
111 }
112 auto fmtArgIter = fArgs.fFormatArgs.cbegin();
113 fragBuilder->codeAppend(this->expandFormatArgs(fArgs.fCode.c_str(), args, fmtArgIter,
114 coords.c_str()).c_str());
115 SkASSERT(fmtArgIter == fArgs.fFormatArgs.cend());
116 }
117
118 void onSetData(const GrGLSLProgramDataManager& pdman,
119 const GrFragmentProcessor& _proc) override {
120 size_t uniIndex = 0;
121 const GrSkSLFP& outer = _proc.cast<GrSkSLFP>();
122 const uint8_t* inputs = outer.fInputs->bytes();
123 for (const auto& v : outer.fEffect->inputs()) {
124 if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kUniform) {
125 continue;
126 }
127
128 const float* data = reinterpret_cast<const float*>(inputs + v.fOffset);
129 switch (v.fType) {
130 case SkRuntimeEffect::Variable::Type::kFloat:
131 pdman.set1fv(fUniformHandles[uniIndex++], v.fCount, data);
132 break;
133 case SkRuntimeEffect::Variable::Type::kFloat2:
134 pdman.set2fv(fUniformHandles[uniIndex++], v.fCount, data);
135 break;
136 case SkRuntimeEffect::Variable::Type::kFloat3:
137 pdman.set3fv(fUniformHandles[uniIndex++], v.fCount, data);
138 break;
139 case SkRuntimeEffect::Variable::Type::kFloat4:
140 pdman.set4fv(fUniformHandles[uniIndex++], v.fCount, data);
141 break;
142 case SkRuntimeEffect::Variable::Type::kFloat2x2:
143 pdman.setMatrix2fv(fUniformHandles[uniIndex++], v.fCount, data);
144 break;
145 case SkRuntimeEffect::Variable::Type::kFloat3x3:
146 pdman.setMatrix3fv(fUniformHandles[uniIndex++], v.fCount, data);
147 break;
148 case SkRuntimeEffect::Variable::Type::kFloat4x4:
149 pdman.setMatrix4fv(fUniformHandles[uniIndex++], v.fCount, data);
150 break;
151 default:
152 SkDEBUGFAIL("Unsupported uniform type");
153 break;
154 }
155 }
156 }
157
158 // nearly-finished GLSL; still contains printf-style "%s" format tokens
159 SkSL::PipelineStageArgs fArgs;
160 std::vector<UniformHandle> fUniformHandles;
161 std::vector<SkString> fFunctionNames;
162};
163
164std::unique_ptr<GrSkSLFP> GrSkSLFP::Make(GrContext_Base* context, sk_sp<SkRuntimeEffect> effect,
165 const char* name, sk_sp<SkData> inputs,
166 const SkMatrix* matrix) {
167 if (inputs->size() != effect->inputSize()) {
168 return nullptr;
169 }
170 return std::unique_ptr<GrSkSLFP>(new GrSkSLFP(
171 context->priv().caps()->refShaderCaps(), context->priv().getShaderErrorHandler(),
172 std::move(effect), name, std::move(inputs), matrix));
173}
174
175GrSkSLFP::GrSkSLFP(sk_sp<const GrShaderCaps> shaderCaps, ShaderErrorHandler* shaderErrorHandler,
176 sk_sp<SkRuntimeEffect> effect, const char* name, sk_sp<SkData> inputs,
177 const SkMatrix* matrix)
178 : INHERITED(kGrSkSLFP_ClassID, kNone_OptimizationFlags)
179 , fShaderCaps(std::move(shaderCaps))
180 , fShaderErrorHandler(shaderErrorHandler)
181 , fEffect(std::move(effect))
182 , fName(name)
183 , fInputs(std::move(inputs)) {
184 if (matrix) {
185 fCoordTransform = GrCoordTransform(*matrix);
186 }
187 this->addCoordTransform(&fCoordTransform);
188}
189
190GrSkSLFP::GrSkSLFP(const GrSkSLFP& other)
191 : INHERITED(kGrSkSLFP_ClassID, kNone_OptimizationFlags)
192 , fShaderCaps(other.fShaderCaps)
193 , fShaderErrorHandler(other.fShaderErrorHandler)
194 , fEffect(other.fEffect)
195 , fName(other.fName)
196 , fInputs(other.fInputs) {
197 SkASSERT(other.numCoordTransforms() == 1);
198 fCoordTransform = other.fCoordTransform;
199 this->addCoordTransform(&fCoordTransform);
200}
201
202const char* GrSkSLFP::name() const {
203 return fName;
204}
205
206void GrSkSLFP::addChild(std::unique_ptr<GrFragmentProcessor> child) {
207 child->setSampledWithExplicitCoords(true);
208 this->registerChildProcessor(std::move(child));
209}
210
211GrGLSLFragmentProcessor* GrSkSLFP::onCreateGLSLInstance() const {
212 // Note: This is actually SkSL (again) but with inline format specifiers.
213 SkSL::PipelineStageArgs args;
214 fEffect->toPipelineStage(fInputs->data(), fShaderCaps.get(), fShaderErrorHandler, &args);
215 return new GrGLSLSkSLFP(std::move(args));
216}
217
218void GrSkSLFP::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {
219 // In the unlikely event of a hash collision, we also include the input size in the key.
220 // That ensures that we will (at worst) use the wrong program, but one that expects the same
221 // amount of input data.
222 b->add32(fEffect->hash());
223 b->add32(SkToU32(fInputs->size()));
224 const uint8_t* inputs = fInputs->bytes();
225 for (const auto& v : fEffect->inputs()) {
226 if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kIn) {
227 continue;
228 }
229 // 'in' arrays are not supported
230 SkASSERT(!v.isArray());
231 switch (v.fType) {
232 case SkRuntimeEffect::Variable::Type::kBool:
233 b->add32(inputs[v.fOffset]);
234 break;
235 case SkRuntimeEffect::Variable::Type::kInt:
236 case SkRuntimeEffect::Variable::Type::kFloat:
237 b->add32(*(int32_t*)(inputs + v.fOffset));
238 break;
239 default:
240 SkDEBUGFAIL("Unsupported input variable type");
241 break;
242 }
243 }
244}
245
246bool GrSkSLFP::onIsEqual(const GrFragmentProcessor& other) const {
247 const GrSkSLFP& sk = other.cast<GrSkSLFP>();
248 return fEffect->hash() == sk.fEffect->hash() && fInputs->equals(sk.fInputs.get());
249}
250
251std::unique_ptr<GrFragmentProcessor> GrSkSLFP::clone() const {
252 std::unique_ptr<GrSkSLFP> result(new GrSkSLFP(*this));
253 for (int i = 0; i < this->numChildProcessors(); ++i) {
254 result->addChild(this->childProcessor(i).clone());
255 }
256 return std::unique_ptr<GrFragmentProcessor>(result.release());
257}
258
259/**************************************************************************************************/
260
261GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSkSLFP);
262
263#if GR_TEST_UTILS
264
265#include "include/effects/SkArithmeticImageFilter.h"
266#include "include/gpu/GrContext.h"
267#include "src/gpu/effects/generated/GrConstColorProcessor.h"
268
269extern const char* SKSL_ARITHMETIC_SRC;
270extern const char* SKSL_DITHER_SRC;
271extern const char* SKSL_OVERDRAW_SRC;
272
273using Value = SkSL::Program::Settings::Value;
274
275std::unique_ptr<GrFragmentProcessor> GrSkSLFP::TestCreate(GrProcessorTestData* d) {
276 int type = d->fRandom->nextULessThan(3);
277 switch (type) {
278 case 0: {
279 static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_DITHER_SRC)));
280 int rangeType = d->fRandom->nextULessThan(3);
281 auto result = GrSkSLFP::Make(d->context(), effect, "Dither",
282 SkData::MakeWithCopy(&rangeType, sizeof(rangeType)));
283 return std::unique_ptr<GrFragmentProcessor>(result.release());
284 }
285 case 1: {
286 static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_ARITHMETIC_SRC)));
287 ArithmeticFPInputs inputs{d->fRandom->nextF(), d->fRandom->nextF(), d->fRandom->nextF(),
288 d->fRandom->nextF(), d->fRandom->nextBool()};
289 auto result = GrSkSLFP::Make(d->context(), effect, "Arithmetic",
290 SkData::MakeWithCopy(&inputs, sizeof(inputs)));
291 result->addChild(GrConstColorProcessor::Make(
292 SK_PMColor4fWHITE, GrConstColorProcessor::InputMode::kIgnore));
293 return std::unique_ptr<GrFragmentProcessor>(result.release());
294 }
295 case 2: {
296 static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_OVERDRAW_SRC)));
297 SkColor4f inputs[6];
298 for (int i = 0; i < 6; ++i) {
299 inputs[i] = SkColor4f::FromBytes_RGBA(d->fRandom->nextU());
300 }
301 auto result = GrSkSLFP::Make(d->context(), effect, "Overdraw",
302 SkData::MakeWithCopy(&inputs, sizeof(inputs)));
303 return std::unique_ptr<GrFragmentProcessor>(result.release());
304 }
305 }
306 SK_ABORT("unreachable");
307}
308
309#endif
310