| 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_EvaluatingNestedShaders, 128, 128, false, 5) { |
| 5 |
// Create a linear gradient from white (left) to black (right) |
| 6 |
sk_sp<SkShader> makeGradientShader() { |
| 7 |
const char* sksl = |
| 8 |
"half4 main(float2 coord) {" |
| 9 |
" float t = coord.x / 128;" |
| 10 |
" half4 white = half4(1);" |
| 11 |
" half4 black = half4(0,0,0,1);" |
| 12 |
" return mix(white, black, t);" |
| 13 |
"}"; |
| 14 |
auto [effect, err] = SkRuntimeEffect::MakeForShader(SkString(sksl)); |
| 15 |
return effect->makeShader(/*uniforms=*/ nullptr, /*children=*/ {}); |
| 16 |
} |
| 17 |
|
| 18 |
void draw(SkCanvas* canvas) { |
| 19 |
// Turn `image` into an SkShader: |
| 20 |
sk_sp<SkShader> imageShader = image->makeShader(SkSamplingOptions(SkFilterMode::kLinear)); |
| 21 |
|
| 22 |
const char* sksl = |
| 23 |
"uniform shader input_1;" |
| 24 |
"uniform shader input_2;" |
| 25 |
"half4 main(float2 coord) {" |
| 26 |
" return input_1.eval(coord) * input_2.eval(coord);" |
| 27 |
"}"; |
| 28 |
SkRuntimeEffect::ChildPtr children[] = { /*input_1=*/ imageShader, |
| 29 |
/*input_2=*/ makeGradientShader() }; |
| 30 |
|
| 31 |
// Create SkShader from SkSL, then fill surface: // SK_FOLD_START |
| 32 |
|
| 33 |
// Create an SkShader from our SkSL, with `children` bound to the inputs: |
| 34 |
auto [effect, err] = SkRuntimeEffect::MakeForShader(SkString(sksl)); |
| 35 |
sk_sp<SkShader> myShader = effect->makeShader(/*uniforms=*/ nullptr, |
| 36 |
/*children=*/ children); |
| 37 |
|
| 38 |
// Fill the surface with `myShader`: |
| 39 |
SkPaint p; |
| 40 |
p.setShader(myShader); |
| 41 |
canvas->drawPaint(p); |
| 42 |
// SK_FOLD_END |
| 43 |
} |
| 44 |
} // END FIDDLE |