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/SkAlphaType.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkBlender.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkCapabilities.h"
13 #include "include/core/SkColor.h"
14 #include "include/core/SkColorFilter.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkImageInfo.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkRefCnt.h"
21 #include "include/core/SkScalar.h"
22 #include "include/core/SkShader.h"
23 #include "include/core/SkSize.h"
24 #include "include/core/SkSpan.h"
25 #include "include/core/SkStream.h"
26 #include "include/core/SkString.h"
27 #include "include/core/SkSurface.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkBlenders.h"
30 #include "include/effects/SkGradientShader.h"
31 #include "include/effects/SkRuntimeEffect.h"
32 #include "include/gpu/GpuTypes.h"
33 #include "include/gpu/GrDirectContext.h"
34 #include "include/private/SkColorData.h"
35 #include "include/private/SkSLSampleUsage.h"
36 #include "include/private/SkSLString.h"
37 #include "include/private/base/SkTArray.h"
38 #include "include/sksl/SkSLDebugTrace.h"
39 #include "include/sksl/SkSLVersion.h"
40 #include "src/base/SkTLazy.h"
41 #include "src/core/SkColorSpacePriv.h"
42 #include "src/core/SkRuntimeEffectPriv.h"
43 #include "src/gpu/KeyBuilder.h"
44 #include "src/gpu/SkBackingFit.h"
45 #include "src/gpu/ganesh/GrCaps.h"
46 #include "src/gpu/ganesh/GrColor.h"
47 #include "src/gpu/ganesh/GrDirectContextPriv.h"
48 #include "src/gpu/ganesh/GrFragmentProcessor.h"
49 #include "src/gpu/ganesh/GrImageInfo.h"
50 #include "src/gpu/ganesh/GrPixmap.h"
51 #include "src/gpu/ganesh/SurfaceFillContext.h"
52 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
53 #include "tests/CtsEnforcement.h"
54 #include "tests/Test.h"
55
56 #include <array>
57 #include <cstdint>
58 #include <functional>
59 #include <initializer_list>
60 #include <memory>
61 #include <string>
62 #include <thread>
63 #include <utility>
64
65 class GrRecordingContext;
66 struct GrContextOptions;
67 struct SkIPoint;
68
69 #if defined(SK_GRAPHITE)
70 #include "include/gpu/graphite/Context.h"
71 #include "include/gpu/graphite/Recorder.h"
72 #include "include/gpu/graphite/Recording.h"
73 #include "src/gpu/graphite/Surface_Graphite.h"
74
75 struct GraphiteInfo {
76 skgpu::graphite::Context* context = nullptr;
77 skgpu::graphite::Recorder* recorder = nullptr;
78 };
79 #else
80 struct GraphiteInfo {
81 void* context = nullptr;
82 void* recorder = nullptr;
83 };
84 #endif
85
test_invalid_effect(skiatest::Reporter * r,const char * src,const char * expected)86 void test_invalid_effect(skiatest::Reporter* r, const char* src, const char* expected) {
87 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src));
88 REPORTER_ASSERT(r, !effect);
89 REPORTER_ASSERT(r, errorText.contains(expected),
90 "Expected error message to contain \"%s\". Actual message: \"%s\"",
91 expected, errorText.c_str());
92 }
93
94 #define EMPTY_MAIN "half4 main(float2 p) { return half4(0); }"
95
DEF_TEST(SkRuntimeEffectInvalid_NoInVariables,r)96 DEF_TEST(SkRuntimeEffectInvalid_NoInVariables, r) {
97 // 'in' variables aren't allowed at all:
98 test_invalid_effect(r, "in bool b;" EMPTY_MAIN, "'in'");
99 test_invalid_effect(r, "in float f;" EMPTY_MAIN, "'in'");
100 test_invalid_effect(r, "in float2 v;" EMPTY_MAIN, "'in'");
101 test_invalid_effect(r, "in half3x3 m;" EMPTY_MAIN, "'in'");
102 }
103
DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction,r)104 DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction, r) {
105 test_invalid_effect(r, "half4 missing(); half4 main(float2 p) { return missing(); }",
106 "function 'half4 missing()' is not defined");
107 }
108
DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain,r)109 DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain, r) {
110 // Shouldn't be possible to create an SkRuntimeEffect without "main"
111 test_invalid_effect(r, "", "main");
112 }
113
DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed,r)114 DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed, r) {
115 // sk_Caps is an internal system. It should not be visible to runtime effects
116 test_invalid_effect(
117 r,
118 "half4 main(float2 p) { return sk_Caps.floatIs32Bits ? half4(1) : half4(0); }",
119 "name 'sk_Caps' is reserved");
120 }
121
DEF_TEST(SkRuntimeEffect_DeadCodeEliminationStackOverflow,r)122 DEF_TEST(SkRuntimeEffect_DeadCodeEliminationStackOverflow, r) {
123 // Verify that a deeply-nested loop does not cause stack overflow during SkVM dead-code
124 // elimination.
125 auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
126 half4 main(half4 color) {
127 half value = color.r;
128
129 for (int a=0; a<10; ++a) { // 10
130 for (int b=0; b<10; ++b) { // 100
131 for (int c=0; c<10; ++c) { // 1000
132 for (int d=0; d<10; ++d) { // 10000
133 ++value;
134 }}}}
135
136 return value.xxxx;
137 }
138 )"));
139 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
140 }
141
DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions,r)142 DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions, r) {
143 auto test_valid_es3 = [](skiatest::Reporter* r, const char* sksl) {
144 SkRuntimeEffect::Options opt = SkRuntimeEffectPriv::ES3Options();
145 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl), opt);
146 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
147 };
148
149 test_invalid_effect(r, "float f[2] = float[2](0, 1);" EMPTY_MAIN, "construction of array type");
150 test_valid_es3 (r, "float f[2] = float[2](0, 1);" EMPTY_MAIN);
151 }
152
DEF_TEST(SkRuntimeEffectCanEnableVersion300,r)153 DEF_TEST(SkRuntimeEffectCanEnableVersion300, r) {
154 auto test_valid = [](skiatest::Reporter* r, const char* sksl) {
155 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
156 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
157 };
158
159 test_invalid_effect(r, "#version 100\nfloat f[2] = float[2](0, 1);" EMPTY_MAIN,
160 "construction of array type");
161 test_valid (r, "#version 300\nfloat f[2] = float[2](0, 1);" EMPTY_MAIN);
162 }
163
DEF_TEST(SkRuntimeEffectUniformFlags,r)164 DEF_TEST(SkRuntimeEffectUniformFlags, r) {
165 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(R"(
166 uniform int simple; // should have no flags
167 uniform float arrayOfOne[1]; // should have kArray_Flag
168 uniform float arrayOfMultiple[2]; // should have kArray_Flag
169 layout(color) uniform float4 color; // should have kColor_Flag
170 uniform half3 halfPrecisionFloat; // should have kHalfPrecision_Flag
171 layout(color) uniform half4 allFlags[2]; // should have Array | Color | HalfPrecision
172 )" EMPTY_MAIN));
173 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
174
175 SkSpan<const SkRuntimeEffect::Uniform> uniforms = effect->uniforms();
176 REPORTER_ASSERT(r, uniforms.size() == 6);
177
178 REPORTER_ASSERT(r, uniforms[0].flags == 0);
179 REPORTER_ASSERT(r, uniforms[1].flags == SkRuntimeEffect::Uniform::kArray_Flag);
180 REPORTER_ASSERT(r, uniforms[2].flags == SkRuntimeEffect::Uniform::kArray_Flag);
181 REPORTER_ASSERT(r, uniforms[3].flags == SkRuntimeEffect::Uniform::kColor_Flag);
182 REPORTER_ASSERT(r, uniforms[4].flags == SkRuntimeEffect::Uniform::kHalfPrecision_Flag);
183 REPORTER_ASSERT(r, uniforms[5].flags == (SkRuntimeEffect::Uniform::kArray_Flag |
184 SkRuntimeEffect::Uniform::kColor_Flag |
185 SkRuntimeEffect::Uniform::kHalfPrecision_Flag));
186 }
187
DEF_TEST(SkRuntimeEffectValidation,r)188 DEF_TEST(SkRuntimeEffectValidation, r) {
189 auto es2Effect = SkRuntimeEffect::MakeForShader(SkString("#version 100\n" EMPTY_MAIN)).effect;
190 auto es3Effect = SkRuntimeEffect::MakeForShader(SkString("#version 300\n" EMPTY_MAIN)).effect;
191 REPORTER_ASSERT(r, es2Effect && es3Effect);
192
193 auto es2Caps = SkCapabilities::RasterBackend();
194 REPORTER_ASSERT(r, es2Caps->skslVersion() == SkSL::Version::k100);
195
196 REPORTER_ASSERT(r, SkRuntimeEffectPriv::CanDraw(es2Caps.get(), es2Effect.get()));
197 REPORTER_ASSERT(r, !SkRuntimeEffectPriv::CanDraw(es2Caps.get(), es3Effect.get()));
198 }
199
DEF_TEST(SkRuntimeEffectForColorFilter,r)200 DEF_TEST(SkRuntimeEffectForColorFilter, r) {
201 // Tests that the color filter factory rejects or accepts certain SkSL constructs
202 auto test_valid = [r](const char* sksl) {
203 auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
204 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
205 };
206
207 auto test_invalid = [r](const char* sksl, const char* expected) {
208 auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
209 REPORTER_ASSERT(r, !effect);
210 REPORTER_ASSERT(r,
211 errorText.contains(expected),
212 "Expected error message to contain \"%s\". Actual message: \"%s\"",
213 expected,
214 errorText.c_str());
215 };
216
217 // Color filters must use the 'half4 main(half4)' signature. Either color can be float4/vec4
218 test_valid("half4 main(half4 c) { return c; }");
219 test_valid("float4 main(half4 c) { return c; }");
220 test_valid("half4 main(float4 c) { return c; }");
221 test_valid("float4 main(float4 c) { return c; }");
222 test_valid("vec4 main(half4 c) { return c; }");
223 test_valid("half4 main(vec4 c) { return c; }");
224 test_valid("vec4 main(vec4 c) { return c; }");
225
226 // Invalid return types
227 test_invalid("void main(half4 c) {}", "'main' must return");
228 test_invalid("half3 main(half4 c) { return c.rgb; }", "'main' must return");
229
230 // Invalid argument types (some are valid as shaders, but not color filters)
231 test_invalid("half4 main() { return half4(1); }", "'main' parameter");
232 test_invalid("half4 main(float2 p) { return half4(1); }", "'main' parameter");
233 test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter");
234
235 // sk_FragCoord should not be available
236 test_invalid("half4 main(half4 c) { return sk_FragCoord.xy01; }", "unknown identifier");
237
238 // Sampling a child shader requires that we pass explicit coords
239 test_valid("uniform shader child;"
240 "half4 main(half4 c) { return child.eval(c.rg); }");
241
242 // Sampling a colorFilter requires a color
243 test_valid("uniform colorFilter child;"
244 "half4 main(half4 c) { return child.eval(c); }");
245
246 // Sampling a blender requires two colors
247 test_valid("uniform blender child;"
248 "half4 main(half4 c) { return child.eval(c, c); }");
249 }
250
DEF_TEST(SkRuntimeEffectForBlender,r)251 DEF_TEST(SkRuntimeEffectForBlender, r) {
252 // Tests that the blender factory rejects or accepts certain SkSL constructs
253 auto test_valid = [r](const char* sksl) {
254 auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(sksl));
255 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
256 };
257
258 auto test_invalid = [r](const char* sksl, const char* expected) {
259 auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(sksl));
260 REPORTER_ASSERT(r, !effect);
261 REPORTER_ASSERT(r,
262 errorText.contains(expected),
263 "Expected error message to contain \"%s\". Actual message: \"%s\"",
264 expected,
265 errorText.c_str());
266 };
267
268 // Blenders must use the 'half4 main(half4, half4)' signature. Any mixture of float4/vec4/half4
269 // is allowed.
270 test_valid("half4 main(half4 s, half4 d) { return s; }");
271 test_valid("float4 main(float4 s, float4 d) { return d; }");
272 test_valid("float4 main(half4 s, float4 d) { return s; }");
273 test_valid("half4 main(float4 s, half4 d) { return d; }");
274 test_valid("vec4 main(half4 s, half4 d) { return s; }");
275 test_valid("half4 main(vec4 s, vec4 d) { return d; }");
276 test_valid("vec4 main(vec4 s, vec4 d) { return s; }");
277
278 // Invalid return types
279 test_invalid("void main(half4 s, half4 d) {}", "'main' must return");
280 test_invalid("half3 main(half4 s, half4 d) { return s.rgb; }", "'main' must return");
281
282 // Invalid argument types (some are valid as shaders/color filters)
283 test_invalid("half4 main() { return half4(1); }", "'main' parameter");
284 test_invalid("half4 main(half4 c) { return c; }", "'main' parameter");
285 test_invalid("half4 main(float2 p) { return half4(1); }", "'main' parameter");
286 test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter");
287 test_invalid("half4 main(float2 p, half4 a, half4 b) { return a; }", "'main' parameter");
288 test_invalid("half4 main(half4 a, half4 b, half4 c) { return a; }", "'main' parameter");
289
290 // sk_FragCoord should not be available
291 test_invalid("half4 main(half4 s, half4 d) { return sk_FragCoord.xy01; }",
292 "unknown identifier");
293
294 // Sampling a child shader requires that we pass explicit coords
295 test_valid("uniform shader child;"
296 "half4 main(half4 s, half4 d) { return child.eval(s.rg); }");
297
298 // Sampling a colorFilter requires a color
299 test_valid("uniform colorFilter child;"
300 "half4 main(half4 s, half4 d) { return child.eval(d); }");
301
302 // Sampling a blender requires two colors
303 test_valid("uniform blender child;"
304 "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
305 }
306
DEF_TEST(SkRuntimeEffectForShader,r)307 DEF_TEST(SkRuntimeEffectForShader, r) {
308 // Tests that the shader factory rejects or accepts certain SkSL constructs
309 auto test_valid = [r](const char* sksl, SkRuntimeEffect::Options options = {}) {
310 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl), options);
311 REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
312 };
313
314 auto test_invalid = [r](const char* sksl,
315 const char* expected,
316 SkRuntimeEffect::Options options = {}) {
317 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
318 REPORTER_ASSERT(r, !effect);
319 REPORTER_ASSERT(r,
320 errorText.contains(expected),
321 "Expected error message to contain \"%s\". Actual message: \"%s\"",
322 expected,
323 errorText.c_str());
324 };
325
326 // Shaders must use the 'half4 main(float2)' signature
327 // Either color can be half4/float4/vec4, but the coords must be float2/vec2
328 test_valid("half4 main(float2 p) { return p.xyxy; }");
329 test_valid("float4 main(float2 p) { return p.xyxy; }");
330 test_valid("vec4 main(float2 p) { return p.xyxy; }");
331 test_valid("half4 main(vec2 p) { return p.xyxy; }");
332 test_valid("vec4 main(vec2 p) { return p.xyxy; }");
333
334 // The 'half4 main(float2, half4|float4)' signature is disallowed on both public and private
335 // runtime effects.
336 SkRuntimeEffect::Options options;
337 SkRuntimeEffectPriv::AllowPrivateAccess(&options);
338 test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter");
339 test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter", options);
340
341 test_invalid("half4 main(float2 p, float4 c) { return c; }", "'main' parameter");
342 test_invalid("half4 main(float2 p, float4 c) { return c; }", "'main' parameter", options);
343
344 test_invalid("half4 main(float2 p, vec4 c) { return c; }", "'main' parameter");
345 test_invalid("half4 main(float2 p, vec4 c) { return c; }", "'main' parameter", options);
346
347 test_invalid("float4 main(float2 p, half4 c) { return c; }", "'main' parameter");
348 test_invalid("float4 main(float2 p, half4 c) { return c; }", "'main' parameter", options);
349
350 test_invalid("vec4 main(float2 p, half4 c) { return c; }", "'main' parameter");
351 test_invalid("vec4 main(float2 p, half4 c) { return c; }", "'main' parameter", options);
352
353 test_invalid("vec4 main(vec2 p, vec4 c) { return c; }", "'main' parameter");
354 test_invalid("vec4 main(vec2 p, vec4 c) { return c; }", "'main' parameter", options);
355
356 // Invalid return types
357 test_invalid("void main(float2 p) {}", "'main' must return");
358 test_invalid("half3 main(float2 p) { return p.xy1; }", "'main' must return");
359
360 // Invalid argument types (some are valid as color filters, but not shaders)
361 test_invalid("half4 main() { return half4(1); }", "'main' parameter");
362 test_invalid("half4 main(half4 c) { return c; }", "'main' parameter");
363
364 // sk_FragCoord should be available, but only if we've enabled it via Options
365 test_invalid("half4 main(float2 p) { return sk_FragCoord.xy01; }",
366 "unknown identifier 'sk_FragCoord'");
367
368 test_valid("half4 main(float2 p) { return sk_FragCoord.xy01; }", options);
369
370 // Sampling a child shader requires that we pass explicit coords
371 test_valid("uniform shader child;"
372 "half4 main(float2 p) { return child.eval(p); }");
373
374 // Sampling a colorFilter requires a color
375 test_valid("uniform colorFilter child;"
376 "half4 main(float2 p) { return child.eval(half4(1)); }");
377
378 // Sampling a blender requires two colors
379 test_valid("uniform blender child;"
380 "half4 main(float2 p) { return child.eval(half4(0.5), half4(0.6)); }");
381 }
382
383 using PreTestFn = std::function<void(SkCanvas*, SkPaint*)>;
384
paint_canvas(SkCanvas * canvas,SkPaint * paint,const PreTestFn & preTestCallback)385 void paint_canvas(SkCanvas* canvas, SkPaint* paint, const PreTestFn& preTestCallback) {
386 canvas->save();
387 if (preTestCallback) {
388 preTestCallback(canvas, paint);
389 }
390 canvas->drawPaint(*paint);
391 canvas->restore();
392 }
393
read_pixels(SkSurface * surface,GrColor * pixels)394 static bool read_pixels(SkSurface* surface,
395 GrColor* pixels) {
396 SkImageInfo info = surface->imageInfo();
397 SkPixmap dest{info, pixels, info.minRowBytes()};
398 return surface->readPixels(dest, /*srcX=*/0, /*srcY=*/0);
399 }
400
verify_2x2_surface_results(skiatest::Reporter * r,const SkRuntimeEffect * effect,SkSurface * surface,std::array<GrColor,4> expected)401 static void verify_2x2_surface_results(skiatest::Reporter* r,
402 const SkRuntimeEffect* effect,
403 SkSurface* surface,
404 std::array<GrColor, 4> expected) {
405 std::array<GrColor, 4> actual;
406 SkImageInfo info = surface->imageInfo();
407 if (!read_pixels(surface, actual.data())) {
408 REPORT_FAILURE(r, "readPixels", SkString("readPixels failed"));
409 return;
410 }
411
412 if (actual != expected) {
413 REPORT_FAILURE(r, "Runtime effect didn't match expectations",
414 SkStringPrintf("\n"
415 "Expected: [ %08x %08x %08x %08x ]\n"
416 "Got : [ %08x %08x %08x %08x ]\n"
417 "SkSL:\n%s\n",
418 expected[0], expected[1], expected[2], expected[3],
419 actual[0], actual[1], actual[2], actual[3],
420 effect->source().c_str()));
421 }
422 }
423
make_surface(GrRecordingContext * grContext,const GraphiteInfo * graphite,SkISize size)424 static sk_sp<SkSurface> make_surface(GrRecordingContext* grContext,
425 const GraphiteInfo* graphite,
426 SkISize size) {
427 const SkImageInfo info = SkImageInfo::Make(size, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
428 sk_sp<SkSurface> surface;
429 if (graphite) {
430 #if defined(SK_GRAPHITE)
431 surface = SkSurface::MakeGraphite(graphite->recorder, info);
432 #endif
433 } else if (grContext) {
434 surface = SkSurface::MakeRenderTarget(grContext, skgpu::Budgeted::kNo, info);
435 } else {
436 surface = SkSurface::MakeRaster(info);
437 }
438 SkASSERT(surface);
439 return surface;
440 }
441
442 class TestEffect {
443 public:
TestEffect(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite,SkISize size={2, 2})444 TestEffect(skiatest::Reporter* r,
445 GrRecordingContext* grContext,
446 const GraphiteInfo* graphite,
447 SkISize size = {2, 2})
448 : fReporter(r), fGrContext(grContext), fGraphite(graphite), fSize(size) {
449 fSurface = make_surface(fGrContext, fGraphite, fSize);
450 }
451
build(const char * src)452 void build(const char* src) {
453 SkRuntimeEffect::Options options;
454 SkRuntimeEffectPriv::AllowPrivateAccess(&options);
455 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src), options);
456 if (!effect) {
457 ERRORF(fReporter, "Effect didn't compile: %s", errorText.c_str());
458 return;
459 }
460 fBuilder.init(std::move(effect));
461 }
462
uniform(const char * name)463 SkRuntimeShaderBuilder::BuilderUniform uniform(const char* name) {
464 return fBuilder->uniform(name);
465 }
466
child(const char * name)467 SkRuntimeShaderBuilder::BuilderChild child(const char* name) {
468 return fBuilder->child(name);
469 }
470
test(std::array<GrColor,4> expected,PreTestFn preTestCallback=nullptr)471 void test(std::array<GrColor, 4> expected, PreTestFn preTestCallback = nullptr) {
472 auto shader = fBuilder->makeShader();
473 if (!shader) {
474 ERRORF(fReporter, "Effect didn't produce a shader");
475 return;
476 }
477
478 SkCanvas* canvas = fSurface->getCanvas();
479
480 // We shouldn't need to clear the canvas, because we are about to paint over the whole thing
481 // with a `source` blend mode. However, there are a few devices where the background can
482 // leak through when we paint with MSAA on. (This seems to be a driver/hardware bug.)
483 // Graphite, at present, uses MSAA to do `drawPaint`. To avoid flakiness in this test on
484 // those devices, we explicitly clear the canvas here. (skia:13761)
485 canvas->clear(SK_ColorBLACK);
486
487 SkPaint paint;
488 paint.setShader(std::move(shader));
489 paint.setBlendMode(SkBlendMode::kSrc);
490
491 paint_canvas(canvas, &paint, preTestCallback);
492
493 verify_2x2_surface_results(fReporter, fBuilder->effect(), fSurface.get(), expected);
494 }
495
trace(const SkIPoint & traceCoord)496 std::string trace(const SkIPoint& traceCoord) {
497 sk_sp<SkShader> shader = fBuilder->makeShader();
498 if (!shader) {
499 ERRORF(fReporter, "Effect didn't produce a shader");
500 return {};
501 }
502
503 auto [debugShader, debugTrace] = SkRuntimeEffect::MakeTraced(std::move(shader), traceCoord);
504
505 SkCanvas* canvas = fSurface->getCanvas();
506 SkPaint paint;
507 paint.setShader(std::move(debugShader));
508 paint.setBlendMode(SkBlendMode::kSrc);
509
510 paint_canvas(canvas, &paint, /*preTestCallback=*/nullptr);
511
512 SkDynamicMemoryWStream wstream;
513 debugTrace->dump(&wstream);
514 sk_sp<SkData> streamData = wstream.detachAsData();
515 return std::string(static_cast<const char*>(streamData->data()), streamData->size());
516 }
517
test(GrColor expected,PreTestFn preTestCallback=nullptr)518 void test(GrColor expected, PreTestFn preTestCallback = nullptr) {
519 this->test({expected, expected, expected, expected}, preTestCallback);
520 }
521
522 private:
523 skiatest::Reporter* fReporter;
524 sk_sp<SkSurface> fSurface;
525 GrRecordingContext* fGrContext;
526 const GraphiteInfo* fGraphite;
527 SkISize fSize;
528 SkTLazy<SkRuntimeShaderBuilder> fBuilder;
529 };
530
531 class TestBlend {
532 public:
TestBlend(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)533 TestBlend(skiatest::Reporter* r, GrRecordingContext* grContext, const GraphiteInfo* graphite)
534 : fReporter(r), fGrContext(grContext), fGraphite(graphite) {
535 fSurface = make_surface(fGrContext, fGraphite, /*size=*/{2, 2});
536 }
537
build(const char * src)538 void build(const char* src) {
539 auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(src));
540 if (!effect) {
541 ERRORF(fReporter, "Effect didn't compile: %s", errorText.c_str());
542 return;
543 }
544 fBuilder.init(std::move(effect));
545 }
546
surface()547 SkSurface* surface() {
548 return fSurface.get();
549 }
550
uniform(const char * name)551 SkRuntimeBlendBuilder::BuilderUniform uniform(const char* name) {
552 return fBuilder->uniform(name);
553 }
554
child(const char * name)555 SkRuntimeBlendBuilder::BuilderChild child(const char* name) {
556 return fBuilder->child(name);
557 }
558
test(std::array<GrColor,4> expected,PreTestFn preTestCallback=nullptr)559 void test(std::array<GrColor, 4> expected, PreTestFn preTestCallback = nullptr) {
560 auto blender = fBuilder->makeBlender();
561 if (!blender) {
562 ERRORF(fReporter, "Effect didn't produce a blender");
563 return;
564 }
565
566 SkCanvas* canvas = fSurface->getCanvas();
567 SkPaint paint;
568 paint.setBlender(std::move(blender));
569 paint.setColor(SK_ColorGRAY);
570
571 paint_canvas(canvas, &paint, preTestCallback);
572
573 verify_2x2_surface_results(fReporter, fBuilder->effect(), fSurface.get(), expected);
574 }
575
test(GrColor expected,PreTestFn preTestCallback=nullptr)576 void test(GrColor expected, PreTestFn preTestCallback = nullptr) {
577 this->test({expected, expected, expected, expected}, preTestCallback);
578 }
579
580 private:
581 skiatest::Reporter* fReporter;
582 sk_sp<SkSurface> fSurface;
583 GrRecordingContext* fGrContext;
584 const GraphiteInfo* fGraphite;
585 SkTLazy<SkRuntimeBlendBuilder> fBuilder;
586 };
587
588 // Produces a shader which will paint these opaque colors in a 2x2 rectangle:
589 // [ Red, Green ]
590 // [ Blue, White ]
make_RGBW_shader()591 static sk_sp<SkShader> make_RGBW_shader() {
592 static constexpr SkColor colors[] = {SK_ColorWHITE, SK_ColorWHITE,
593 SK_ColorBLUE, SK_ColorBLUE,
594 SK_ColorRED, SK_ColorRED,
595 SK_ColorGREEN, SK_ColorGREEN};
596 static constexpr SkScalar pos[] = { 0, .25f, .25f, .50f, .50f, .75, .75, 1 };
597 static_assert(std::size(colors) == std::size(pos), "size mismatch");
598 return SkGradientShader::MakeSweep(1, 1, colors, pos, std::size(colors));
599 }
600
test_RuntimeEffect_Shaders(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)601 static void test_RuntimeEffect_Shaders(skiatest::Reporter* r,
602 GrRecordingContext* grContext,
603 const GraphiteInfo* graphite) {
604 TestEffect effect(r, grContext, graphite);
605 using float4 = std::array<float, 4>;
606 using int4 = std::array<int, 4>;
607
608 // Local coords
609 effect.build("half4 main(float2 p) { return half4(half2(p - 0.5), 0, 1); }");
610 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
611
612 // Use of a simple uniform. (Draw twice with two values to ensure it's updated).
613 effect.build("uniform float4 gColor; half4 main(float2 p) { return half4(gColor); }");
614 effect.uniform("gColor") = float4{ 0.0f, 0.25f, 0.75f, 1.0f };
615 effect.test(0xFFBF4000);
616 effect.uniform("gColor") = float4{ 1.0f, 0.0f, 0.0f, 0.498f };
617 effect.test(0x7F0000FF); // Tests that we don't clamp to valid premul
618
619 // Same, with integer uniforms
620 effect.build("uniform int4 gColor; half4 main(float2 p) { return half4(gColor) / 255.0; }");
621 effect.uniform("gColor") = int4{ 0x00, 0x40, 0xBF, 0xFF };
622 effect.test(0xFFBF4000);
623 effect.uniform("gColor") = int4{ 0xFF, 0x00, 0x00, 0x7F };
624 effect.test(0x7F0000FF); // Tests that we don't clamp to valid premul
625
626 // Test sk_FragCoord (device coords). Rotate the canvas to be sure we're seeing device coords.
627 // Since the surface is 2x2, we should see (0,0), (1,0), (0,1), (1,1). Multiply by 0.498 to
628 // make sure we're not saturating unexpectedly.
629 effect.build(
630 "half4 main(float2 p) { return half4(0.498 * (half2(sk_FragCoord.xy) - 0.5), 0, 1); }");
631 effect.test({0xFF000000, 0xFF00007F, 0xFF007F00, 0xFF007F7F},
632 [](SkCanvas* canvas, SkPaint*) { canvas->rotate(45.0f); });
633
634 // Runtime effects should use relaxed precision rules by default
635 effect.build("half4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
636 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
637
638 // ... and support *returning* float4 (aka vec4), not just half4
639 effect.build("float4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
640 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
641 effect.build("vec4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
642 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
643
644 // Mutating coords should work. (skbug.com/10918)
645 effect.build("vec4 main(vec2 p) { p -= 0.5; return vec4(p, 0, 1); }");
646 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
647 effect.build("void moveCoords(inout vec2 p) { p -= 0.5; }"
648 "vec4 main(vec2 p) { moveCoords(p); return vec4(p, 0, 1); }");
649 effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
650
651 //
652 // Sampling children
653 //
654
655 // Sampling a null shader should return the paint color
656 if (!graphite) {
657 // TODO: Graphite does not yet pass this test.
658 effect.build("uniform shader child;"
659 "half4 main(float2 p) { return child.eval(p); }");
660 effect.child("child") = nullptr;
661 effect.test(0xFF00FFFF,
662 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
663 }
664
665 // Sampling a null color-filter should return the passed-in color
666 effect.build("uniform colorFilter child;"
667 "half4 main(float2 p) { return child.eval(half4(1, 1, 0, 1)); }");
668 effect.child("child") = nullptr;
669 effect.test(0xFF00FFFF);
670
671 // Sampling a null blender should return blend_src_over(src, dest).
672 effect.build("uniform blender child;"
673 "half4 main(float2 p) {"
674 " float4 src = float4(p - 0.5, 0, 1) * 0.498;"
675 " return child.eval(src, half4(0, 0, 0, 1));"
676 "}");
677 effect.child("child") = nullptr;
678 effect.test({0xFF000000, 0xFF00007F, 0xFF007F00, 0xFF007F7F});
679
680 // Sampling a simple child at our coordinates
681 sk_sp<SkShader> rgbwShader = make_RGBW_shader();
682
683 effect.build("uniform shader child;"
684 "half4 main(float2 p) { return child.eval(p); }");
685 effect.child("child") = rgbwShader;
686 effect.test({0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF});
687
688 // Sampling with explicit coordinates (reflecting about the diagonal)
689 effect.build("uniform shader child;"
690 "half4 main(float2 p) { return child.eval(p.yx); }");
691 effect.child("child") = rgbwShader;
692 effect.test({0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFFFFFFFF});
693
694 // Bind an image shader, but don't use it - ensure that we don't assert or generate bad shaders.
695 // (skbug.com/12429)
696 effect.build("uniform shader child;"
697 "half4 main(float2 p) { return half4(0, 1, 0, 1); }");
698 effect.child("child") = rgbwShader;
699 effect.test(0xFF00FF00);
700
701 //
702 // Helper functions
703 //
704
705 // Test case for inlining in the pipeline-stage and fragment-shader passes (skbug.com/10526):
706 effect.build("float2 helper(float2 x) { return x + 1; }"
707 "half4 main(float2 p) { float2 v = helper(p); return half4(half2(v), 0, 1); }");
708 effect.test(0xFF00FFFF);
709 }
710
DEF_TEST(SkRuntimeEffectSimple,r)711 DEF_TEST(SkRuntimeEffectSimple, r) {
712 test_RuntimeEffect_Shaders(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
713 }
714
715 #if defined(SK_GRAPHITE)
DEF_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_Graphite,r,context)716 DEF_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_Graphite, r, context) {
717 std::unique_ptr<skgpu::graphite::Recorder> recorder = context->makeRecorder();
718 GraphiteInfo graphite = {context, recorder.get()};
719 test_RuntimeEffect_Shaders(r, /*grContext=*/nullptr, &graphite);
720 }
721 #endif
722
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)723 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU,
724 r,
725 ctxInfo,
726 CtsEnforcement::kApiLevel_T) {
727 test_RuntimeEffect_Shaders(r, ctxInfo.directContext(), /*graphite=*/nullptr);
728 }
729
verify_draw_obeys_capabilities(skiatest::Reporter * r,const SkRuntimeEffect * effect,SkSurface * surface,const SkPaint & paint)730 static void verify_draw_obeys_capabilities(skiatest::Reporter* r,
731 const SkRuntimeEffect* effect,
732 SkSurface* surface,
733 const SkPaint& paint) {
734 // We expect the draw to do something if-and-only-if expectSuccess is true:
735 const bool expectSuccess = surface->capabilities()->skslVersion() >= SkSL::Version::k300;
736
737 constexpr GrColor kGreen = 0xFF00FF00;
738 constexpr GrColor kRed = 0xFF0000FF;
739 const GrColor kExpected = expectSuccess ? kGreen : kRed;
740
741 surface->getCanvas()->clear(SK_ColorRED);
742 surface->getCanvas()->drawPaint(paint);
743 verify_2x2_surface_results(r, effect, surface, {kExpected, kExpected, kExpected, kExpected});
744 }
745
test_RuntimeEffectObeysCapabilities(skiatest::Reporter * r,SkSurface * surface)746 static void test_RuntimeEffectObeysCapabilities(skiatest::Reporter* r, SkSurface* surface) {
747 // This test creates shaders and blenders that target `#version 300`. If a user validates an
748 // effect like this against a particular device, and later draws that effect to a device with
749 // insufficient capabilities -- we want to fail gracefully (drop the draw entirely).
750 // If the capabilities indicate that the effect is supported, we expect it to work.
751 //
752 // We test two different scenarios here:
753 // 1) An effect flagged as #version 300, but actually compatible with #version 100.
754 // 2) An effect flagged as #version 300, and using features not available in ES2.
755 //
756 // We expect both cases to fail cleanly on ES2-only devices -- nothing should be drawn, and
757 // there should be no asserts or driver shader-compilation errors.
758 //
759 // In all tests, we first clear the canvas to RED, then draw an effect that (if it renders)
760 // will fill the canvas with GREEN. We check that the final colors match our expectations,
761 // based on the device capabilities.
762
763 // Effect that would actually work on CPU/ES2, but should still fail on those devices:
764 {
765 auto effect = SkRuntimeEffect::MakeForShader(SkString(R"(
766 #version 300
767 half4 main(float2 xy) { return half4(0, 1, 0, 1); }
768 )")).effect;
769 REPORTER_ASSERT(r, effect);
770 SkPaint paint;
771 paint.setShader(effect->makeShader(/*uniforms=*/nullptr, /*children=*/{}));
772 REPORTER_ASSERT(r, paint.getShader());
773 verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
774 }
775
776 // Effect that won't work on CPU/ES2 at all, and should fail gracefully on those devices.
777 // We choose to use bit-pun intrinsics because SkSL doesn't automatically inject an extension
778 // to enable them (like it does for derivatives). We pass a non-literal value so that SkSL's
779 // constant folding doesn't elide them entirely before the driver sees the shader.
780 {
781 auto effect = SkRuntimeEffect::MakeForShader(SkString(R"(
782 #version 300
783 half4 main(float2 xy) {
784 half4 result = half4(0, 1, 0, 1);
785 result.g = intBitsToFloat(floatBitsToInt(result.g));
786 return result;
787 }
788 )")).effect;
789 REPORTER_ASSERT(r, effect);
790 SkPaint paint;
791 paint.setShader(effect->makeShader(/*uniforms=*/nullptr, /*children=*/{}));
792 REPORTER_ASSERT(r, paint.getShader());
793 verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
794 }
795
796 //
797 // As above, but with a blender
798 //
799
800 {
801 auto effect = SkRuntimeEffect::MakeForBlender(SkString(R"(
802 #version 300
803 half4 main(half4 src, half4 dst) { return half4(0, 1, 0, 1); }
804 )")).effect;
805 REPORTER_ASSERT(r, effect);
806 SkPaint paint;
807 paint.setBlender(effect->makeBlender(/*uniforms=*/nullptr, /*children=*/{}));
808 REPORTER_ASSERT(r, paint.getBlender());
809 verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
810 }
811
812 {
813 auto effect = SkRuntimeEffect::MakeForBlender(SkString(R"(
814 #version 300
815 half4 main(half4 src, half4 dst) {
816 half4 result = half4(0, 1, 0, 1);
817 result.g = intBitsToFloat(floatBitsToInt(result.g));
818 return result;
819 }
820 )")).effect;
821 REPORTER_ASSERT(r, effect);
822 SkPaint paint;
823 paint.setBlender(effect->makeBlender(/*uniforms=*/nullptr, /*children=*/{}));
824 REPORTER_ASSERT(r, paint.getBlender());
825 verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
826 }
827 }
828
DEF_TEST(SkRuntimeEffectObeysCapabilities_CPU,r)829 DEF_TEST(SkRuntimeEffectObeysCapabilities_CPU, r) {
830 SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
831 sk_sp<SkSurface> surface = SkSurface::MakeRaster(info);
832 REPORTER_ASSERT(r, surface);
833 test_RuntimeEffectObeysCapabilities(r, surface.get());
834 }
835
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectObeysCapabilities_GPU,r,ctxInfo,CtsEnforcement::kNextRelease)836 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectObeysCapabilities_GPU,
837 r,
838 ctxInfo,
839 CtsEnforcement::kNextRelease) {
840 SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
841 sk_sp<SkSurface> surface =
842 SkSurface::MakeRenderTarget(ctxInfo.directContext(), skgpu::Budgeted::kNo, info);
843 REPORTER_ASSERT(r, surface);
844 test_RuntimeEffectObeysCapabilities(r, surface.get());
845 }
846
DEF_TEST(SkRuntimeColorFilterLimitedToES2,r)847 DEF_TEST(SkRuntimeColorFilterLimitedToES2, r) {
848 // Verify that SkSL requesting #version 300 can't be used to create a color-filter effect.
849 // This restriction could be removed if we can find a way to implement filterColor for these
850 // color filters.
851 {
852 auto effect = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
853 #version 300
854 half4 main(half4 inColor) { return half4(1, 0, 0, 1); }
855 )")).effect;
856 REPORTER_ASSERT(r, !effect);
857 }
858
859 {
860 auto effect = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
861 #version 300
862 uniform int loops;
863 half4 main(half4 inColor) {
864 half4 result = half4(1, 0, 0, 1);
865 for (int i = 0; i < loops; i++) {
866 result = result.argb;
867 }
868 return result;
869 }
870 )")).effect;
871 REPORTER_ASSERT(r, !effect);
872 }
873 }
874
DEF_TEST(SkRuntimeEffectTraceShader,r)875 DEF_TEST(SkRuntimeEffectTraceShader, r) {
876 for (int imageSize : {2, 80}) {
877 TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr,
878 SkISize{imageSize, imageSize});
879 effect.build(R"(
880 half4 main(float2 p) {
881 float2 val = p - 0.5;
882 return val.0y01;
883 }
884 )");
885 int center = imageSize / 2;
886 std::string dump = effect.trace({center, 1});
887 auto expectation = SkSL::String::printf(R"($0 = [main].result (float4 : slot 1/4, L2)
888 $1 = [main].result (float4 : slot 2/4, L2)
889 $2 = [main].result (float4 : slot 3/4, L2)
890 $3 = [main].result (float4 : slot 4/4, L2)
891 $4 = p (float2 : slot 1/2, L2)
892 $5 = p (float2 : slot 2/2, L2)
893 $6 = val (float2 : slot 1/2, L3)
894 $7 = val (float2 : slot 2/2, L3)
895 F0 = half4 main(float2 p)
896
897 enter half4 main(float2 p)
898 p.x = %d.5
899 p.y = 1.5
900 scope +1
901 line 3
902 val.x = %d
903 val.y = 1
904 line 4
905 [main].result.x = 0
906 [main].result.y = 1
907 [main].result.z = 0
908 [main].result.w = 1
909 scope -1
910 exit half4 main(float2 p)
911 )", center, center);
912 REPORTER_ASSERT(r, dump == expectation,
913 "Trace output does not match expectation for %dx%d:\n%.*s\n",
914 imageSize, imageSize, (int)dump.size(), dump.data());
915 }
916 }
917
DEF_TEST(SkRuntimeEffectTracesAreUnoptimized,r)918 DEF_TEST(SkRuntimeEffectTracesAreUnoptimized, r) {
919 TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
920
921 effect.build(R"(
922 int globalUnreferencedVar = 7;
923 half inlinableFunction() {
924 return 1;
925 }
926 half4 main(float2 p) {
927 if (true) {
928 int localUnreferencedVar = 7;
929 }
930 return inlinableFunction().xxxx;
931 }
932 )");
933 std::string dump = effect.trace({1, 1});
934 constexpr char kExpectation[] = R"($0 = globalUnreferencedVar (int, L2)
935 $1 = [main].result (float4 : slot 1/4, L6)
936 $2 = [main].result (float4 : slot 2/4, L6)
937 $3 = [main].result (float4 : slot 3/4, L6)
938 $4 = [main].result (float4 : slot 4/4, L6)
939 $5 = p (float2 : slot 1/2, L6)
940 $6 = p (float2 : slot 2/2, L6)
941 $7 = localUnreferencedVar (int, L8)
942 $8 = [inlinableFunction].result (float, L3)
943 F0 = half4 main(float2 p)
944 F1 = half inlinableFunction()
945
946 globalUnreferencedVar = 7
947 enter half4 main(float2 p)
948 p.x = 1.5
949 p.y = 1.5
950 scope +1
951 line 7
952 scope +1
953 line 8
954 localUnreferencedVar = 7
955 scope -1
956 line 10
957 enter half inlinableFunction()
958 scope +1
959 line 4
960 [inlinableFunction].result = 1
961 scope -1
962 exit half inlinableFunction()
963 [main].result.x = 1
964 [main].result.y = 1
965 [main].result.z = 1
966 [main].result.w = 1
967 scope -1
968 exit half4 main(float2 p)
969 )";
970 REPORTER_ASSERT(r, dump == kExpectation,
971 "Trace output does not match expectation:\n%.*s\n",
972 (int)dump.size(), dump.data());
973 }
974
DEF_TEST(SkRuntimeEffectTraceCodeThatCannotBeUnoptimized,r)975 DEF_TEST(SkRuntimeEffectTraceCodeThatCannotBeUnoptimized, r) {
976 TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
977
978 effect.build(R"(
979 half4 main(float2 p) {
980 int variableThatGetsOptimizedAway = 7;
981 if (true) {
982 return half4(1);
983 }
984 // This (unreachable) path doesn't return a value.
985 // Without optimization, SkSL thinks this code doesn't return a value on every path.
986 }
987 )");
988 std::string dump = effect.trace({1, 1});
989 constexpr char kExpectation[] = R"($0 = [main].result (float4 : slot 1/4, L2)
990 $1 = [main].result (float4 : slot 2/4, L2)
991 $2 = [main].result (float4 : slot 3/4, L2)
992 $3 = [main].result (float4 : slot 4/4, L2)
993 $4 = p (float2 : slot 1/2, L2)
994 $5 = p (float2 : slot 2/2, L2)
995 F0 = half4 main(float2 p)
996
997 enter half4 main(float2 p)
998 p.x = 1.5
999 p.y = 1.5
1000 scope +1
1001 scope +1
1002 line 5
1003 [main].result.x = 1
1004 [main].result.y = 1
1005 [main].result.z = 1
1006 [main].result.w = 1
1007 scope -1
1008 scope -1
1009 exit half4 main(float2 p)
1010 )";
1011 REPORTER_ASSERT(r, dump == kExpectation,
1012 "Trace output does not match expectation:\n%.*s\n",
1013 (int)dump.size(), dump.data());
1014 }
1015
test_RuntimeEffect_Blenders(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)1016 static void test_RuntimeEffect_Blenders(skiatest::Reporter* r,
1017 GrRecordingContext* grContext,
1018 const GraphiteInfo* graphite) {
1019 TestBlend effect(r, grContext, graphite);
1020
1021 using float2 = std::array<float, 2>;
1022 using float4 = std::array<float, 4>;
1023 using int4 = std::array<int, 4>;
1024
1025 // Use of a simple uniform. (Draw twice with two values to ensure it's updated).
1026 effect.build("uniform float4 gColor; half4 main(half4 s, half4 d) { return half4(gColor); }");
1027 effect.uniform("gColor") = float4{ 0.0f, 0.25f, 0.75f, 1.0f };
1028 effect.test(0xFFBF4000);
1029 effect.uniform("gColor") = float4{ 1.0f, 0.0f, 0.0f, 0.498f };
1030 effect.test(0x7F0000FF); // We don't clamp here either
1031
1032 // Same, with integer uniforms
1033 effect.build("uniform int4 gColor;"
1034 "half4 main(half4 s, half4 d) { return half4(gColor) / 255.0; }");
1035 effect.uniform("gColor") = int4{ 0x00, 0x40, 0xBF, 0xFF };
1036 effect.test(0xFFBF4000);
1037 effect.uniform("gColor") = int4{ 0xFF, 0x00, 0x00, 0x7F };
1038 effect.test(0x7F0000FF); // We don't clamp here either
1039
1040 // Verify that mutating the source and destination colors is allowed
1041 effect.build("half4 main(half4 s, half4 d) { s += d; d += s; return half4(1); }");
1042 effect.test(0xFFFFFFFF);
1043
1044 // Verify that we can write out the source color (ignoring the dest color)
1045 // This is equivalent to the kSrc blend mode.
1046 effect.build("half4 main(half4 s, half4 d) { return s; }");
1047 effect.test(0xFF888888);
1048
1049 // Fill the destination with a variety of colors (using the RGBW shader)
1050 SkPaint rgbwPaint;
1051 rgbwPaint.setShader(make_RGBW_shader());
1052 rgbwPaint.setBlendMode(SkBlendMode::kSrc);
1053 effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1054
1055 // Verify that we can read back the dest color exactly as-is (ignoring the source color)
1056 // This is equivalent to the kDst blend mode.
1057 effect.build("half4 main(half4 s, half4 d) { return d; }");
1058 effect.test({0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF});
1059
1060 // Verify that we can invert the destination color (including the alpha channel).
1061 // The expected outputs are the exact inverse of the previous test.
1062 effect.build("half4 main(half4 s, half4 d) { return half4(1) - d; }");
1063 effect.test({0x00FFFF00, 0x00FF00FF, 0x0000FFFF, 0x00000000});
1064
1065 // Verify that color values are clamped to 0 and 1.
1066 effect.build("half4 main(half4 s, half4 d) { return half4(-1); }");
1067 effect.test(0x00000000);
1068 effect.build("half4 main(half4 s, half4 d) { return half4(2); }");
1069 effect.test(0xFFFFFFFF);
1070
1071 //
1072 // Sampling children
1073 //
1074
1075 // Sampling a null shader/color filter should return the paint color.
1076 effect.build("uniform shader child;"
1077 "half4 main(half4 s, half4 d) { return child.eval(s.rg); }");
1078 effect.child("child") = nullptr;
1079 effect.test(0xFF00FFFF,
1080 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
1081
1082 effect.build("uniform colorFilter child;"
1083 "half4 main(half4 s, half4 d) { return child.eval(s); }");
1084 effect.child("child") = nullptr;
1085 effect.test(0xFF00FFFF,
1086 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
1087
1088 // Sampling a null blender should do a src-over blend. Draw 50% black over RGBW to verify this.
1089 effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1090 effect.build("uniform blender child;"
1091 "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1092 effect.child("child") = nullptr;
1093 effect.test({0xFF000080, 0xFF008000, 0xFF800000, 0xFF808080},
1094 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({0.0f, 0.0f, 0.0f, 0.497f}); });
1095
1096 // Sampling a shader at various coordinates
1097 effect.build("uniform shader child;"
1098 "uniform half2 pos;"
1099 "half4 main(half4 s, half4 d) { return child.eval(pos); }");
1100 effect.child("child") = make_RGBW_shader();
1101 effect.uniform("pos") = float2{0.5, 0.5};
1102 effect.test(0xFF0000FF);
1103
1104 effect.uniform("pos") = float2{1.5, 0.5};
1105 effect.test(0xFF00FF00);
1106
1107 effect.uniform("pos") = float2{0.5, 1.5};
1108 effect.test(0xFFFF0000);
1109
1110 effect.uniform("pos") = float2{1.5, 1.5};
1111 effect.test(0xFFFFFFFF);
1112
1113 // Sampling a color filter
1114 effect.build("uniform colorFilter child;"
1115 "half4 main(half4 s, half4 d) { return child.eval(half4(1)); }");
1116 effect.child("child") = SkColorFilters::Blend(0xFF012345, SkBlendMode::kSrc);
1117 effect.test(0xFF452301);
1118
1119 // Sampling a built-in blender
1120 effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1121 effect.build("uniform blender child;"
1122 "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1123 effect.child("child") = SkBlender::Mode(SkBlendMode::kPlus);
1124 effect.test({0xFF4523FF, 0xFF45FF01, 0xFFFF2301, 0xFFFFFFFF},
1125 [](SkCanvas*, SkPaint* paint) { paint->setColor(0xFF012345); });
1126
1127 // Sampling a runtime-effect blender
1128 effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1129 effect.build("uniform blender child;"
1130 "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1131 effect.child("child") = SkBlenders::Arithmetic(0, 1, 1, 0, /*enforcePremul=*/false);
1132 effect.test({0xFF4523FF, 0xFF45FF01, 0xFFFF2301, 0xFFFFFFFF},
1133 [](SkCanvas*, SkPaint* paint) { paint->setColor(0xFF012345); });
1134 }
1135
DEF_TEST(SkRuntimeEffect_Blender_CPU,r)1136 DEF_TEST(SkRuntimeEffect_Blender_CPU, r) {
1137 test_RuntimeEffect_Blenders(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
1138 }
1139
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffect_Blender_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)1140 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffect_Blender_GPU,
1141 r,
1142 ctxInfo,
1143 CtsEnforcement::kApiLevel_T) {
1144 test_RuntimeEffect_Blenders(r, ctxInfo.directContext(), /*graphite=*/nullptr);
1145 }
1146
DEF_TEST(SkRuntimeShaderBuilderReuse,r)1147 DEF_TEST(SkRuntimeShaderBuilderReuse, r) {
1148 const char* kSource = R"(
1149 uniform half x;
1150 half4 main(float2 p) { return half4(x); }
1151 )";
1152
1153 sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
1154 REPORTER_ASSERT(r, effect);
1155
1156 // Test passes if this sequence doesn't assert. skbug.com/10667
1157 SkRuntimeShaderBuilder b(std::move(effect));
1158 b.uniform("x") = 0.0f;
1159 auto shader_0 = b.makeShader();
1160
1161 b.uniform("x") = 1.0f;
1162 auto shader_1 = b.makeShader();
1163 }
1164
DEF_TEST(SkRuntimeBlendBuilderReuse,r)1165 DEF_TEST(SkRuntimeBlendBuilderReuse, r) {
1166 const char* kSource = R"(
1167 uniform half x;
1168 half4 main(half4 s, half4 d) { return half4(x); }
1169 )";
1170
1171 sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForBlender(SkString(kSource)).effect;
1172 REPORTER_ASSERT(r, effect);
1173
1174 // We should be able to construct multiple SkBlenders in a row without asserting.
1175 SkRuntimeBlendBuilder b(std::move(effect));
1176 for (float x = 0.0f; x <= 2.0f; x += 2.0f) {
1177 b.uniform("x") = x;
1178 sk_sp<SkBlender> blender = b.makeBlender();
1179 }
1180 }
1181
DEF_TEST(SkRuntimeShaderBuilderSetUniforms,r)1182 DEF_TEST(SkRuntimeShaderBuilderSetUniforms, r) {
1183 const char* kSource = R"(
1184 uniform half x;
1185 uniform vec2 offset;
1186 half4 main(float2 p) { return half4(x); }
1187 )";
1188
1189 sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
1190 REPORTER_ASSERT(r, effect);
1191
1192 SkRuntimeShaderBuilder b(std::move(effect));
1193
1194 // Test passes if this sequence doesn't assert.
1195 float x = 1.0f;
1196 REPORTER_ASSERT(r, b.uniform("x").set(&x, 1));
1197
1198 // add extra value to ensure that set doesn't try to use sizeof(array)
1199 float origin[] = { 2.0f, 3.0f, 4.0f };
1200 REPORTER_ASSERT(r, b.uniform("offset").set<float>(origin, 2));
1201
1202 #ifndef SK_DEBUG
1203 REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 1));
1204 REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 3));
1205 #endif
1206
1207 auto shader = b.makeShader();
1208 }
1209
DEF_TEST(SkRuntimeEffectThreaded,r)1210 DEF_TEST(SkRuntimeEffectThreaded, r) {
1211 // This tests that we can safely use SkRuntimeEffect::MakeForShader from more than one thread,
1212 // and also that programs don't refer to shared structures owned by the compiler.
1213 // skbug.com/10589
1214 static constexpr char kSource[] = "half4 main(float2 p) { return sk_FragCoord.xyxy; }";
1215
1216 std::thread threads[16];
1217 for (auto& thread : threads) {
1218 thread = std::thread([r]() {
1219 SkRuntimeEffect::Options options;
1220 SkRuntimeEffectPriv::AllowPrivateAccess(&options);
1221 auto [effect, error] = SkRuntimeEffect::MakeForShader(SkString(kSource), options);
1222 REPORTER_ASSERT(r, effect);
1223 });
1224 }
1225
1226 for (auto& thread : threads) {
1227 thread.join();
1228 }
1229 }
1230
DEF_TEST(SkRuntimeEffectAllowsPrivateAccess,r)1231 DEF_TEST(SkRuntimeEffectAllowsPrivateAccess, r) {
1232 SkRuntimeEffect::Options defaultOptions;
1233 SkRuntimeEffect::Options optionsWithAccess;
1234 SkRuntimeEffectPriv::AllowPrivateAccess(&optionsWithAccess);
1235
1236 // Confirm that shaders can only access $private_functions when private access is allowed.
1237 {
1238 static constexpr char kShader[] =
1239 "half4 main(float2 p) { return $hsl_to_rgb(p.xxx, p.y); }";
1240 SkRuntimeEffect::Result normal =
1241 SkRuntimeEffect::MakeForShader(SkString(kShader), defaultOptions);
1242 REPORTER_ASSERT(r, !normal.effect);
1243 SkRuntimeEffect::Result privileged =
1244 SkRuntimeEffect::MakeForShader(SkString(kShader), optionsWithAccess);
1245 REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1246 }
1247
1248 // Confirm that color filters can only access $private_functions when private access is allowed.
1249 {
1250 static constexpr char kColorFilter[] =
1251 "half4 main(half4 c) { return $hsl_to_rgb(c.rgb, c.a); }";
1252 SkRuntimeEffect::Result normal =
1253 SkRuntimeEffect::MakeForColorFilter(SkString(kColorFilter), defaultOptions);
1254 REPORTER_ASSERT(r, !normal.effect);
1255 SkRuntimeEffect::Result privileged =
1256 SkRuntimeEffect::MakeForColorFilter(SkString(kColorFilter), optionsWithAccess);
1257 REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1258 }
1259
1260 // Confirm that blenders can only access $private_functions when private access is allowed.
1261 {
1262 static constexpr char kBlender[] =
1263 "half4 main(half4 s, half4 d) { return $hsl_to_rgb(s.rgb, d.a); }";
1264 SkRuntimeEffect::Result normal =
1265 SkRuntimeEffect::MakeForBlender(SkString(kBlender), defaultOptions);
1266 REPORTER_ASSERT(r, !normal.effect);
1267 SkRuntimeEffect::Result privileged =
1268 SkRuntimeEffect::MakeForBlender(SkString(kBlender), optionsWithAccess);
1269 REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1270 }
1271 }
1272
DEF_TEST(SkRuntimeColorFilterSingleColor,r)1273 DEF_TEST(SkRuntimeColorFilterSingleColor, r) {
1274 // Test runtime colorfilters support filterColor4f().
1275 auto [effect, err] =
1276 SkRuntimeEffect::MakeForColorFilter(SkString{"half4 main(half4 c) { return c*c; }"});
1277 REPORTER_ASSERT(r, effect);
1278 REPORTER_ASSERT(r, err.isEmpty());
1279
1280 sk_sp<SkColorFilter> cf = effect->makeColorFilter(SkData::MakeEmpty());
1281 REPORTER_ASSERT(r, cf);
1282
1283 SkColor4f c = cf->filterColor4f({0.25, 0.5, 0.75, 1.0},
1284 sk_srgb_singleton(), sk_srgb_singleton());
1285 REPORTER_ASSERT(r, c.fR == 0.0625f);
1286 REPORTER_ASSERT(r, c.fG == 0.25f);
1287 REPORTER_ASSERT(r, c.fB == 0.5625f);
1288 REPORTER_ASSERT(r, c.fA == 1.0f);
1289 }
1290
test_RuntimeEffectStructNameReuse(skiatest::Reporter * r,GrRecordingContext * rContext)1291 static void test_RuntimeEffectStructNameReuse(skiatest::Reporter* r, GrRecordingContext* rContext) {
1292 // Test that two different runtime effects can reuse struct names in a single paint operation
1293 auto [childEffect, err] = SkRuntimeEffect::MakeForShader(SkString(
1294 "uniform shader paint;"
1295 "struct S { half4 rgba; };"
1296 "void process(inout S s) { s.rgba.rgb *= 0.5; }"
1297 "half4 main(float2 p) { S s; s.rgba = paint.eval(p); process(s); return s.rgba; }"
1298 ));
1299 REPORTER_ASSERT(r, childEffect, "%s\n", err.c_str());
1300 sk_sp<SkShader> nullChild = nullptr;
1301 sk_sp<SkShader> child = childEffect->makeShader(/*uniforms=*/nullptr,
1302 &nullChild,
1303 /*childCount=*/1);
1304
1305 TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
1306 effect.build(
1307 "uniform shader child;"
1308 "struct S { float2 coord; };"
1309 "void process(inout S s) { s.coord = s.coord.yx; }"
1310 "half4 main(float2 p) { S s; s.coord = p; process(s); return child.eval(s.coord); "
1311 "}");
1312 effect.child("child") = child;
1313 effect.test(0xFF00407F, [](SkCanvas*, SkPaint* paint) {
1314 paint->setColor4f({0.99608f, 0.50196f, 0.0f, 1.0f});
1315 });
1316 }
1317
DEF_TEST(SkRuntimeStructNameReuse,r)1318 DEF_TEST(SkRuntimeStructNameReuse, r) {
1319 test_RuntimeEffectStructNameReuse(r, nullptr);
1320 }
1321
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)1322 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU,
1323 r,
1324 ctxInfo,
1325 CtsEnforcement::kApiLevel_T) {
1326 test_RuntimeEffectStructNameReuse(r, ctxInfo.directContext());
1327 }
1328
DEF_TEST(SkRuntimeColorFilterFlags,r)1329 DEF_TEST(SkRuntimeColorFilterFlags, r) {
1330 { // Here's a non-trivial filter that doesn't change alpha.
1331 auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{
1332 "half4 main(half4 color) { return color + half4(1,1,1,0); }"});
1333 REPORTER_ASSERT(r, effect && err.isEmpty());
1334 sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
1335 REPORTER_ASSERT(r, filter && filter->isAlphaUnchanged());
1336 }
1337
1338 { // Here's one that definitely changes alpha.
1339 auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{
1340 "half4 main(half4 color) { return color + half4(0,0,0,4); }"});
1341 REPORTER_ASSERT(r, effect && err.isEmpty());
1342 sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
1343 REPORTER_ASSERT(r, filter && !filter->isAlphaUnchanged());
1344 }
1345 }
1346
DEF_TEST(SkRuntimeShaderSampleCoords,r)1347 DEF_TEST(SkRuntimeShaderSampleCoords, r) {
1348 // This test verifies that we detect calls to sample where the coords are the same as those
1349 // passed to main. In those cases, it's safe to turn the "explicit" sampling into "passthrough"
1350 // sampling. This optimization is implemented very conservatively.
1351 //
1352 // It also checks that we correctly set the "referencesSampleCoords" bit on the runtime effect
1353 // FP, depending on how the coords parameter to main is used.
1354
1355 auto test = [&](const char* src, bool expectExplicit, bool expectReferencesSampleCoords) {
1356 auto [effect, err] =
1357 SkRuntimeEffect::MakeForShader(SkStringPrintf("uniform shader child; %s", src));
1358 REPORTER_ASSERT(r, effect);
1359
1360 auto child = GrFragmentProcessor::MakeColor({ 1, 1, 1, 1 });
1361 auto fp = GrSkSLFP::Make(effect.get(), "test_fp", /*inputFP=*/nullptr,
1362 GrSkSLFP::OptFlags::kNone, "child", std::move(child));
1363 REPORTER_ASSERT(r, fp);
1364
1365 REPORTER_ASSERT(r, fp->childProcessor(0)->sampleUsage().isExplicit() == expectExplicit);
1366 REPORTER_ASSERT(r, fp->usesSampleCoords() == expectReferencesSampleCoords);
1367 };
1368
1369 // Cases where our optimization is valid, and works:
1370
1371 // Direct use of passed-in coords. Here, the only use of sample coords is for a sample call
1372 // converted to passthrough, so referenceSampleCoords is *false*, despite appearing in main.
1373 test("half4 main(float2 xy) { return child.eval(xy); }", false, false);
1374 // Sample with passed-in coords, read (but don't write) sample coords elsewhere
1375 test("half4 main(float2 xy) { return child.eval(xy) + sin(xy.x); }", false, true);
1376
1377 // Cases where our optimization is not valid, and does not happen:
1378
1379 // Sampling with values completely unrelated to passed-in coords
1380 test("half4 main(float2 xy) { return child.eval(float2(0, 0)); }", true, false);
1381 // Use of expression involving passed in coords
1382 test("half4 main(float2 xy) { return child.eval(xy * 0.5); }", true, true);
1383 // Use of coords after modification
1384 test("half4 main(float2 xy) { xy *= 2; return child.eval(xy); }", true, true);
1385 // Use of coords after modification via out-param call
1386 test("void adjust(inout float2 xy) { xy *= 2; }"
1387 "half4 main(float2 xy) { adjust(xy); return child.eval(xy); }", true, true);
1388
1389 // There should (must) not be any false-positive cases. There are false-negatives.
1390 // In all of these cases, our optimization would be valid, but does not happen:
1391
1392 // Direct use of passed-in coords, modified after use
1393 test("half4 main(float2 xy) { half4 c = child.eval(xy); xy *= 2; return c; }", true, true);
1394 // Passed-in coords copied to a temp variable
1395 test("half4 main(float2 xy) { float2 p = xy; return child.eval(p); }", true, true);
1396 // Use of coords passed to helper function
1397 test("half4 helper(float2 xy) { return child.eval(xy); }"
1398 "half4 main(float2 xy) { return helper(xy); }", true, true);
1399 }
1400
DEF_TEST(SkRuntimeShaderIsOpaque,r)1401 DEF_TEST(SkRuntimeShaderIsOpaque, r) {
1402 // This test verifies that we detect certain simple patterns in runtime shaders, and can deduce
1403 // (via code in SkSL::Analysis::ReturnsOpaqueColor) that the resulting shader is always opaque.
1404 // That logic is conservative, and the tests below reflect this.
1405
1406 auto test = [&](const char* body, bool expectOpaque) {
1407 auto [effect, err] = SkRuntimeEffect::MakeForShader(SkStringPrintf(R"(
1408 uniform shader cOnes;
1409 uniform shader cZeros;
1410 uniform float4 uOnes;
1411 uniform float4 uZeros;
1412 half4 main(float2 xy) {
1413 %s
1414 })", body));
1415 REPORTER_ASSERT(r, effect);
1416
1417 auto cOnes = SkShaders::Color(SK_ColorWHITE);
1418 auto cZeros = SkShaders::Color(SK_ColorTRANSPARENT);
1419 SkASSERT(cOnes->isOpaque());
1420 SkASSERT(!cZeros->isOpaque());
1421
1422 SkRuntimeShaderBuilder builder(effect);
1423 builder.child("cOnes") = std::move(cOnes);
1424 builder.child("cZeros") = std::move(cZeros);
1425 builder.uniform("uOnes") = SkColors::kWhite;
1426 builder.uniform("uZeros") = SkColors::kTransparent;
1427
1428 auto shader = builder.makeShader();
1429 REPORTER_ASSERT(r, shader->isOpaque() == expectOpaque);
1430 };
1431
1432 // Cases where our optimization is valid, and works:
1433
1434 // Returning opaque literals
1435 test("return half4(1);", true);
1436 test("return half4(0, 1, 0, 1);", true);
1437 test("return half4(0, 0, 0, 1);", true);
1438
1439 // Simple expressions involving uniforms
1440 test("return uZeros.rgb1;", true);
1441 test("return uZeros.bgra.rgb1;", true);
1442 test("return half4(uZeros.rgb, 1);", true);
1443
1444 // Simple expressions involving child.eval
1445 test("return cZeros.eval(xy).rgb1;", true);
1446 test("return cZeros.eval(xy).bgra.rgb1;", true);
1447 test("return half4(cZeros.eval(xy).rgb, 1);", true);
1448
1449 // Multiple returns
1450 test("if (xy.x < 100) { return uZeros.rgb1; } else { return cZeros.eval(xy).rgb1; }", true);
1451
1452 // More expression cases:
1453 test("return (cZeros.eval(xy) * uZeros).rgb1;", true);
1454 test("return half4(1, 1, 1, 0.5 + 0.5);", true);
1455
1456 // Constant variable propagation
1457 test("const half4 kWhite = half4(1); return kWhite;", true);
1458
1459 // Cases where our optimization is not valid, and does not happen:
1460
1461 // Returning non-opaque literals
1462 test("return half4(0);", false);
1463 test("return half4(1, 1, 1, 0);", false);
1464
1465 // Returning non-opaque uniforms or children
1466 test("return uZeros;", false);
1467 test("return cZeros.eval(xy);", false);
1468
1469 // Multiple returns
1470 test("if (xy.x < 100) { return uZeros; } else { return cZeros.eval(xy).rgb1; }", false);
1471 test("if (xy.x < 100) { return uZeros.rgb1; } else { return cZeros.eval(xy); }", false);
1472
1473 // There should (must) not be any false-positive cases. There are false-negatives.
1474 // In these cases, our optimization would be valid, but does not happen:
1475
1476 // More complex expressions that can't be simplified
1477 test("return xy.x < 100 ? uZeros.rgb1 : cZeros.eval(xy).rgb1;", false);
1478
1479 // Finally, there are cases that are conditional on the uniforms and children. These *could*
1480 // determine dynamically if the uniform and/or child being referenced is opaque, and use that
1481 // information. Today, we don't do this, so we pessimistically assume they're transparent:
1482 test("return uOnes;", false);
1483 test("return cOnes.eval(xy);", false);
1484 }
1485
DEF_GANESH_TEST_FOR_ALL_CONTEXTS(GrSkSLFP_Specialized,r,ctxInfo,CtsEnforcement::kApiLevel_T)1486 DEF_GANESH_TEST_FOR_ALL_CONTEXTS(GrSkSLFP_Specialized, r, ctxInfo, CtsEnforcement::kApiLevel_T) {
1487 struct FpAndKey {
1488 std::unique_ptr<GrFragmentProcessor> fp;
1489 SkTArray<uint32_t, true> key;
1490 };
1491
1492 // Constant color, but with an 'specialize' option that decides if the color is inserted in the
1493 // SkSL as a literal, or left as a uniform
1494 auto make_color_fp = [&](SkPMColor4f color, bool specialize) {
1495 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
1496 "uniform half4 color;"
1497 "half4 main(float2 xy) { return color; }"
1498 );
1499 FpAndKey result;
1500 result.fp = GrSkSLFP::Make(effect, "color_fp", /*inputFP=*/nullptr,
1501 GrSkSLFP::OptFlags::kNone,
1502 "color", GrSkSLFP::SpecializeIf(specialize, color));
1503 skgpu::KeyBuilder builder(&result.key);
1504 result.fp->addToKey(*ctxInfo.directContext()->priv().caps()->shaderCaps(), &builder);
1505 builder.flush();
1506 return result;
1507 };
1508
1509 FpAndKey uRed = make_color_fp({1, 0, 0, 1}, false),
1510 uGreen = make_color_fp({0, 1, 0, 1}, false),
1511 sRed = make_color_fp({1, 0, 0, 1}, true),
1512 sGreen = make_color_fp({0, 1, 0, 1}, true);
1513
1514 // uRed and uGreen should have the same key - they just have different uniforms
1515 SkASSERT(uRed.key == uGreen.key);
1516 // sRed and sGreen should have keys that are different from the uniform case, and each other
1517 SkASSERT(sRed.key != uRed.key);
1518 SkASSERT(sGreen.key != uRed.key);
1519 SkASSERT(sRed.key != sGreen.key);
1520 }
1521
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(GrSkSLFP_UniformArray,r,ctxInfo,CtsEnforcement::kApiLevel_T)1522 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(GrSkSLFP_UniformArray,
1523 r,
1524 ctxInfo,
1525 CtsEnforcement::kApiLevel_T) {
1526 // Make a fill-context to draw into.
1527 GrDirectContext* directContext = ctxInfo.directContext();
1528 SkImageInfo info = SkImageInfo::Make(1, 1, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
1529 std::unique_ptr<skgpu::v1::SurfaceFillContext> testCtx =
1530 directContext->priv().makeSFC(info, /*label=*/{}, SkBackingFit::kExact);
1531
1532 // Make an effect that takes a uniform array as input.
1533 static constexpr std::array<float, 4> kRed {1.0f, 0.0f, 0.0f, 1.0f};
1534 static constexpr std::array<float, 4> kGreen{0.0f, 1.0f, 0.0f, 1.0f};
1535 static constexpr std::array<float, 4> kBlue {0.0f, 0.0f, 1.0f, 1.0f};
1536 static constexpr std::array<float, 4> kGray {0.499f, 0.499f, 0.499f, 1.0f};
1537
1538 for (const auto& colorArray : {kRed, kGreen, kBlue, kGray}) {
1539 // Compile our runtime effect.
1540 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
1541 "uniform half color[4];"
1542 "half4 main(float2 xy) { return half4(color[0], color[1], color[2], color[3]); }"
1543 );
1544 // Render our shader into the fill-context with our various input colors.
1545 testCtx->fillWithFP(GrSkSLFP::Make(effect, "test_fp", /*inputFP=*/nullptr,
1546 GrSkSLFP::OptFlags::kNone,
1547 "color", SkSpan(colorArray)));
1548 // Read our color back and ensure it matches.
1549 GrColor actual;
1550 GrPixmap pixmap(info, &actual, sizeof(GrColor));
1551 if (!testCtx->readPixels(directContext, pixmap, /*srcPt=*/{0, 0})) {
1552 REPORT_FAILURE(r, "readPixels", SkString("readPixels failed"));
1553 break;
1554 }
1555 if (actual != GrColorPackRGBA(255 * colorArray[0], 255 * colorArray[1],
1556 255 * colorArray[2], 255 * colorArray[3])) {
1557 REPORT_FAILURE(r, "Uniform array didn't match expectations",
1558 SkStringPrintf("\n"
1559 "Expected: [ %g %g %g %g ]\n"
1560 "Got : [ %08x ]\n",
1561 colorArray[0], colorArray[1],
1562 colorArray[2], colorArray[3],
1563 actual));
1564 break;
1565 }
1566 }
1567 }
1568