1/*
2 * Copyright 2021 Google LLC.
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 "gm/gm.h"
9#include "include/effects/SkRuntimeEffect.h"
10#include "src/core/SkCanvasPriv.h"
11#include "src/gpu/SurfaceFillContext.h"
12#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
13#include "src/sksl/dsl/priv/DSLFPs.h"
14#include "src/sksl/dsl/priv/DSLWriter.h"
15#include "src/sksl/ir/SkSLVariable.h"
16
17class SimpleDSLEffect : public GrFragmentProcessor {
18public:
19    static constexpr GrProcessor::ClassID CLASS_ID = (GrProcessor::ClassID) 100;
20
21    SimpleDSLEffect() : GrFragmentProcessor(CLASS_ID, kNone_OptimizationFlags) {
22    }
23
24    const char* name() const override { return "DSLEffect"; }
25    void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
26    bool onIsEqual(const GrFragmentProcessor& that) const override { return this == &that; }
27    std::unique_ptr<GrFragmentProcessor> clone() const override { return nullptr; }
28
29    std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
30        class Impl : public ProgramImpl {
31        public:
32            void emitCode(EmitArgs& args) override {
33                using namespace SkSL::dsl;
34                StartFragmentProcessor(this, &args);
35
36                // Test for skbug.com/11384
37                Var x(kInt_Type, 1);
38                Declare(x);
39                SkASSERT(DSLWriter::Var(x)->initialValue()->description() == "1");
40
41                GlobalVar blueAlpha(kUniform_Modifier, kHalf2_Type, "blueAlpha");
42                Declare(blueAlpha);
43                fBlueAlphaUniform = VarUniformHandle(blueAlpha);
44                Var coords(kFloat4_Type, sk_FragCoord());
45                Declare(coords);
46                Return(Half4(Swizzle(coords, X, Y) / 100, blueAlpha));
47                EndFragmentProcessor();
48            }
49
50        private:
51            void onSetData(const GrGLSLProgramDataManager& pdman,
52                           const GrFragmentProcessor& effect) override {
53                pdman.set2f(fBlueAlphaUniform, 0.0, 1.0);
54            }
55
56            GrGLSLProgramDataManager::UniformHandle fBlueAlphaUniform;
57        };
58        return std::make_unique<Impl>();
59    }
60};
61
62DEF_SIMPLE_GPU_GM(simple_dsl_test, rContext, canvas, 100, 100) {
63    auto sfc = SkCanvasPriv::TopDeviceSurfaceFillContext(canvas);
64    if (!sfc) {
65        return;
66    }
67
68    sfc->fillWithFP(std::make_unique<SimpleDSLEffect>());
69}
70