xref: /aosp_15_r20/external/skia/docs/examples/SkSL_EvaluatingTwoShaders.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 // Copyright 2024 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3 #include "tools/fiddle/examples.h"
4 REG_FIDDLE(SkSL_EvaluatingTwoShaders, 128, 128, false, 5) {
5 // Create a linear gradient from white (left) to black (right)
makeGradientShader()6 sk_sp<SkShader> makeGradientShader() {
7   const SkPoint pts[] = { { 0, 0 }, { 128, 0 } };
8   const SkColor colors[] = { SK_ColorWHITE, SK_ColorBLACK };
9   return SkGradientShader::MakeLinear(pts, colors, nullptr, 2, SkTileMode::kClamp);
10 }
11 
draw(SkCanvas * canvas)12 void draw(SkCanvas* canvas) {
13   // Turn `image` into an SkShader:
14   sk_sp<SkShader> imageShader = image->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
15 
16   const char* sksl =
17     "uniform shader input_1;"
18     "uniform shader input_2;"
19     "half4 main(float2 coord) {"
20     "  return input_1.eval(coord) * input_2.eval(coord);"
21     "}";
22   SkRuntimeEffect::ChildPtr children[] = { /*input_1=*/ imageShader,
23                                            /*input_2=*/ makeGradientShader() };
24 
25   // Create SkShader from SkSL, then fill surface: // SK_FOLD_START
26 
27   // Create an SkShader from our SkSL, with `children` bound to the inputs:
28   auto [effect, err] = SkRuntimeEffect::MakeForShader(SkString(sksl));
29   sk_sp<SkShader> myShader = effect->makeShader(/*uniforms=*/ nullptr,
30                                                 /*children=*/ { children, 2 });
31 
32   // Fill the surface with `myShader`:
33   SkPaint p;
34   p.setShader(myShader);
35   canvas->drawPaint(p);
36   // SK_FOLD_END
37 }
38 }  // END FIDDLE
39