• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 "include/core/SkBitmap.h"
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkColorFilter.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkPaint.h"
13 #include "include/core/SkSurface.h"
14 #include "include/effects/SkRuntimeEffect.h"
15 #include "include/gpu/GrDirectContext.h"
16 #include "src/core/SkColorSpacePriv.h"
17 #include "src/core/SkRuntimeEffectPriv.h"
18 #include "src/core/SkTLazy.h"
19 #include "src/gpu/GrColor.h"
20 #include "src/gpu/GrFragmentProcessor.h"
21 #include "tests/Test.h"
22 
23 #include <algorithm>
24 #include <thread>
25 
test_invalid_effect(skiatest::Reporter * r,const char * src,const char * expected)26 void test_invalid_effect(skiatest::Reporter* r, const char* src, const char* expected) {
27     auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src));
28     REPORTER_ASSERT(r, !effect);
29     REPORTER_ASSERT(r, errorText.contains(expected),
30                     "Expected error message to contain \"%s\". Actual message: \"%s\"",
31                     expected, errorText.c_str());
32 };
33 
34 #define EMPTY_MAIN "half4 main(float2 p) { return half4(0); }"
35 
DEF_TEST(SkRuntimeEffectInvalid_FPOnly,r)36 DEF_TEST(SkRuntimeEffectInvalid_FPOnly, r) {
37     // Features that are only allowed in .fp files (key, in uniform, ctype, when, tracked).
38     // Ensure that these fail, and the error messages contain the relevant keyword.
39     test_invalid_effect(r, "layout(key) in bool Input;"             EMPTY_MAIN, "key");
40     test_invalid_effect(r, "in uniform float Input;"                EMPTY_MAIN, "in uniform");
41     test_invalid_effect(r, "layout(ctype=SkRect) float4 Input;"     EMPTY_MAIN, "ctype");
42     test_invalid_effect(r, "in bool Flag; "
43                            "layout(when=Flag) uniform float Input;" EMPTY_MAIN, "when");
44     test_invalid_effect(r, "layout(tracked) uniform float Input;"   EMPTY_MAIN, "tracked");
45 }
46 
DEF_TEST(SkRuntimeEffectInvalid_LimitedUniformTypes,r)47 DEF_TEST(SkRuntimeEffectInvalid_LimitedUniformTypes, r) {
48     // Runtime SkSL supports a limited set of uniform types. No bool, for example:
49     test_invalid_effect(r, "uniform bool b;" EMPTY_MAIN, "uniform");
50 }
51 
DEF_TEST(SkRuntimeEffectInvalid_NoInVariables,r)52 DEF_TEST(SkRuntimeEffectInvalid_NoInVariables, r) {
53     // 'in' variables aren't allowed at all:
54     test_invalid_effect(r, "in bool b;"    EMPTY_MAIN, "'in'");
55     test_invalid_effect(r, "in float f;"   EMPTY_MAIN, "'in'");
56     test_invalid_effect(r, "in float2 v;"  EMPTY_MAIN, "'in'");
57     test_invalid_effect(r, "in half3x3 m;" EMPTY_MAIN, "'in'");
58 }
59 
DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction,r)60 DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction, r) {
61     test_invalid_effect(r, "half4 missing(); half4 main(float2 p) { return missing(); }",
62                            "undefined function");
63 }
64 
DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain,r)65 DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain, r) {
66     // Shouldn't be possible to create an SkRuntimeEffect without "main"
67     test_invalid_effect(r, "", "main");
68 }
69 
DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed,r)70 DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed, r) {
71     // sk_Caps is an internal system. It should not be visible to runtime effects
72     test_invalid_effect(
73             r,
74             "half4 main(float2 p) { return sk_Caps.integerSupport ? half4(1) : half4(0); }",
75             "unknown identifier 'sk_Caps'");
76 }
77 
DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions,r)78 DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions, r) {
79     auto test_valid_es3 = [](skiatest::Reporter* r, const char* sksl) {
80         SkRuntimeEffect::Options opt;
81         opt.enforceES2Restrictions = false;
82         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl), opt);
83         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
84     };
85 
86     test_invalid_effect(r, "float f[2] = float[2](0, 1);" EMPTY_MAIN, "construction of array type");
87     test_valid_es3     (r, "float f[2] = float[2](0, 1);" EMPTY_MAIN);
88 }
89 
DEF_TEST(SkRuntimeEffectForColorFilter,r)90 DEF_TEST(SkRuntimeEffectForColorFilter, r) {
91     // Tests that the color filter factory rejects or accepts certain SkSL constructs
92     auto test_valid = [r](const char* sksl) {
93         auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
94         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
95     };
96 
97     auto test_invalid = [r](const char* sksl, const char* expected) {
98         auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
99         REPORTER_ASSERT(r, !effect);
100         REPORTER_ASSERT(r,
101                         errorText.contains(expected),
102                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
103                         expected,
104                         errorText.c_str());
105     };
106 
107     // Color filters must use the 'half4 main(half4)' signature. Either color can be float4/vec4
108     test_valid("half4  main(half4  c) { return c; }");
109     test_valid("float4 main(half4  c) { return c; }");
110     test_valid("half4  main(float4 c) { return c; }");
111     test_valid("float4 main(float4 c) { return c; }");
112     test_valid("vec4   main(half4  c) { return c; }");
113     test_valid("half4  main(vec4   c) { return c; }");
114     test_valid("vec4   main(vec4   c) { return c; }");
115 
116     // Invalid return types
117     test_invalid("void  main(half4 c) {}",                "'main' must return");
118     test_invalid("half3 main(half4 c) { return c.rgb; }", "'main' must return");
119 
120     // Invalid argument types (some are valid as shaders, but not color filters)
121     test_invalid("half4 main() { return half4(1); }",           "'main' parameter");
122     test_invalid("half4 main(float2 p) { return half4(1); }",   "'main' parameter");
123     test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter");
124 
125     // sk_FragCoord should not be available
126     test_invalid("half4 main(half4 c) { return sk_FragCoord.xy01; }", "unknown identifier");
127 
128     // Sampling a child shader requires that we pass explicit coords
129     test_valid("uniform shader child;"
130                "half4 main(half4 c) { return sample(child, c.rg); }");
131     // Trying to pass a color as well. (Works internally with FPs, but not in runtime effects).
132     test_invalid("uniform shader child;"
133                  "half4 main(half4 c) { return sample(child, c.rg, c); }",
134                  "no match for sample(shader, half2, half4)");
135 
136     // Shader with just a color
137     test_invalid("uniform shader child;"
138                  "half4 main(half4 c) { return sample(child, c); }",
139                  "no match for sample(shader, half4)");
140     // Coords and color in a differet order
141     test_invalid("uniform shader child;"
142                  "half4 main(half4 c) { return sample(child, c, c.rg); }",
143                  "no match for sample(shader, half4, half2)");
144 
145     // Older variants that are no longer allowed
146     test_invalid(
147             "uniform shader child;"
148             "half4 main(half4 c) { return sample(child); }",
149             "no match for sample(shader)");
150     test_invalid(
151             "uniform shader child;"
152             "half4 main(half4 c) { return sample(child, float3x3(1)); }",
153             "no match for sample(shader, float3x3)");
154 
155     // Sampling a colorFilter requires a color. No other signatures are valid.
156     test_valid("uniform colorFilter child;"
157                "half4 main(half4 c) { return sample(child, c); }");
158 
159     test_invalid("uniform colorFilter child;"
160                  "half4 main(half4 c) { return sample(child); }",
161                  "sample(colorFilter)");
162     test_invalid("uniform colorFilter child;"
163                  "half4 main(half4 c) { return sample(child, c.rg); }",
164                  "sample(colorFilter, half2)");
165     test_invalid("uniform colorFilter child;"
166                  "half4 main(half4 c) { return sample(child, c.rg, c); }",
167                  "sample(colorFilter, half2, half4)");
168 }
169 
DEF_TEST(SkRuntimeEffectForShader,r)170 DEF_TEST(SkRuntimeEffectForShader, r) {
171     // Tests that the shader factory rejects or accepts certain SkSL constructs
172     auto test_valid = [r](const char* sksl) {
173         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
174         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
175     };
176 
177     auto test_invalid = [r](const char* sksl, const char* expected) {
178         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
179         REPORTER_ASSERT(r, !effect);
180         REPORTER_ASSERT(r,
181                         errorText.contains(expected),
182                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
183                         expected,
184                         errorText.c_str());
185     };
186 
187     // Shaders must use either the 'half4 main(float2)' or 'half4 main(float2, half4)' signature
188     // Either color can be half4/float4/vec4, but the coords must be float2/vec2
189     test_valid("half4  main(float2 p) { return p.xyxy; }");
190     test_valid("float4 main(float2 p) { return p.xyxy; }");
191     test_valid("vec4   main(float2 p) { return p.xyxy; }");
192     test_valid("half4  main(vec2   p) { return p.xyxy; }");
193     test_valid("vec4   main(vec2   p) { return p.xyxy; }");
194     test_valid("half4  main(float2 p, half4  c) { return c; }");
195     test_valid("half4  main(float2 p, float4 c) { return c; }");
196     test_valid("half4  main(float2 p, vec4   c) { return c; }");
197     test_valid("float4 main(float2 p, half4  c) { return c; }");
198     test_valid("vec4   main(float2 p, half4  c) { return c; }");
199     test_valid("vec4   main(vec2   p, vec4   c) { return c; }");
200 
201     // Invalid return types
202     test_invalid("void  main(float2 p) {}",                "'main' must return");
203     test_invalid("half3 main(float2 p) { return p.xy1; }", "'main' must return");
204 
205     // Invalid argument types (some are valid as color filters, but not shaders)
206     test_invalid("half4 main() { return half4(1); }", "'main' parameter");
207     test_invalid("half4 main(half4 c) { return c; }", "'main' parameter");
208 
209     // sk_FragCoord should be available
210     test_valid("half4 main(float2 p) { return sk_FragCoord.xy01; }");
211 
212     // Sampling a child shader requires that we pass explicit coords
213     test_valid("uniform shader child;"
214                "half4 main(float2 p) { return sample(child, p); }");
215 
216     // Trying to pass a color as well. (Works internally with FPs, but not in runtime effects).
217     test_invalid("uniform shader child;"
218                  "half4 main(float2 p, half4 c) { return sample(child, p, c); }",
219                  "no match for sample(shader, float2, half4)");
220 
221     // Shader with just a color
222     test_invalid("uniform shader child;"
223                  "half4 main(float2 p, half4 c) { return sample(child, c); }",
224                  "no match for sample(shader, half4)");
225     // Coords and color in a different order
226     test_invalid("uniform shader child;"
227                  "half4 main(float2 p, half4 c) { return sample(child, c, p); }",
228                  "no match for sample(shader, half4, float2)");
229 
230     // Older variants that are no longer allowed
231     test_invalid(
232             "uniform shader child;"
233             "half4 main(float2 p) { return sample(child); }",
234             "no match for sample(shader)");
235     test_invalid(
236             "uniform shader child;"
237             "half4 main(float2 p) { return sample(child, float3x3(1)); }",
238             "no match for sample(shader, float3x3)");
239 
240     // Sampling a colorFilter requires a color. No other signatures are valid.
241     test_valid("uniform colorFilter child;"
242                "half4 main(float2 p, half4 c) { return sample(child, c); }");
243 
244     test_invalid("uniform colorFilter child;"
245                  "half4 main(float2 p) { return sample(child); }",
246                  "sample(colorFilter)");
247     test_invalid("uniform colorFilter child;"
248                  "half4 main(float2 p) { return sample(child, p); }",
249                  "sample(colorFilter, float2)");
250     test_invalid("uniform colorFilter child;"
251                  "half4 main(float2 p, half4 c) { return sample(child, p, c); }",
252                  "sample(colorFilter, float2, half4)");
253 }
254 
255 class TestEffect {
256 public:
TestEffect(skiatest::Reporter * r,sk_sp<SkSurface> surface)257     TestEffect(skiatest::Reporter* r, sk_sp<SkSurface> surface)
258             : fReporter(r), fSurface(std::move(surface)) {}
259 
build(const char * src)260     void build(const char* src) {
261         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src));
262         if (!effect) {
263             REPORT_FAILURE(fReporter, "effect",
264                            SkStringPrintf("Effect didn't compile: %s", errorText.c_str()));
265             return;
266         }
267         fBuilder.init(std::move(effect));
268     }
269 
uniform(const char * name)270     SkRuntimeShaderBuilder::BuilderUniform uniform(const char* name) {
271         return fBuilder->uniform(name);
272     }
child(const char * name)273     SkRuntimeShaderBuilder::BuilderChild child(const char* name) {
274         return fBuilder->child(name);
275     }
276 
277     using PreTestFn = std::function<void(SkCanvas*, SkPaint*)>;
278 
test(GrColor TL,GrColor TR,GrColor BL,GrColor BR,PreTestFn preTestCallback=nullptr)279     void test(GrColor TL, GrColor TR, GrColor BL, GrColor BR,
280               PreTestFn preTestCallback = nullptr) {
281         auto shader = fBuilder->makeShader(nullptr, false);
282         if (!shader) {
283             REPORT_FAILURE(fReporter, "shader", SkString("Effect didn't produce a shader"));
284             return;
285         }
286 
287         SkCanvas* canvas = fSurface->getCanvas();
288         SkPaint paint;
289         paint.setShader(std::move(shader));
290         paint.setBlendMode(SkBlendMode::kSrc);
291 
292         canvas->save();
293         if (preTestCallback) {
294             preTestCallback(canvas, &paint);
295         }
296         canvas->drawPaint(paint);
297         canvas->restore();
298 
299         GrColor actual[4];
300         SkImageInfo info = fSurface->imageInfo();
301         if (!fSurface->readPixels(info, actual, info.minRowBytes(), 0, 0)) {
302             REPORT_FAILURE(fReporter, "readPixels", SkString("readPixels failed"));
303             return;
304         }
305 
306         GrColor expected[4] = {TL, TR, BL, BR};
307         if (0 != memcmp(actual, expected, sizeof(actual))) {
308             REPORT_FAILURE(fReporter, "Runtime effect didn't match expectations",
309                            SkStringPrintf("\n"
310                                           "Expected: [ %08x %08x %08x %08x ]\n"
311                                           "Got     : [ %08x %08x %08x %08x ]\n"
312                                           "SkSL:\n%s\n",
313                                           TL, TR, BL, BR, actual[0], actual[1], actual[2],
314                                           actual[3], fBuilder->effect()->source().c_str()));
315         }
316     }
317 
test(GrColor expected,PreTestFn preTestCallback=nullptr)318     void test(GrColor expected, PreTestFn preTestCallback = nullptr) {
319         this->test(expected, expected, expected, expected, preTestCallback);
320     }
321 
322 private:
323     skiatest::Reporter*             fReporter;
324     sk_sp<SkSurface>                fSurface;
325     SkTLazy<SkRuntimeShaderBuilder> fBuilder;
326 };
327 
328 // Produces a 2x2 bitmap shader, with opaque colors:
329 // [  Red, Green ]
330 // [ Blue, White ]
make_RGBW_shader()331 static sk_sp<SkShader> make_RGBW_shader() {
332     SkBitmap bmp;
333     bmp.allocPixels(SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType));
334     SkIRect topLeft = SkIRect::MakeWH(1, 1);
335     bmp.pixmap().erase(SK_ColorRED,   topLeft);
336     bmp.pixmap().erase(SK_ColorGREEN, topLeft.makeOffset(1, 0));
337     bmp.pixmap().erase(SK_ColorBLUE,  topLeft.makeOffset(0, 1));
338     bmp.pixmap().erase(SK_ColorWHITE, topLeft.makeOffset(1, 1));
339     return bmp.makeShader(SkSamplingOptions());
340 }
341 
test_RuntimeEffect_Shaders(skiatest::Reporter * r,GrRecordingContext * rContext)342 static void test_RuntimeEffect_Shaders(skiatest::Reporter* r, GrRecordingContext* rContext) {
343     SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
344     sk_sp<SkSurface> surface = rContext
345                                     ? SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, info)
346                                     : SkSurface::MakeRaster(info);
347     REPORTER_ASSERT(r, surface);
348     TestEffect effect(r, surface);
349 
350     using float4 = std::array<float, 4>;
351     using int4 = std::array<int, 4>;
352 
353     // Local coords
354     effect.build("half4 main(float2 p) { return half4(half2(p - 0.5), 0, 1); }");
355     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
356 
357     // Use of a simple uniform. (Draw twice with two values to ensure it's updated).
358     effect.build("uniform float4 gColor; half4 main(float2 p) { return half4(gColor); }");
359     effect.uniform("gColor") = float4{ 0.0f, 0.25f, 0.75f, 1.0f };
360     effect.test(0xFFBF4000);
361     effect.uniform("gColor") = float4{ 1.0f, 0.0f, 0.0f, 0.498f };
362     effect.test(0x7F00007F);  // Tests that we clamp to valid premul
363 
364     // Same, with integer uniforms
365     effect.build("uniform int4 gColor; half4 main(float2 p) { return half4(gColor) / 255.0; }");
366     effect.uniform("gColor") = int4{ 0x00, 0x40, 0xBF, 0xFF };
367     effect.test(0xFFBF4000);
368     effect.uniform("gColor") = int4{ 0xFF, 0x00, 0x00, 0x7F };
369     effect.test(0x7F00007F);  // Tests that we clamp to valid premul
370 
371     // Test sk_FragCoord (device coords). Rotate the canvas to be sure we're seeing device coords.
372     // Since the surface is 2x2, we should see (0,0), (1,0), (0,1), (1,1). Multiply by 0.498 to
373     // make sure we're not saturating unexpectedly.
374     effect.build(
375             "half4 main(float2 p) { return half4(0.498 * (half2(sk_FragCoord.xy) - 0.5), 0, 1); }");
376     effect.test(0xFF000000, 0xFF00007F, 0xFF007F00, 0xFF007F7F,
377                 [](SkCanvas* canvas, SkPaint*) { canvas->rotate(45.0f); });
378 
379     // Runtime effects should use relaxed precision rules by default
380     effect.build("half4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
381     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
382 
383     // ... and support *returning* float4 (aka vec4), not just half4
384     effect.build("float4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
385     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
386     effect.build("vec4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
387     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
388 
389     // Mutating coords should work. (skbug.com/10918)
390     effect.build("vec4 main(vec2 p) { p -= 0.5; return vec4(p, 0, 1); }");
391     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
392     effect.build("void moveCoords(inout vec2 p) { p -= 0.5; }"
393                  "vec4 main(vec2 p) { moveCoords(p); return vec4(p, 0, 1); }");
394     effect.test(0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
395 
396     //
397     // Sampling children
398     //
399 
400     // Sampling a null child should return the paint color
401     effect.build("uniform shader child;"
402                  "half4 main(float2 p) { return sample(child, p); }");
403     effect.child("child") = nullptr;
404     effect.test(0xFF00FFFF,
405                 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
406 
407     sk_sp<SkShader> rgbwShader = make_RGBW_shader();
408 
409     // Sampling a simple child at our coordinates
410     effect.build("uniform shader child;"
411                  "half4 main(float2 p) { return sample(child, p); }");
412     effect.child("child") = rgbwShader;
413     effect.test(0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF);
414 
415     // Sampling with explicit coordinates (reflecting about the diagonal)
416     effect.build("uniform shader child;"
417                  "half4 main(float2 p) { return sample(child, p.yx); }");
418     effect.child("child") = rgbwShader;
419     effect.test(0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFFFFFFFF);
420 
421     //
422     // Helper functions
423     //
424 
425     // Test case for inlining in the pipeline-stage and fragment-shader passes (skbug.com/10526):
426     effect.build("float2 helper(float2 x) { return x + 1; }"
427                  "half4 main(float2 p) { float2 v = helper(p); return half4(half2(v), 0, 1); }");
428     effect.test(0xFF00FFFF);
429 }
430 
DEF_TEST(SkRuntimeEffectSimple,r)431 DEF_TEST(SkRuntimeEffectSimple, r) {
432     test_RuntimeEffect_Shaders(r, nullptr);
433 }
434 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU,r,ctxInfo)435 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU, r, ctxInfo) {
436     test_RuntimeEffect_Shaders(r, ctxInfo.directContext());
437 }
438 
DEF_TEST(SkRuntimeShaderBuilderReuse,r)439 DEF_TEST(SkRuntimeShaderBuilderReuse, r) {
440     const char* kSource = R"(
441         uniform half x;
442         half4 main(float2 p) { return half4(x); }
443     )";
444 
445     sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
446     REPORTER_ASSERT(r, effect);
447 
448     // Test passes if this sequence doesn't assert.  skbug.com/10667
449     SkRuntimeShaderBuilder b(std::move(effect));
450     b.uniform("x") = 0.0f;
451     auto shader_0 = b.makeShader(nullptr, false);
452 
453     b.uniform("x") = 1.0f;
454     auto shader_1 = b.makeShader(nullptr, true);
455 }
456 
DEF_TEST(SkRuntimeShaderBuilderSetUniforms,r)457 DEF_TEST(SkRuntimeShaderBuilderSetUniforms, r) {
458     const char* kSource = R"(
459         uniform half x;
460         uniform vec2 offset;
461         half4 main(float2 p) { return half4(x); }
462     )";
463 
464     sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
465     REPORTER_ASSERT(r, effect);
466 
467     SkRuntimeShaderBuilder b(std::move(effect));
468 
469     // Test passes if this sequence doesn't assert.
470     float x = 1.0f;
471     REPORTER_ASSERT(r, b.uniform("x").set(&x, 1));
472 
473     // add extra value to ensure that set doesn't try to use sizeof(array)
474     float origin[] = { 2.0f, 3.0f, 4.0f };
475     REPORTER_ASSERT(r, b.uniform("offset").set<float>(origin, 2));
476 
477 #ifndef SK_DEBUG
478     REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 1));
479     REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 3));
480 #endif
481 
482 
483     auto shader = b.makeShader(nullptr, false);
484 }
485 
DEF_TEST(SkRuntimeEffectThreaded,r)486 DEF_TEST(SkRuntimeEffectThreaded, r) {
487     // SkRuntimeEffect uses a single compiler instance, but it's mutex locked.
488     // This tests that we can safely use it from more than one thread, and also
489     // that programs don't refer to shared structures owned by the compiler.
490     // skbug.com/10589
491     static constexpr char kSource[] = "half4 main(float2 p) { return sk_FragCoord.xyxy; }";
492 
493     std::thread threads[16];
494     for (auto& thread : threads) {
495         thread = std::thread([r]() {
496             auto [effect, error] = SkRuntimeEffect::MakeForShader(SkString(kSource));
497             REPORTER_ASSERT(r, effect);
498         });
499     }
500 
501     for (auto& thread : threads) {
502         thread.join();
503     }
504 }
505 
DEF_TEST(SkRuntimeColorFilterSingleColor,r)506 DEF_TEST(SkRuntimeColorFilterSingleColor, r) {
507     // Test runtime colorfilters support filterColor4f().
508     auto [effect, err] =
509             SkRuntimeEffect::MakeForColorFilter(SkString{"half4 main(half4 c) { return c*c; }"});
510     REPORTER_ASSERT(r, effect);
511     REPORTER_ASSERT(r, err.isEmpty());
512 
513     sk_sp<SkColorFilter> cf = effect->makeColorFilter(SkData::MakeEmpty());
514     REPORTER_ASSERT(r, cf);
515 
516     SkColor4f c = cf->filterColor4f({0.25, 0.5, 0.75, 1.0},
517                                     sk_srgb_singleton(), sk_srgb_singleton());
518     REPORTER_ASSERT(r, c.fR == 0.0625f);
519     REPORTER_ASSERT(r, c.fG == 0.25f);
520     REPORTER_ASSERT(r, c.fB == 0.5625f);
521     REPORTER_ASSERT(r, c.fA == 1.0f);
522 }
523 
test_RuntimeEffectStructNameReuse(skiatest::Reporter * r,GrRecordingContext * rContext)524 static void test_RuntimeEffectStructNameReuse(skiatest::Reporter* r, GrRecordingContext* rContext) {
525     // Test that two different runtime effects can reuse struct names in a single paint operation
526     auto [childEffect, err] = SkRuntimeEffect::MakeForShader(SkString(
527         "uniform shader paint;"
528         "struct S { half4 rgba; };"
529         "void process(inout S s) { s.rgba.rgb *= 0.5; }"
530         "half4 main(float2 p) { S s; s.rgba = sample(paint, p); process(s); return s.rgba; }"
531     ));
532     REPORTER_ASSERT(r, childEffect, "%s\n", err.c_str());
533     sk_sp<SkShader> nullChild = nullptr;
534     sk_sp<SkShader> child = childEffect->makeShader(/*uniforms=*/nullptr, &nullChild,
535                                                     /*childCount=*/1, /*localMatrix=*/nullptr,
536                                                     /*isOpaque=*/false);
537 
538     SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
539     sk_sp<SkSurface> surface = rContext
540                                     ? SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, info)
541                                     : SkSurface::MakeRaster(info);
542     REPORTER_ASSERT(r, surface);
543 
544     TestEffect effect(r, surface);
545     effect.build(
546             "uniform shader child;"
547             "struct S { float2 coord; };"
548             "void process(inout S s) { s.coord = s.coord.yx; }"
549             "half4 main(float2 p) { S s; s.coord = p; process(s); return sample(child, s.coord); "
550             "}");
551     effect.child("child") = child;
552     effect.test(0xFF00407F, [](SkCanvas*, SkPaint* paint) {
553         paint->setColor4f({0.99608f, 0.50196f, 0.0f, 1.0f});
554     });
555 }
556 
DEF_TEST(SkRuntimeStructNameReuse,r)557 DEF_TEST(SkRuntimeStructNameReuse, r) {
558     test_RuntimeEffectStructNameReuse(r, nullptr);
559 }
560 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU,r,ctxInfo)561 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU, r, ctxInfo) {
562     test_RuntimeEffectStructNameReuse(r, ctxInfo.directContext());
563 }
564 
DEF_TEST(SkRuntimeColorFilterFlags,r)565 DEF_TEST(SkRuntimeColorFilterFlags, r) {
566     {   // Here's a non-trivial filter that doesn't change alpha.
567         auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{
568                 "half4 main(half4 color) { return color + half4(1,1,1,0); }"});
569         REPORTER_ASSERT(r, effect && err.isEmpty());
570         sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
571         REPORTER_ASSERT(r, filter && filter->isAlphaUnchanged());
572     }
573 
574     {  // Here's one that definitely changes alpha.
575         auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{
576                 "half4 main(half4 color) { return color + half4(0,0,0,4); }"});
577         REPORTER_ASSERT(r, effect && err.isEmpty());
578         sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
579         REPORTER_ASSERT(r, filter && !filter->isAlphaUnchanged());
580     }
581 }
582 
DEF_TEST(SkRuntimeShaderSampleUsage,r)583 DEF_TEST(SkRuntimeShaderSampleUsage, r) {
584     auto test = [&](const char* src, bool expectExplicit) {
585         auto [effect, err] =
586                 SkRuntimeEffect::MakeForShader(SkStringPrintf("uniform shader child; %s", src));
587         REPORTER_ASSERT(r, effect);
588 
589         auto child = GrFragmentProcessor::MakeColor({ 1, 1, 1, 1 });
590         auto fp = effect->makeFP(nullptr, &child, 1);
591         REPORTER_ASSERT(r, fp);
592 
593         REPORTER_ASSERT(r, fp->childProcessor(0)->isSampledWithExplicitCoords() == expectExplicit);
594     };
595 
596     // This test verifies that we detect calls to sample where the coords are the same as those
597     // passed to main. In those cases, it's safe to turn the "explicit" sampling into "passthrough"
598     // sampling. This optimization is implemented very conservatively.
599 
600     // Cases where our optimization is valid, and works:
601 
602     // Direct use of passed-in coords
603     test("half4 main(float2 xy) { return sample(child, xy); }", false);
604     // Sample with passed-in coords, read (but don't write) sample coords elsewhere
605     test("half4 main(float2 xy) { return sample(child, xy) + sin(xy.x); }", false);
606 
607     // Cases where our optimization is not valid, and does not happen:
608 
609     // Sampling with values completely unrelated to passed-in coords
610     test("half4 main(float2 xy) { return sample(child, float2(0, 0)); }", true);
611     // Use of expression involving passed in coords
612     test("half4 main(float2 xy) { return sample(child, xy * 0.5); }", true);
613     // Use of coords after modification
614     test("half4 main(float2 xy) { xy *= 2; return sample(child, xy); }", true);
615     // Use of coords after modification via out-param call
616     test("void adjust(inout float2 xy) { xy *= 2; }"
617          "half4 main(float2 xy) { adjust(xy); return sample(child, xy); }", true);
618 
619     // There should (must) not be any false-positive cases. There are false-negatives.
620     // In all of these cases, our optimization would be valid, but does not happen:
621 
622     // Direct use of passed-in coords, modified after use
623     test("half4 main(float2 xy) { half4 c = sample(child, xy); xy *= 2; return c; }", true);
624     // Passed-in coords copied to a temp variable
625     test("half4 main(float2 xy) { float2 p = xy; return sample(child, p); }", true);
626     // Use of coords passed to helper function
627     test("half4 helper(float2 xy) { return sample(child, xy); }"
628          "half4 main(float2 xy) { return helper(xy); }", true);
629 }
630