Update rive-cpp to 2.0 version
[platform/core/uifw/rive-tizen.git] / submodule / skia / src / gpu / ganesh / GrFragmentProcessor.cpp
1 /*
2 * Copyright 2015 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/ganesh/GrFragmentProcessor.h"
9
10 #include "src/core/SkRuntimeEffectPriv.h"
11 #include "src/gpu/KeyBuilder.h"
12 #include "src/gpu/ganesh/GrPipeline.h"
13 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
14 #include "src/gpu/ganesh/GrShaderCaps.h"
15 #include "src/gpu/ganesh/effects/GrBlendFragmentProcessor.h"
16 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
17 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
18 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
19 #include "src/gpu/ganesh/glsl/GrGLSLProgramBuilder.h"
20 #include "src/gpu/ganesh/glsl/GrGLSLProgramDataManager.h"
21 #include "src/gpu/ganesh/glsl/GrGLSLUniformHandler.h"
22
23 bool GrFragmentProcessor::isEqual(const GrFragmentProcessor& that) const {
24     if (this->classID() != that.classID()) {
25         return false;
26     }
27     if (this->sampleUsage() != that.sampleUsage()) {
28         return false;
29     }
30     if (!this->onIsEqual(that)) {
31         return false;
32     }
33     if (this->numChildProcessors() != that.numChildProcessors()) {
34         return false;
35     }
36     for (int i = 0; i < this->numChildProcessors(); ++i) {
37         auto thisChild = this->childProcessor(i),
38              thatChild = that .childProcessor(i);
39         if (SkToBool(thisChild) != SkToBool(thatChild)) {
40             return false;
41         }
42         if (thisChild && !thisChild->isEqual(*thatChild)) {
43             return false;
44         }
45     }
46     return true;
47 }
48
49 void GrFragmentProcessor::visitProxies(const GrVisitProxyFunc& func) const {
50     this->visitTextureEffects([&func](const GrTextureEffect& te) {
51         func(te.view().proxy(), te.samplerState().mipmapped());
52     });
53 }
54
55 void GrFragmentProcessor::visitTextureEffects(
56         const std::function<void(const GrTextureEffect&)>& func) const {
57     if (auto* te = this->asTextureEffect()) {
58         func(*te);
59     }
60     for (auto& child : fChildProcessors) {
61         if (child) {
62             child->visitTextureEffects(func);
63         }
64     }
65 }
66
67 void GrFragmentProcessor::visitWithImpls(
68         const std::function<void(const GrFragmentProcessor&, ProgramImpl&)>& f,
69         ProgramImpl& impl) const {
70     f(*this, impl);
71     SkASSERT(impl.numChildProcessors() == this->numChildProcessors());
72     for (int i = 0; i < this->numChildProcessors(); ++i) {
73         if (const auto* child = this->childProcessor(i)) {
74             child->visitWithImpls(f, *impl.childProcessor(i));
75         }
76     }
77 }
78
79 GrTextureEffect* GrFragmentProcessor::asTextureEffect() {
80     if (this->classID() == kGrTextureEffect_ClassID) {
81         return static_cast<GrTextureEffect*>(this);
82     }
83     return nullptr;
84 }
85
86 const GrTextureEffect* GrFragmentProcessor::asTextureEffect() const {
87     if (this->classID() == kGrTextureEffect_ClassID) {
88         return static_cast<const GrTextureEffect*>(this);
89     }
90     return nullptr;
91 }
92
93 #if GR_TEST_UTILS
94 static void recursive_dump_tree_info(const GrFragmentProcessor& fp,
95                                      SkString indent,
96                                      SkString* text) {
97     for (int index = 0; index < fp.numChildProcessors(); ++index) {
98         text->appendf("\n%s(#%d) -> ", indent.c_str(), index);
99         if (const GrFragmentProcessor* childFP = fp.childProcessor(index)) {
100             text->append(childFP->dumpInfo());
101             indent.append("\t");
102             recursive_dump_tree_info(*childFP, indent, text);
103         } else {
104             text->append("null");
105         }
106     }
107 }
108
109 SkString GrFragmentProcessor::dumpTreeInfo() const {
110     SkString text = this->dumpInfo();
111     recursive_dump_tree_info(*this, SkString("\t"), &text);
112     text.append("\n");
113     return text;
114 }
115 #endif
116
117 std::unique_ptr<GrFragmentProcessor::ProgramImpl> GrFragmentProcessor::makeProgramImpl() const {
118     std::unique_ptr<ProgramImpl> impl = this->onMakeProgramImpl();
119     impl->fChildProcessors.push_back_n(fChildProcessors.count());
120     for (int i = 0; i < fChildProcessors.count(); ++i) {
121         impl->fChildProcessors[i] = fChildProcessors[i] ? fChildProcessors[i]->makeProgramImpl()
122                                                         : nullptr;
123     }
124     return impl;
125 }
126
127 int GrFragmentProcessor::numNonNullChildProcessors() const {
128     return std::count_if(fChildProcessors.begin(), fChildProcessors.end(),
129                          [](const auto& c) { return c != nullptr; });
130 }
131
132 #ifdef SK_DEBUG
133 bool GrFragmentProcessor::isInstantiated() const {
134     bool result = true;
135     this->visitTextureEffects([&result](const GrTextureEffect& te) {
136         if (!te.texture()) {
137             result = false;
138         }
139     });
140     return result;
141 }
142 #endif
143
144 void GrFragmentProcessor::registerChild(std::unique_ptr<GrFragmentProcessor> child,
145                                         SkSL::SampleUsage sampleUsage) {
146     SkASSERT(sampleUsage.isSampled());
147
148     if (!child) {
149         fChildProcessors.push_back(nullptr);
150         return;
151     }
152
153     // The child should not have been attached to another FP already and not had any sampling
154     // strategy set on it.
155     SkASSERT(!child->fParent && !child->sampleUsage().isSampled());
156
157     // Configure child's sampling state first
158     child->fUsage = sampleUsage;
159
160     // Propagate the "will read dest-color" flag up to parent FPs.
161     if (child->willReadDstColor()) {
162         this->setWillReadDstColor();
163     }
164
165     // If this child receives passthrough or matrix transformed coords from its parent then note
166     // that the parent's coords are used indirectly to ensure that they aren't omitted.
167     if ((sampleUsage.isPassThrough() || sampleUsage.isUniformMatrix()) &&
168         child->usesSampleCoords()) {
169         fFlags |= kUsesSampleCoordsIndirectly_Flag;
170     }
171
172     // Record that the child is attached to us; this FP is the source of any uniform data needed
173     // to evaluate the child sample matrix.
174     child->fParent = this;
175     fChildProcessors.push_back(std::move(child));
176
177     // Validate: our sample strategy comes from a parent we shouldn't have yet.
178     SkASSERT(!fUsage.isSampled() && !fParent);
179 }
180
181 void GrFragmentProcessor::cloneAndRegisterAllChildProcessors(const GrFragmentProcessor& src) {
182     for (int i = 0; i < src.numChildProcessors(); ++i) {
183         if (auto fp = src.childProcessor(i)) {
184             this->registerChild(fp->clone(), fp->sampleUsage());
185         } else {
186             this->registerChild(nullptr);
187         }
188     }
189 }
190
191 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MakeColor(SkPMColor4f color) {
192     // Use ColorFilter signature/factory to get the constant output for constant input optimization
193     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
194         uniform half4 color;
195         half4 main(half4 inColor) { return color; }
196     )");
197     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
198     return GrSkSLFP::Make(effect, "color_fp", /*inputFP=*/nullptr,
199                           color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
200                                            : GrSkSLFP::OptFlags::kNone,
201                           "color", color);
202 }
203
204 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MulInputByChildAlpha(
205         std::unique_ptr<GrFragmentProcessor> fp) {
206     if (!fp) {
207         return nullptr;
208     }
209     return GrBlendFragmentProcessor::Make<SkBlendMode::kSrcIn>(/*src=*/nullptr, std::move(fp));
210 }
211
212 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ApplyPaintAlpha(
213         std::unique_ptr<GrFragmentProcessor> child) {
214     SkASSERT(child);
215     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
216         uniform colorFilter fp;
217         half4 main(half4 inColor) {
218             return fp.eval(inColor.rgb1) * inColor.a;
219         }
220     )");
221     return GrSkSLFP::Make(effect, "ApplyPaintAlpha", /*inputFP=*/nullptr,
222                           GrSkSLFP::OptFlags::kPreservesOpaqueInput |
223                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
224                           "fp", std::move(child));
225 }
226
227 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ModulateRGBA(
228         std::unique_ptr<GrFragmentProcessor> inputFP, const SkPMColor4f& color) {
229     auto colorFP = MakeColor(color);
230     return GrBlendFragmentProcessor::Make<SkBlendMode::kModulate>(std::move(colorFP),
231                                                                   std::move(inputFP));
232 }
233
234 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ClampOutput(
235         std::unique_ptr<GrFragmentProcessor> fp) {
236     SkASSERT(fp);
237     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
238         half4 main(half4 inColor) {
239             return saturate(inColor);
240         }
241     )");
242     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
243     return GrSkSLFP::Make(
244             effect, "Clamp", std::move(fp), GrSkSLFP::OptFlags::kPreservesOpaqueInput);
245 }
246
247 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SwizzleOutput(
248         std::unique_ptr<GrFragmentProcessor> fp, const skgpu::Swizzle& swizzle) {
249     class SwizzleFragmentProcessor : public GrFragmentProcessor {
250     public:
251         static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp,
252                                                          const skgpu::Swizzle& swizzle) {
253             return std::unique_ptr<GrFragmentProcessor>(
254                     new SwizzleFragmentProcessor(std::move(fp), swizzle));
255         }
256
257         const char* name() const override { return "Swizzle"; }
258
259         std::unique_ptr<GrFragmentProcessor> clone() const override {
260             return Make(this->childProcessor(0)->clone(), fSwizzle);
261         }
262
263     private:
264         SwizzleFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp,
265                                  const skgpu::Swizzle& swizzle)
266                 : INHERITED(kSwizzleFragmentProcessor_ClassID, ProcessorOptimizationFlags(fp.get()))
267                 , fSwizzle(swizzle) {
268             this->registerChild(std::move(fp));
269         }
270
271         std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
272             class Impl : public ProgramImpl {
273             public:
274                 void emitCode(EmitArgs& args) override {
275                     SkString childColor = this->invokeChild(0, args);
276
277                     const SwizzleFragmentProcessor& sfp = args.fFp.cast<SwizzleFragmentProcessor>();
278                     const skgpu::Swizzle& swizzle = sfp.fSwizzle;
279                     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
280
281                     fragBuilder->codeAppendf("return %s.%s;",
282                                              childColor.c_str(), swizzle.asString().c_str());
283                 }
284             };
285             return std::make_unique<Impl>();
286         }
287
288         void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const override {
289             b->add32(fSwizzle.asKey());
290         }
291
292         bool onIsEqual(const GrFragmentProcessor& other) const override {
293             const SwizzleFragmentProcessor& sfp = other.cast<SwizzleFragmentProcessor>();
294             return fSwizzle == sfp.fSwizzle;
295         }
296
297         SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
298             return fSwizzle.applyTo(ConstantOutputForConstantInput(this->childProcessor(0), input));
299         }
300
301         skgpu::Swizzle fSwizzle;
302
303         using INHERITED = GrFragmentProcessor;
304     };
305
306     if (!fp) {
307         return nullptr;
308     }
309     if (skgpu::Swizzle::RGBA() == swizzle) {
310         return fp;
311     }
312     return SwizzleFragmentProcessor::Make(std::move(fp), swizzle);
313 }
314
315 //////////////////////////////////////////////////////////////////////////////
316
317 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::OverrideInput(
318         std::unique_ptr<GrFragmentProcessor> fp, const SkPMColor4f& color) {
319     if (!fp) {
320         return nullptr;
321     }
322     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
323         uniform colorFilter fp;  // Declared as colorFilter so we can pass a color
324         uniform half4 color;
325         half4 main(half4 inColor) {
326             return fp.eval(color);
327         }
328     )");
329     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
330     return GrSkSLFP::Make(effect, "OverrideInput", /*inputFP=*/nullptr,
331                           color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
332                                            : GrSkSLFP::OptFlags::kNone,
333                           "fp", std::move(fp),
334                           "color", color);
335 }
336
337 //////////////////////////////////////////////////////////////////////////////
338
339 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DisableCoverageAsAlpha(
340         std::unique_ptr<GrFragmentProcessor> fp) {
341     if (!fp || !fp->compatibleWithCoverageAsAlpha()) {
342         return fp;
343     }
344     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
345         half4 main(half4 inColor) { return inColor; }
346     )");
347     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
348     return GrSkSLFP::Make(effect, "DisableCoverageAsAlpha", std::move(fp),
349                           GrSkSLFP::OptFlags::kPreservesOpaqueInput);
350 }
351
352 //////////////////////////////////////////////////////////////////////////////
353
354 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::UseDestColorAsInput(
355         std::unique_ptr<GrFragmentProcessor> fp) {
356     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForBlender, R"(
357         uniform colorFilter fp;  // Declared as colorFilter so we can pass a color
358         half4 main(half4 src, half4 dst) {
359             return fp.eval(dst);
360         }
361     )");
362     return GrSkSLFP::Make(effect, "UseDestColorAsInput", /*inputFP=*/nullptr,
363                           GrSkSLFP::OptFlags::kNone, "fp", std::move(fp));
364 }
365
366 //////////////////////////////////////////////////////////////////////////////
367
368 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Compose(
369         std::unique_ptr<GrFragmentProcessor> f, std::unique_ptr<GrFragmentProcessor> g) {
370     class ComposeProcessor : public GrFragmentProcessor {
371     public:
372         static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> f,
373                                                          std::unique_ptr<GrFragmentProcessor> g) {
374             return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(std::move(f),
375                                                                              std::move(g)));
376         }
377
378         const char* name() const override { return "Compose"; }
379
380         std::unique_ptr<GrFragmentProcessor> clone() const override {
381             return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(*this));
382         }
383
384     private:
385         std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
386             class Impl : public ProgramImpl {
387             public:
388                 void emitCode(EmitArgs& args) override {
389                     SkString result = this->invokeChild(1, args);         // g(x)
390                     result = this->invokeChild(0, result.c_str(), args);  // f(g(x))
391                     args.fFragBuilder->codeAppendf("return %s;", result.c_str());
392                 }
393             };
394             return std::make_unique<Impl>();
395         }
396
397         ComposeProcessor(std::unique_ptr<GrFragmentProcessor> f,
398                          std::unique_ptr<GrFragmentProcessor> g)
399                 : INHERITED(kSeriesFragmentProcessor_ClassID,
400                             f->optimizationFlags() & g->optimizationFlags()) {
401             this->registerChild(std::move(f));
402             this->registerChild(std::move(g));
403         }
404
405         ComposeProcessor(const ComposeProcessor& that) : INHERITED(that) {}
406
407         void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
408
409         bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
410
411         SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& inColor) const override {
412             SkPMColor4f color = inColor;
413             color = ConstantOutputForConstantInput(this->childProcessor(1), color);
414             color = ConstantOutputForConstantInput(this->childProcessor(0), color);
415             return color;
416         }
417
418         using INHERITED = GrFragmentProcessor;
419     };
420
421     // Allow either of the composed functions to be null.
422     if (f == nullptr) {
423         return g;
424     }
425     if (g == nullptr) {
426         return f;
427     }
428
429     // Run an optimization pass on this composition.
430     GrProcessorAnalysisColor inputColor;
431     inputColor.setToUnknown();
432
433     std::unique_ptr<GrFragmentProcessor> series[2] = {std::move(g), std::move(f)};
434     GrColorFragmentProcessorAnalysis info(inputColor, series, SK_ARRAY_COUNT(series));
435
436     SkPMColor4f knownColor;
437     int leadingFPsToEliminate = info.initialProcessorsToEliminate(&knownColor);
438     switch (leadingFPsToEliminate) {
439         default:
440             // We shouldn't eliminate more than we started with.
441             SkASSERT(leadingFPsToEliminate <= 2);
442             [[fallthrough]];
443         case 0:
444             // Compose the two processors as requested.
445             return ComposeProcessor::Make(/*f=*/std::move(series[1]), /*g=*/std::move(series[0]));
446         case 1:
447             // Replace the first processor with a constant color.
448             return ComposeProcessor::Make(/*f=*/std::move(series[1]),
449                                           /*g=*/MakeColor(knownColor));
450         case 2:
451             // Replace the entire composition with a constant color.
452             return MakeColor(knownColor);
453     }
454 }
455
456 //////////////////////////////////////////////////////////////////////////////
457
458 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ColorMatrix(
459         std::unique_ptr<GrFragmentProcessor> child,
460         const float matrix[20],
461         bool unpremulInput,
462         bool clampRGBOutput,
463         bool premulOutput) {
464     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
465         uniform half4x4 m;
466         uniform half4   v;
467         uniform int unpremulInput;   // always specialized
468         uniform int clampRGBOutput;  // always specialized
469         uniform int premulOutput;    // always specialized
470         half4 main(half4 color) {
471             if (bool(unpremulInput)) {
472                 color = unpremul(color);
473             }
474             color = m * color + v;
475             if (bool(clampRGBOutput)) {
476                 color = saturate(color);
477             } else {
478                 color.a = saturate(color.a);
479             }
480             if (bool(premulOutput)) {
481                 color.rgb *= color.a;
482             }
483             return color;
484         }
485     )");
486     SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
487
488     SkM44 m44(matrix[ 0], matrix[ 1], matrix[ 2], matrix[ 3],
489               matrix[ 5], matrix[ 6], matrix[ 7], matrix[ 8],
490               matrix[10], matrix[11], matrix[12], matrix[13],
491               matrix[15], matrix[16], matrix[17], matrix[18]);
492     SkV4 v4 = {matrix[4], matrix[9], matrix[14], matrix[19]};
493     return GrSkSLFP::Make(effect, "ColorMatrix", std::move(child), GrSkSLFP::OptFlags::kNone,
494                           "m", m44,
495                           "v", v4,
496                           "unpremulInput",  GrSkSLFP::Specialize(unpremulInput  ? 1 : 0),
497                           "clampRGBOutput", GrSkSLFP::Specialize(clampRGBOutput ? 1 : 0),
498                           "premulOutput",   GrSkSLFP::Specialize(premulOutput   ? 1 : 0));
499 }
500
501 //////////////////////////////////////////////////////////////////////////////
502
503 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SurfaceColor() {
504     class SurfaceColorProcessor : public GrFragmentProcessor {
505     public:
506         static std::unique_ptr<GrFragmentProcessor> Make() {
507             return std::unique_ptr<GrFragmentProcessor>(new SurfaceColorProcessor());
508         }
509
510         std::unique_ptr<GrFragmentProcessor> clone() const override { return Make(); }
511
512         const char* name() const override { return "SurfaceColor"; }
513
514     private:
515         std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
516             class Impl : public ProgramImpl {
517             public:
518                 void emitCode(EmitArgs& args) override {
519                     const char* dstColor = args.fFragBuilder->dstColor();
520                     args.fFragBuilder->codeAppendf("return %s;", dstColor);
521                 }
522             };
523             return std::make_unique<Impl>();
524         }
525
526         SurfaceColorProcessor()
527                 : INHERITED(kSurfaceColorProcessor_ClassID, kNone_OptimizationFlags) {
528             this->setWillReadDstColor();
529         }
530
531         void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
532
533         bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
534
535         using INHERITED = GrFragmentProcessor;
536     };
537
538     return SurfaceColorProcessor::Make();
539 }
540
541 //////////////////////////////////////////////////////////////////////////////
542
543 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DeviceSpace(
544         std::unique_ptr<GrFragmentProcessor> fp) {
545     if (!fp) {
546         return nullptr;
547     }
548
549     class DeviceSpace : GrFragmentProcessor {
550     public:
551         static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
552             return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(fp)));
553         }
554
555     private:
556         DeviceSpace(std::unique_ptr<GrFragmentProcessor> fp)
557                 : GrFragmentProcessor(kDeviceSpace_ClassID, fp->optimizationFlags()) {
558             // Passing FragCoord here is the reason this is a subclass and not a runtime-FP.
559             this->registerChild(std::move(fp), SkSL::SampleUsage::FragCoord());
560         }
561
562         std::unique_ptr<GrFragmentProcessor> clone() const override {
563             auto child = this->childProcessor(0)->clone();
564             return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(child)));
565         }
566
567         SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& f) const override {
568             return this->childProcessor(0)->constantOutputForConstantInput(f);
569         }
570
571         std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
572             class Impl : public ProgramImpl {
573             public:
574                 Impl() = default;
575                 void emitCode(ProgramImpl::EmitArgs& args) override {
576                     auto child = this->invokeChild(0, args.fInputColor, args, "sk_FragCoord.xy");
577                     args.fFragBuilder->codeAppendf("return %s;", child.c_str());
578                 }
579             };
580             return std::make_unique<Impl>();
581         }
582
583         void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
584
585         bool onIsEqual(const GrFragmentProcessor& processor) const override { return true; }
586
587         const char* name() const override { return "DeviceSpace"; }
588     };
589
590     return DeviceSpace::Make(std::move(fp));
591 }
592
593 //////////////////////////////////////////////////////////////////////////////
594
595 #define CLIP_EDGE_SKSL              \
596     "const int kFillBW = 0;"        \
597     "const int kFillAA = 1;"        \
598     "const int kInverseFillBW = 2;" \
599     "const int kInverseFillAA = 3;"
600
601 static_assert(static_cast<int>(GrClipEdgeType::kFillBW) == 0);
602 static_assert(static_cast<int>(GrClipEdgeType::kFillAA) == 1);
603 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillBW) == 2);
604 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillAA) == 3);
605
606 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Rect(
607         std::unique_ptr<GrFragmentProcessor> inputFP, GrClipEdgeType edgeType, SkRect rect) {
608     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
609         uniform int edgeType;  // GrClipEdgeType, specialized
610         uniform float4 rectUniform;
611
612         half4 main(float2 xy, half4 inColor) {
613             half coverage;
614             if (edgeType == kFillBW || edgeType == kInverseFillBW) {
615                 // non-AA
616                 coverage = all(greaterThan(float4(sk_FragCoord.xy, rectUniform.zw),
617                                            float4(rectUniform.xy, sk_FragCoord.xy))) ? 1 : 0;
618             } else {
619                 // compute coverage relative to left and right edges, add, then subtract 1 to
620                 // account for double counting. And similar for top/bottom.
621                 half4 dists4 = clamp(half4(1, 1, -1, -1) *
622                                      half4(sk_FragCoord.xyxy - rectUniform), 0, 1);
623                 half2 dists2 = dists4.xy + dists4.zw - 1;
624                 coverage = dists2.x * dists2.y;
625             }
626
627             if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
628                 coverage = 1.0 - coverage;
629             }
630
631             return inColor * coverage;
632         }
633     )");
634
635     SkASSERT(rect.isSorted());
636     // The AA math in the shader evaluates to 0 at the uploaded coordinates, so outset by 0.5
637     // to interpolate from 0 at a half pixel inset and 1 at a half pixel outset of rect.
638     SkRect rectUniform = GrClipEdgeTypeIsAA(edgeType) ? rect.makeOutset(.5f, .5f) : rect;
639
640     return GrSkSLFP::Make(effect, "Rect", std::move(inputFP),
641                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
642                           "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
643                           "rectUniform", rectUniform);
644 }
645
646 GrFPResult GrFragmentProcessor::Circle(std::unique_ptr<GrFragmentProcessor> inputFP,
647                                        GrClipEdgeType edgeType,
648                                        SkPoint center,
649                                        float radius) {
650     // A radius below half causes the implicit insetting done by this processor to become
651     // inverted. We could handle this case by making the processor code more complicated.
652     if (radius < .5f && GrClipEdgeTypeIsInverseFill(edgeType)) {
653         return GrFPFailure(std::move(inputFP));
654     }
655
656     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
657         uniform int edgeType;  // GrClipEdgeType, specialized
658         // The circle uniform is (center.x, center.y, radius + 0.5, 1 / (radius + 0.5)) for regular
659         // fills and (..., radius - 0.5, 1 / (radius - 0.5)) for inverse fills.
660         uniform float4 circle;
661
662         half4 main(float2 xy, half4 inColor) {
663             // TODO: Right now the distance to circle calculation is performed in a space normalized
664             // to the radius and then denormalized. This is to mitigate overflow on devices that
665             // don't have full float.
666             half d;
667             if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
668                 d = half((length((circle.xy - sk_FragCoord.xy) * circle.w) - 1.0) * circle.z);
669             } else {
670                 d = half((1.0 - length((circle.xy - sk_FragCoord.xy) *  circle.w)) * circle.z);
671             }
672             if (edgeType == kFillAA || edgeType == kInverseFillAA) {
673                 return inColor * saturate(d);
674             } else {
675                 return d > 0.5 ? inColor : half4(0);
676             }
677         }
678     )");
679
680     SkScalar effectiveRadius = radius;
681     if (GrClipEdgeTypeIsInverseFill(edgeType)) {
682         effectiveRadius -= 0.5f;
683         // When the radius is 0.5 effectiveRadius is 0 which causes an inf * 0 in the shader.
684         effectiveRadius = std::max(0.001f, effectiveRadius);
685     } else {
686         effectiveRadius += 0.5f;
687     }
688     SkV4 circle = {center.fX, center.fY, effectiveRadius, SkScalarInvert(effectiveRadius)};
689
690     return GrFPSuccess(GrSkSLFP::Make(effect, "Circle", std::move(inputFP),
691                                       GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
692                                       "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
693                                       "circle", circle));
694 }
695
696 GrFPResult GrFragmentProcessor::Ellipse(std::unique_ptr<GrFragmentProcessor> inputFP,
697                                         GrClipEdgeType edgeType,
698                                         SkPoint center,
699                                         SkPoint radii,
700                                         const GrShaderCaps& caps) {
701     const bool medPrecision = !caps.floatIs32Bits();
702
703     // Small radii produce bad results on devices without full float.
704     if (medPrecision && (radii.fX < 0.5f || radii.fY < 0.5f)) {
705         return GrFPFailure(std::move(inputFP));
706     }
707     // Very narrow ellipses produce bad results on devices without full float
708     if (medPrecision && (radii.fX > 255*radii.fY || radii.fY > 255*radii.fX)) {
709         return GrFPFailure(std::move(inputFP));
710     }
711     // Very large ellipses produce bad results on devices without full float
712     if (medPrecision && (radii.fX > 16384 || radii.fY > 16384)) {
713         return GrFPFailure(std::move(inputFP));
714     }
715
716     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
717         uniform int edgeType;      // GrClipEdgeType, specialized
718         uniform int medPrecision;  // !sk_Caps.floatIs32Bits, specialized
719
720         uniform float4 ellipse;
721         uniform float2 scale;    // only for medPrecision
722
723         half4 main(float2 xy, half4 inColor) {
724             // d is the offset to the ellipse center
725             float2 d = sk_FragCoord.xy - ellipse.xy;
726             // If we're on a device with a "real" mediump then we'll do the distance computation in
727             // a space that is normalized by the larger radius or 128, whichever is smaller. The
728             // scale uniform will be scale, 1/scale. The inverse squared radii uniform values are
729             // already in this normalized space. The center is not.
730             if (bool(medPrecision)) {
731                 d *= scale.y;
732             }
733             float2 Z = d * ellipse.zw;
734             // implicit is the evaluation of (x/rx)^2 + (y/ry)^2 - 1.
735             float implicit = dot(Z, d) - 1;
736             // grad_dot is the squared length of the gradient of the implicit.
737             float grad_dot = 4 * dot(Z, Z);
738             // Avoid calling inversesqrt on zero.
739             if (bool(medPrecision)) {
740                 grad_dot = max(grad_dot, 6.1036e-5);
741             } else {
742                 grad_dot = max(grad_dot, 1.1755e-38);
743             }
744             float approx_dist = implicit * inversesqrt(grad_dot);
745             if (bool(medPrecision)) {
746                 approx_dist *= scale.x;
747             }
748
749             half alpha;
750             if (edgeType == kFillBW) {
751                 alpha = approx_dist > 0.0 ? 0.0 : 1.0;
752             } else if (edgeType == kFillAA) {
753                 alpha = saturate(0.5 - half(approx_dist));
754             } else if (edgeType == kInverseFillBW) {
755                 alpha = approx_dist > 0.0 ? 1.0 : 0.0;
756             } else {  // edgeType == kInverseFillAA
757                 alpha = saturate(0.5 + half(approx_dist));
758             }
759             return inColor * alpha;
760         }
761     )");
762
763     float invRXSqd;
764     float invRYSqd;
765     SkV2 scale = {1, 1};
766     // If we're using a scale factor to work around precision issues, choose the larger radius as
767     // the scale factor. The inv radii need to be pre-adjusted by the scale factor.
768     if (medPrecision) {
769         if (radii.fX > radii.fY) {
770             invRXSqd = 1.f;
771             invRYSqd = (radii.fX * radii.fX) / (radii.fY * radii.fY);
772             scale = {radii.fX, 1.f / radii.fX};
773         } else {
774             invRXSqd = (radii.fY * radii.fY) / (radii.fX * radii.fX);
775             invRYSqd = 1.f;
776             scale = {radii.fY, 1.f / radii.fY};
777         }
778     } else {
779         invRXSqd = 1.f / (radii.fX * radii.fX);
780         invRYSqd = 1.f / (radii.fY * radii.fY);
781     }
782     SkV4 ellipse = {center.fX, center.fY, invRXSqd, invRYSqd};
783
784     return GrFPSuccess(GrSkSLFP::Make(effect, "Ellipse", std::move(inputFP),
785                                       GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
786                                       "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
787                                       "medPrecision",  GrSkSLFP::Specialize<int>(medPrecision),
788                                       "ellipse", ellipse,
789                                       "scale", scale));
790 }
791
792 //////////////////////////////////////////////////////////////////////////////
793
794 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::HighPrecision(
795         std::unique_ptr<GrFragmentProcessor> fp) {
796     class HighPrecisionFragmentProcessor : public GrFragmentProcessor {
797     public:
798         static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
799             return std::unique_ptr<GrFragmentProcessor>(
800                     new HighPrecisionFragmentProcessor(std::move(fp)));
801         }
802
803         const char* name() const override { return "HighPrecision"; }
804
805         std::unique_ptr<GrFragmentProcessor> clone() const override {
806             return Make(this->childProcessor(0)->clone());
807         }
808
809     private:
810         HighPrecisionFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp)
811                 : INHERITED(kHighPrecisionFragmentProcessor_ClassID,
812                             ProcessorOptimizationFlags(fp.get())) {
813             this->registerChild(std::move(fp));
814         }
815
816         std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
817             class Impl : public ProgramImpl {
818             public:
819                 void emitCode(EmitArgs& args) override {
820                     SkString childColor = this->invokeChild(0, args);
821
822                     args.fFragBuilder->forceHighPrecision();
823                     args.fFragBuilder->codeAppendf("return %s;", childColor.c_str());
824                 }
825             };
826             return std::make_unique<Impl>();
827         }
828
829         void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
830         bool onIsEqual(const GrFragmentProcessor& other) const override { return true; }
831
832         SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
833             return ConstantOutputForConstantInput(this->childProcessor(0), input);
834         }
835
836         using INHERITED = GrFragmentProcessor;
837     };
838
839     return HighPrecisionFragmentProcessor::Make(std::move(fp));
840 }
841
842 //////////////////////////////////////////////////////////////////////////////
843
844 using ProgramImpl = GrFragmentProcessor::ProgramImpl;
845
846 void ProgramImpl::setData(const GrGLSLProgramDataManager& pdman,
847                           const GrFragmentProcessor& processor) {
848     this->onSetData(pdman, processor);
849 }
850
851 SkString ProgramImpl::invokeChild(int childIndex,
852                                   const char* inputColor,
853                                   const char* destColor,
854                                   EmitArgs& args,
855                                   std::string_view skslCoords) {
856     SkASSERT(childIndex >= 0);
857
858     if (!inputColor) {
859         inputColor = args.fInputColor;
860     }
861
862     const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
863     if (!childProc) {
864         // If no child processor is provided, return the input color as-is.
865         return SkString(inputColor);
866     }
867
868     auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
869                                      inputColor);
870
871     if (childProc->isBlendFunction()) {
872         if (!destColor) {
873             destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
874         }
875         invocation.appendf(", %s", destColor);
876     }
877
878     // Assert that the child has no sample matrix. A uniform matrix sample call would go through
879     // invokeChildWithMatrix, not here.
880     SkASSERT(!childProc->sampleUsage().isUniformMatrix());
881
882     if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
883         SkASSERT(!childProc->sampleUsage().isFragCoord() || skslCoords == "sk_FragCoord.xy");
884         // The child's function takes a half4 color and a float2 coordinate
885         if (!skslCoords.empty()) {
886             invocation.appendf(", %.*s", (int)skslCoords.size(), skslCoords.data());
887         } else {
888             invocation.appendf(", %s", args.fSampleCoord);
889         }
890     }
891
892     invocation.append(")");
893     return invocation;
894 }
895
896 SkString ProgramImpl::invokeChildWithMatrix(int childIndex,
897                                             const char* inputColor,
898                                             const char* destColor,
899                                             EmitArgs& args) {
900     SkASSERT(childIndex >= 0);
901
902     if (!inputColor) {
903         inputColor = args.fInputColor;
904     }
905
906     const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
907     if (!childProc) {
908         // If no child processor is provided, return the input color as-is.
909         return SkString(inputColor);
910     }
911
912     SkASSERT(childProc->sampleUsage().isUniformMatrix());
913
914     // Every uniform matrix has the same (initial) name. Resolve that into the mangled name:
915     GrShaderVar uniform = args.fUniformHandler->getUniformMapping(
916             args.fFp, SkString(SkSL::SampleUsage::MatrixUniformName()));
917     SkASSERT(uniform.getType() == SkSLType::kFloat3x3);
918     const SkString& matrixName(uniform.getName());
919
920     auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
921                                      inputColor);
922
923     if (childProc->isBlendFunction()) {
924         if (!destColor) {
925             destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
926         }
927         invocation.appendf(", %s", destColor);
928     }
929
930     // Produce a string containing the call to the helper function. We have a uniform variable
931     // containing our transform (matrixName). If the parent coords were produced by uniform
932     // transforms, then the entire expression (matrixName * coords) is lifted to a vertex shader
933     // and is stored in a varying. In that case, childProc will not be sampled explicitly, so its
934     // function signature will not take in coords.
935     //
936     // In all other cases, we need to insert sksl to compute matrix * parent coords and then invoke
937     // the function.
938     if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
939         // Only check perspective for this specific matrix transform, not the aggregate FP property.
940         // Any parent perspective will have already been applied when evaluated in the FS.
941         if (childProc->sampleUsage().hasPerspective()) {
942             invocation.appendf(", proj((%s) * %s.xy1)", matrixName.c_str(), args.fSampleCoord);
943         } else if (args.fShaderCaps->nonsquareMatrixSupport()) {
944             invocation.appendf(", float3x2(%s) * %s.xy1", matrixName.c_str(), args.fSampleCoord);
945         } else {
946             invocation.appendf(", ((%s) * %s.xy1).xy", matrixName.c_str(), args.fSampleCoord);
947         }
948     }
949
950     invocation.append(")");
951     return invocation;
952 }