blob: 713c3f00e563fefc09fa1be8362ec493601acfce [file] [log] [blame]
Mike Reed3fd3cc92019-06-20 12:40:30 -04001/*
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 "gm/gm.h"
Kevin Lubick677a12f2022-03-09 08:23:14 -05009#include "include/core/SkBitmap.h"
Mike Reed3fd3cc92019-06-20 12:40:30 -040010#include "include/core/SkCanvas.h"
Mike Reed3fd3cc92019-06-20 12:40:30 -040011#include "include/core/SkData.h"
Mike Reed3fd3cc92019-06-20 12:40:30 -040012#include "include/core/SkPaint.h"
Chris Dalton224e5e42021-04-16 11:43:39 -060013#include "include/core/SkRRect.h"
Mike Reed3fd3cc92019-06-20 12:40:30 -040014#include "include/core/SkSize.h"
15#include "include/core/SkString.h"
Brian Osman44fafa62020-07-15 10:52:37 -040016#include "include/core/SkSurface.h"
17#include "include/effects/SkGradientShader.h"
Mike Reed146722e2020-02-13 12:36:28 -050018#include "include/effects/SkImageFilters.h"
Brian Osmanee426f22020-01-02 11:55:24 -050019#include "include/effects/SkRuntimeEffect.h"
Brian Osman1c5cc632023-03-01 16:41:32 -050020#include "include/gpu/GrRecordingContext.h"
Kevin Lubick0d4d1142023-02-13 09:13:10 -050021#include "src/base/SkRandom.h"
Brian Osman2f2977e2021-12-07 16:05:39 -050022#include "src/core/SkColorSpacePriv.h"
Brian Osman529fb1e2023-03-08 10:13:39 -050023#include "src/core/SkRuntimeEffectPriv.h"
Kevin Lubick8b741882023-10-06 11:41:38 -040024#include "tools/DecodeUtils.h"
Mike Reed146722e2020-02-13 12:36:28 -050025#include "tools/Resources.h"
Brian Osman048b59f2023-09-15 16:31:13 -040026#include "tools/ToolUtils.h"
Mike Reed3fd3cc92019-06-20 12:40:30 -040027
Brian Osman44fafa62020-07-15 10:52:37 -040028enum RT_Flags {
Brian Osman6285d642021-05-05 08:24:03 -040029 kAnimate_RTFlag = 0x1,
30 kBench_RTFlag = 0x2,
31 kColorFilter_RTFlag = 0x4,
Brian Osman44fafa62020-07-15 10:52:37 -040032};
Mike Reed3fd3cc92019-06-20 12:40:30 -040033
Brian Osman44fafa62020-07-15 10:52:37 -040034class RuntimeShaderGM : public skiagm::GM {
35public:
36 RuntimeShaderGM(const char* name, SkISize size, const char* sksl, uint32_t flags = 0)
37 : fName(name), fSize(size), fFlags(flags), fSkSL(sksl) {}
38
39 void onOnceBeforeDraw() override {
Brian Osman6285d642021-05-05 08:24:03 -040040 auto [effect, error] = (fFlags & kColorFilter_RTFlag)
41 ? SkRuntimeEffect::MakeForColorFilter(fSkSL)
42 : SkRuntimeEffect::MakeForShader(fSkSL);
Brian Osman44fafa62020-07-15 10:52:37 -040043 if (!effect) {
44 SkDebugf("RuntimeShader error: %s\n", error.c_str());
45 }
46 fEffect = std::move(effect);
Mike Reed3fd3cc92019-06-20 12:40:30 -040047 }
Mike Reed3fd3cc92019-06-20 12:40:30 -040048
Brian Osman44fafa62020-07-15 10:52:37 -040049 bool runAsBench() const override { return SkToBool(fFlags & kBench_RTFlag); }
Leandro Lovisolo24fa2112023-08-15 19:05:17 +000050 SkString getName() const override { return fName; }
Leandro Lovisolo8f023882023-08-15 21:13:52 +000051 SkISize getISize() override { return fSize; }
Mike Reed3fd3cc92019-06-20 12:40:30 -040052
Brian Osman44fafa62020-07-15 10:52:37 -040053 bool onAnimate(double nanos) override {
54 fSecs = nanos / (1000 * 1000 * 1000);
55 return SkToBool(fFlags & kAnimate_RTFlag);
56 }
Mike Reed3fd3cc92019-06-20 12:40:30 -040057
Brian Osman44fafa62020-07-15 10:52:37 -040058protected:
59 SkString fName;
60 SkISize fSize;
61 uint32_t fFlags;
62 float fSecs = 0.0f;
63
64 SkString fSkSL;
65 sk_sp<SkRuntimeEffect> fEffect;
66};
67
68class SimpleRT : public RuntimeShaderGM {
69public:
70 SimpleRT() : RuntimeShaderGM("runtime_shader", {512, 256}, R"(
71 uniform half4 gColor;
72
Brian Osman767f4442020-08-13 16:59:48 -040073 half4 main(float2 p) {
Brian Osmanb25e6e12020-09-14 14:44:42 -040074 return half4(p*(1.0/255), gColor.b, 1);
Brian Osman44fafa62020-07-15 10:52:37 -040075 }
76 )", kBench_RTFlag) {}
Mike Reed3fd3cc92019-06-20 12:40:30 -040077
Mike Reed3fd3cc92019-06-20 12:40:30 -040078 void onDraw(SkCanvas* canvas) override {
Brian Osman44fafa62020-07-15 10:52:37 -040079 SkRuntimeShaderBuilder builder(fEffect);
Brian Osman93de1622019-12-26 08:43:05 -050080
81 SkMatrix localM;
82 localM.setRotate(90, 128, 128);
Brian Osmana4b91692020-08-10 14:26:16 -040083 builder.uniform("gColor") = SkColor4f{1, 0, 0, 1};
Brian Osman93de1622019-12-26 08:43:05 -050084
Mike Reed3fd3cc92019-06-20 12:40:30 -040085 SkPaint p;
Brian Osmancd189e82022-02-09 11:56:45 -050086 p.setShader(builder.makeShader(&localM));
Mike Reed3fd3cc92019-06-20 12:40:30 -040087 canvas->drawRect({0, 0, 256, 256}, p);
88 }
Mike Reed3fd3cc92019-06-20 12:40:30 -040089};
Brian Osman44fafa62020-07-15 10:52:37 -040090DEF_GM(return new SimpleRT;)
Mike Reed146722e2020-02-13 12:36:28 -050091
92static sk_sp<SkShader> make_shader(sk_sp<SkImage> img, SkISize size) {
Mike Reed1f607332020-05-21 12:11:27 -040093 SkMatrix scale = SkMatrix::Scale(size.width() / (float)img->width(),
94 size.height() / (float)img->height());
Mike Reed41068192020-12-09 21:48:52 -050095 return img->makeShader(SkSamplingOptions(), scale);
Mike Reed146722e2020-02-13 12:36:28 -050096}
97
Mike Reed146722e2020-02-13 12:36:28 -050098static sk_sp<SkShader> make_threshold(SkISize size) {
99 auto info = SkImageInfo::Make(size.width(), size.height(), kAlpha_8_SkColorType,
100 kPremul_SkAlphaType);
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400101 auto surf = SkSurfaces::Raster(info);
Mike Reed146722e2020-02-13 12:36:28 -0500102 auto canvas = surf->getCanvas();
103
104 const SkScalar rad = 50;
105 SkColor colors[] = {SK_ColorBLACK, 0};
106 SkPaint paint;
107 paint.setAntiAlias(true);
108 paint.setShader(SkGradientShader::MakeRadial({0,0}, rad, colors, nullptr, 2, SkTileMode::kClamp));
109
110 SkPaint layerPaint;
111 const SkScalar sigma = 16.0f;
112 layerPaint.setImageFilter(SkImageFilters::Blur(sigma, sigma, nullptr));
113 canvas->saveLayer(nullptr, &layerPaint);
114
115 SkRandom rand;
116 for (int i = 0; i < 25; ++i) {
117 SkScalar x = rand.nextF() * size.width();
118 SkScalar y = rand.nextF() * size.height();
119 canvas->save();
120 canvas->translate(x, y);
121 canvas->drawCircle(0, 0, rad, paint);
122 canvas->restore();
123 }
124
125 canvas->restore(); // apply the blur
126
Mike Reed41068192020-12-09 21:48:52 -0500127 return surf->makeImageSnapshot()->makeShader(SkSamplingOptions());
Mike Reed146722e2020-02-13 12:36:28 -0500128}
129
Brian Osman44fafa62020-07-15 10:52:37 -0400130class ThresholdRT : public RuntimeShaderGM {
131public:
132 ThresholdRT() : RuntimeShaderGM("threshold_rt", {256, 256}, R"(
Brian Osman91292e92020-11-04 15:40:50 -0500133 uniform shader before_map;
134 uniform shader after_map;
135 uniform shader threshold_map;
Mike Reed146722e2020-02-13 12:36:28 -0500136
Brian Osman44fafa62020-07-15 10:52:37 -0400137 uniform float cutoff;
138 uniform float slope;
139
140 float smooth_cutoff(float x) {
141 x = x * slope + (0.5 - slope * cutoff);
142 return clamp(x, 0, 1);
143 }
144
Brian Osman767f4442020-08-13 16:59:48 -0400145 half4 main(float2 xy) {
Brian Osmancbfa34a2021-09-02 09:26:27 -0400146 half4 before = before_map.eval(xy);
147 half4 after = after_map.eval(xy);
Brian Osman44fafa62020-07-15 10:52:37 -0400148
Brian Osmancbfa34a2021-09-02 09:26:27 -0400149 float m = smooth_cutoff(threshold_map.eval(xy).a);
Brian Osmanb25e6e12020-09-14 14:44:42 -0400150 return mix(before, after, m);
Brian Osman44fafa62020-07-15 10:52:37 -0400151 }
152 )", kAnimate_RTFlag | kBench_RTFlag) {}
153
154 sk_sp<SkShader> fBefore, fAfter, fThreshold;
Mike Reed146722e2020-02-13 12:36:28 -0500155
156 void onOnceBeforeDraw() override {
157 const SkISize size = {256, 256};
158 fThreshold = make_threshold(size);
Kevin Lubick8b741882023-10-06 11:41:38 -0400159 fBefore = make_shader(ToolUtils::GetResourceAsImage("images/mandrill_256.png"), size);
160 fAfter = make_shader(ToolUtils::GetResourceAsImage("images/dog.jpg"), size);
Mike Reed146722e2020-02-13 12:36:28 -0500161
Brian Osman44fafa62020-07-15 10:52:37 -0400162 this->RuntimeShaderGM::onOnceBeforeDraw();
Mike Reed146722e2020-02-13 12:36:28 -0500163 }
164
Mike Kleinf8d68fe2020-06-18 10:01:31 -0500165 void onDraw(SkCanvas* canvas) override {
Brian Osman44fafa62020-07-15 10:52:37 -0400166 SkRuntimeShaderBuilder builder(fEffect);
167
Kevin Lubickc69d9992023-02-15 08:04:24 -0500168 builder.uniform("cutoff") = sinf(fSecs) * 0.55f + 0.5f;
Brian Osmana4b91692020-08-10 14:26:16 -0400169 builder.uniform("slope") = 10.0f;
Brian Osman44fafa62020-07-15 10:52:37 -0400170
171 builder.child("before_map") = fBefore;
172 builder.child("after_map") = fAfter;
173 builder.child("threshold_map") = fThreshold;
Mike Reed146722e2020-02-13 12:36:28 -0500174
175 SkPaint paint;
Brian Osmancd189e82022-02-09 11:56:45 -0500176 paint.setShader(builder.makeShader());
Mike Reed146722e2020-02-13 12:36:28 -0500177 canvas->drawRect({0, 0, 256, 256}, paint);
178
179 auto draw = [&](SkScalar x, SkScalar y, sk_sp<SkShader> shader) {
180 paint.setShader(shader);
181 canvas->save();
182 canvas->translate(x, y);
183 canvas->drawRect({0, 0, 256, 256}, paint);
184 canvas->restore();
185 };
186 draw(256, 0, fThreshold);
187 draw( 0, 256, fBefore);
188 draw(256, 256, fAfter);
Mike Reed146722e2020-02-13 12:36:28 -0500189 }
Mike Reed146722e2020-02-13 12:36:28 -0500190};
191DEF_GM(return new ThresholdRT;)
Mike Reed8520e762020-04-30 12:06:23 -0400192
Brian Osman44fafa62020-07-15 10:52:37 -0400193class SpiralRT : public RuntimeShaderGM {
194public:
195 SpiralRT() : RuntimeShaderGM("spiral_rt", {512, 512}, R"(
196 uniform float rad_scale;
197 uniform float2 in_center;
Brian Osman8c3d1832021-12-06 10:30:51 -0500198 layout(color) uniform float4 in_colors0;
199 layout(color) uniform float4 in_colors1;
Mike Reed8520e762020-04-30 12:06:23 -0400200
Brian Osman767f4442020-08-13 16:59:48 -0400201 half4 main(float2 p) {
Brian Osman44fafa62020-07-15 10:52:37 -0400202 float2 pp = p - in_center;
203 float radius = length(pp);
204 radius = sqrt(radius);
205 float angle = atan(pp.y / pp.x);
206 float t = (angle + 3.1415926/2) / (3.1415926);
207 t += radius * rad_scale;
208 t = fract(t);
Brian Osmanb25e6e12020-09-14 14:44:42 -0400209 return in_colors0 * (1-t) + in_colors1 * t;
Mike Reed8520e762020-04-30 12:06:23 -0400210 }
Brian Osman44fafa62020-07-15 10:52:37 -0400211 )", kAnimate_RTFlag | kBench_RTFlag) {}
Mike Reed8520e762020-04-30 12:06:23 -0400212
213 void onDraw(SkCanvas* canvas) override {
Brian Osman44fafa62020-07-15 10:52:37 -0400214 SkRuntimeShaderBuilder builder(fEffect);
215
Brian Osmana4b91692020-08-10 14:26:16 -0400216 builder.uniform("rad_scale") = std::sin(fSecs * 0.5f + 2.0f) / 5;
217 builder.uniform("in_center") = SkV2{256, 256};
Brian Osman8c3d1832021-12-06 10:30:51 -0500218 builder.uniform("in_colors0") = SkColors::kRed;
219 builder.uniform("in_colors1") = SkColors::kGreen;
Mike Reed8520e762020-04-30 12:06:23 -0400220
221 SkPaint paint;
Brian Osmancd189e82022-02-09 11:56:45 -0500222 paint.setShader(builder.makeShader());
Mike Reed8520e762020-04-30 12:06:23 -0400223 canvas->drawRect({0, 0, 512, 512}, paint);
224 }
Mike Reed8520e762020-04-30 12:06:23 -0400225};
226DEF_GM(return new SpiralRT;)
Brian Osman9c3eccd2020-05-21 16:41:43 -0400227
Brian Osman827dab42021-04-26 17:02:57 -0400228// Test case for sampling with both unmodified input coordinates, and explicit coordinates.
229// The first version of skbug.com/11869 suffered a bug where all samples of a child were treated
230// as pass-through if *at least one* used the unmodified coordinates. This was detected & tracked
231// in b/181092919. This GM is similar, and demonstrates the bug before the fix was applied.
232class UnsharpRT : public RuntimeShaderGM {
233public:
234 UnsharpRT() : RuntimeShaderGM("unsharp_rt", {512, 256}, R"(
John Stiles67f443b2021-09-30 12:45:36 -0400235 uniform shader child;
Brian Osman827dab42021-04-26 17:02:57 -0400236 half4 main(float2 xy) {
John Stiles67f443b2021-09-30 12:45:36 -0400237 half4 c = child.eval(xy) * 5;
238 c -= child.eval(xy + float2( 1, 0));
239 c -= child.eval(xy + float2(-1, 0));
240 c -= child.eval(xy + float2( 0, 1));
241 c -= child.eval(xy + float2( 0, -1));
Brian Osman827dab42021-04-26 17:02:57 -0400242 return c;
243 }
244 )") {}
245
246 sk_sp<SkImage> fMandrill;
247
248 void onOnceBeforeDraw() override {
Kevin Lubick8b741882023-10-06 11:41:38 -0400249 fMandrill = ToolUtils::GetResourceAsImage("images/mandrill_256.png");
Brian Osman827dab42021-04-26 17:02:57 -0400250 this->RuntimeShaderGM::onOnceBeforeDraw();
251 }
252
253 void onDraw(SkCanvas* canvas) override {
254 // First we draw the unmodified image
255 canvas->drawImage(fMandrill, 0, 0);
256
257 // Now draw the image with our unsharp mask applied
258 SkRuntimeShaderBuilder builder(fEffect);
259 const SkSamplingOptions sampling(SkFilterMode::kNearest);
John Stiles67f443b2021-09-30 12:45:36 -0400260 builder.child("child") = fMandrill->makeShader(sampling);
Brian Osman827dab42021-04-26 17:02:57 -0400261
262 SkPaint paint;
Brian Osmancd189e82022-02-09 11:56:45 -0500263 paint.setShader(builder.makeShader());
Brian Osman827dab42021-04-26 17:02:57 -0400264 canvas->translate(256, 0);
265 canvas->drawRect({ 0, 0, 256, 256 }, paint);
266 }
267};
268DEF_GM(return new UnsharpRT;)
269
Brian Osman44fafa62020-07-15 10:52:37 -0400270class ColorCubeRT : public RuntimeShaderGM {
271public:
272 ColorCubeRT() : RuntimeShaderGM("color_cube_rt", {512, 512}, R"(
John Stiles67f443b2021-09-30 12:45:36 -0400273 uniform shader child;
Brian Osman91292e92020-11-04 15:40:50 -0500274 uniform shader color_cube;
Brian Osman44fafa62020-07-15 10:52:37 -0400275
276 uniform float rg_scale;
277 uniform float rg_bias;
278 uniform float b_scale;
279 uniform float inv_size;
280
Brian Osman767f4442020-08-13 16:59:48 -0400281 half4 main(float2 xy) {
John Stiles67f443b2021-09-30 12:45:36 -0400282 float4 c = unpremul(child.eval(xy));
Brian Osman44fafa62020-07-15 10:52:37 -0400283
284 // Map to cube coords:
285 float3 cubeCoords = float3(c.rg * rg_scale + rg_bias, c.b * b_scale);
286
287 // Compute slice coordinate
288 float2 coords1 = float2((floor(cubeCoords.b) + cubeCoords.r) * inv_size, cubeCoords.g);
289 float2 coords2 = float2(( ceil(cubeCoords.b) + cubeCoords.r) * inv_size, cubeCoords.g);
290
291 // Two bilinear fetches, plus a manual lerp for the third axis:
Brian Osmancbfa34a2021-09-02 09:26:27 -0400292 half4 color = mix(color_cube.eval(coords1), color_cube.eval(coords2),
Brian Osmanb25e6e12020-09-14 14:44:42 -0400293 fract(cubeCoords.b));
Brian Osman44fafa62020-07-15 10:52:37 -0400294
295 // Premul again
296 color.rgb *= color.a;
Brian Osman767f4442020-08-13 16:59:48 -0400297
298 return color;
Brian Osman44fafa62020-07-15 10:52:37 -0400299 }
300 )") {}
301
Brian Osman9c3eccd2020-05-21 16:41:43 -0400302 sk_sp<SkImage> fMandrill, fMandrillSepia, fIdentityCube, fSepiaCube;
Brian Osman9c3eccd2020-05-21 16:41:43 -0400303
304 void onOnceBeforeDraw() override {
Kevin Lubick8b741882023-10-06 11:41:38 -0400305 fMandrill = ToolUtils::GetResourceAsImage("images/mandrill_256.png");
306 fMandrillSepia = ToolUtils::GetResourceAsImage("images/mandrill_sepia.png");
307 fIdentityCube = ToolUtils::GetResourceAsImage("images/lut_identity.png");
308 fSepiaCube = ToolUtils::GetResourceAsImage("images/lut_sepia.png");
Brian Osman9c3eccd2020-05-21 16:41:43 -0400309
Brian Osman44fafa62020-07-15 10:52:37 -0400310 this->RuntimeShaderGM::onOnceBeforeDraw();
Brian Osman9c3eccd2020-05-21 16:41:43 -0400311 }
312
Brian Osman89bf7342020-06-18 17:11:16 -0400313 void onDraw(SkCanvas* canvas) override {
Brian Osman44fafa62020-07-15 10:52:37 -0400314 SkRuntimeShaderBuilder builder(fEffect);
315
Brian Osman9c3eccd2020-05-21 16:41:43 -0400316 // First we draw the unmodified image, and a copy that was sepia-toned in Photoshop:
317 canvas->drawImage(fMandrill, 0, 0);
318 canvas->drawImage(fMandrillSepia, 0, 256);
319
320 // LUT dimensions should be (kSize^2, kSize)
321 constexpr float kSize = 16.0f;
322
Mike Reed5ec22382021-01-14 21:59:01 -0500323 const SkSamplingOptions sampling(SkFilterMode::kLinear);
Mike Reed41068192020-12-09 21:48:52 -0500324
Brian Osmana4b91692020-08-10 14:26:16 -0400325 builder.uniform("rg_scale") = (kSize - 1) / kSize;
326 builder.uniform("rg_bias") = 0.5f / kSize;
327 builder.uniform("b_scale") = kSize - 1;
328 builder.uniform("inv_size") = 1.0f / kSize;
Brian Osman2c28bf92020-05-28 13:38:24 -0400329
John Stiles67f443b2021-09-30 12:45:36 -0400330 builder.child("child") = fMandrill->makeShader(sampling);
Brian Osman9c3eccd2020-05-21 16:41:43 -0400331
Brian Osman9c3eccd2020-05-21 16:41:43 -0400332 SkPaint paint;
Brian Osman9c3eccd2020-05-21 16:41:43 -0400333
Brian Osman2c28bf92020-05-28 13:38:24 -0400334 // TODO: Should we add SkImage::makeNormalizedShader() to handle this automatically?
335 SkMatrix normalize = SkMatrix::Scale(1.0f / (kSize * kSize), 1.0f / kSize);
336
Brian Osman9c3eccd2020-05-21 16:41:43 -0400337 // Now draw the image with an identity color cube - it should look like the original
Mike Reed41068192020-12-09 21:48:52 -0500338 builder.child("color_cube") = fIdentityCube->makeShader(sampling, normalize);
Brian Osmancd189e82022-02-09 11:56:45 -0500339 paint.setShader(builder.makeShader());
Brian Osman9c3eccd2020-05-21 16:41:43 -0400340 canvas->translate(256, 0);
341 canvas->drawRect({ 0, 0, 256, 256 }, paint);
342
343 // ... and with a sepia-tone color cube. This should match the sepia-toned image.
Mike Reed41068192020-12-09 21:48:52 -0500344 builder.child("color_cube") = fSepiaCube->makeShader(sampling, normalize);
Brian Osmancd189e82022-02-09 11:56:45 -0500345 paint.setShader(builder.makeShader());
Brian Osman9c3eccd2020-05-21 16:41:43 -0400346 canvas->translate(0, 256);
347 canvas->drawRect({ 0, 0, 256, 256 }, paint);
Brian Osman9c3eccd2020-05-21 16:41:43 -0400348 }
349};
350DEF_GM(return new ColorCubeRT;)
Brian Osmana7685b22020-07-10 14:08:56 -0400351
Brian Osman6285d642021-05-05 08:24:03 -0400352// Same as above, but demonstrating how to implement this as a runtime color filter (that samples
353// a shader child for the LUT).
354class ColorCubeColorFilterRT : public RuntimeShaderGM {
355public:
356 ColorCubeColorFilterRT() : RuntimeShaderGM("color_cube_cf_rt", {512, 512}, R"(
357 uniform shader color_cube;
358
359 uniform float rg_scale;
360 uniform float rg_bias;
361 uniform float b_scale;
362 uniform float inv_size;
363
364 half4 main(half4 inColor) {
365 float4 c = unpremul(inColor);
366
367 // Map to cube coords:
368 float3 cubeCoords = float3(c.rg * rg_scale + rg_bias, c.b * b_scale);
369
370 // Compute slice coordinate
371 float2 coords1 = float2((floor(cubeCoords.b) + cubeCoords.r) * inv_size, cubeCoords.g);
372 float2 coords2 = float2(( ceil(cubeCoords.b) + cubeCoords.r) * inv_size, cubeCoords.g);
373
374 // Two bilinear fetches, plus a manual lerp for the third axis:
Brian Osmancbfa34a2021-09-02 09:26:27 -0400375 half4 color = mix(color_cube.eval(coords1), color_cube.eval(coords2),
Brian Osman6285d642021-05-05 08:24:03 -0400376 fract(cubeCoords.b));
377
378 // Premul again
379 color.rgb *= color.a;
380
381 return color;
382 }
383 )", kColorFilter_RTFlag) {}
384
385 sk_sp<SkImage> fMandrill, fMandrillSepia, fIdentityCube, fSepiaCube;
386
387 void onOnceBeforeDraw() override {
Kevin Lubick8b741882023-10-06 11:41:38 -0400388 fMandrill = ToolUtils::GetResourceAsImage("images/mandrill_256.png");
389 fMandrillSepia = ToolUtils::GetResourceAsImage("images/mandrill_sepia.png");
390 fIdentityCube = ToolUtils::GetResourceAsImage("images/lut_identity.png");
391 fSepiaCube = ToolUtils::GetResourceAsImage("images/lut_sepia.png");
Brian Osman6285d642021-05-05 08:24:03 -0400392
393 this->RuntimeShaderGM::onOnceBeforeDraw();
394 }
395
396 void onDraw(SkCanvas* canvas) override {
John Stilesa4079ec2023-02-02 17:54:12 -0500397 SkRuntimeColorFilterBuilder builder(fEffect);
398
Brian Osman6285d642021-05-05 08:24:03 -0400399 // First we draw the unmodified image, and a copy that was sepia-toned in Photoshop:
400 canvas->drawImage(fMandrill, 0, 0);
401 canvas->drawImage(fMandrillSepia, 0, 256);
402
403 // LUT dimensions should be (kSize^2, kSize)
404 constexpr float kSize = 16.0f;
405
406 const SkSamplingOptions sampling(SkFilterMode::kLinear);
407
John Stilesa4079ec2023-02-02 17:54:12 -0500408 builder.uniform("rg_scale") = (kSize - 1) / kSize;
409 builder.uniform("rg_bias") = 0.5f / kSize;
410 builder.uniform("b_scale") = kSize - 1;
411 builder.uniform("inv_size") = 1.0f / kSize;
Brian Osman6285d642021-05-05 08:24:03 -0400412
413 SkPaint paint;
414
415 // TODO: Should we add SkImage::makeNormalizedShader() to handle this automatically?
416 SkMatrix normalize = SkMatrix::Scale(1.0f / (kSize * kSize), 1.0f / kSize);
417
418 // Now draw the image with an identity color cube - it should look like the original
John Stilesa4079ec2023-02-02 17:54:12 -0500419 builder.child("color_cube") = fIdentityCube->makeShader(sampling, normalize);
420
421 paint.setColorFilter(builder.makeColorFilter());
Brian Osman6285d642021-05-05 08:24:03 -0400422 canvas->drawImage(fMandrill, 256, 0, sampling, &paint);
423
424 // ... and with a sepia-tone color cube. This should match the sepia-toned image.
John Stilesa4079ec2023-02-02 17:54:12 -0500425 builder.child("color_cube") = fSepiaCube->makeShader(sampling, normalize);
426
427 paint.setColorFilter(builder.makeColorFilter());
Brian Osman6285d642021-05-05 08:24:03 -0400428 canvas->drawImage(fMandrill, 256, 256, sampling, &paint);
429 }
430};
431DEF_GM(return new ColorCubeColorFilterRT;)
432
Chris Dalton224e5e42021-04-16 11:43:39 -0600433// Emits coverage for a rounded rectangle whose corners are superellipses defined by the boundary:
Chris Dalton4e94fd12021-03-15 10:16:09 -0600434//
Chris Dalton224e5e42021-04-16 11:43:39 -0600435// x^n + y^n == 1
Chris Dalton4e94fd12021-03-15 10:16:09 -0600436//
Chris Dalton224e5e42021-04-16 11:43:39 -0600437// Where x and y are normalized, clamped coordinates ranging from 0..1 inside the nearest corner's
438// bounding box.
Chris Dalton4e94fd12021-03-15 10:16:09 -0600439//
Chris Dalton224e5e42021-04-16 11:43:39 -0600440// See: https://en.wikipedia.org/wiki/Superellipse
441class ClipSuperRRect : public RuntimeShaderGM {
Chris Dalton4e94fd12021-03-15 10:16:09 -0600442public:
Chris Dalton224e5e42021-04-16 11:43:39 -0600443 ClipSuperRRect(const char* name, float power) : RuntimeShaderGM(name, {500, 500}, R"(
444 uniform float power_minus1;
445 uniform float2 stretch_factor;
Chris Dalton4e94fd12021-03-15 10:16:09 -0600446 uniform float2x2 derivatives;
447 half4 main(float2 xy) {
Chris Dalton224e5e42021-04-16 11:43:39 -0600448 xy = max(abs(xy) + stretch_factor, 0);
449 float2 exp_minus1 = pow(xy, power_minus1.xx); // If power == 3.5: xy * xy * sqrt(xy)
450 float f = dot(exp_minus1, xy) - 1; // f = x^n + y^n - 1
451 float2 grad = exp_minus1 * derivatives;
452 float fwidth = abs(grad.x) + abs(grad.y) + 1e-12; // 1e-12 to avoid a divide by zero.
Chris Dalton4e94fd12021-03-15 10:16:09 -0600453 return half4(saturate(.5 - f/fwidth)); // Approx coverage by riding the gradient to f=0.
454 }
Chris Dalton224e5e42021-04-16 11:43:39 -0600455 )"), fPower(power) {}
Chris Dalton4e94fd12021-03-15 10:16:09 -0600456
Chris Dalton224e5e42021-04-16 11:43:39 -0600457 void drawSuperRRect(SkCanvas* canvas, const SkRect& superRRect, float radX, float radY,
458 SkColor color) {
459 SkPaint paint;
460 paint.setColor(color);
Chris Dalton4e94fd12021-03-15 10:16:09 -0600461
Chris Dalton224e5e42021-04-16 11:43:39 -0600462 if (fPower == 2) {
463 // Draw a normal round rect for the sake of testing.
464 SkRRect rrect = SkRRect::MakeRectXY(superRRect, radX, radY);
465 paint.setAntiAlias(true);
466 canvas->drawRRect(rrect, paint);
467 return;
468 }
Chris Dalton4e94fd12021-03-15 10:16:09 -0600469
470 SkRuntimeShaderBuilder builder(fEffect);
Chris Dalton224e5e42021-04-16 11:43:39 -0600471 builder.uniform("power_minus1") = fPower - 1;
472
473 // Size the corners such that the "apex" of our "super" rounded corner is in the same
474 // location that the apex of a circular rounded corner would be with the given radii. We
475 // define the apex as the point on the rounded corner that is 45 degrees between the
476 // horizontal and vertical edges.
477 float scale = (1 - SK_ScalarRoot2Over2) / (1 - exp2f(-1/fPower));
478 float cornerWidth = radX * scale;
479 float cornerHeight = radY * scale;
480 cornerWidth = std::min(cornerWidth, superRRect.width() * .5f);
481 cornerHeight = std::min(cornerHeight, superRRect.height() * .5f);
482 // The stretch factor controls how long the flat edge should be between rounded corners.
483 builder.uniform("stretch_factor") = SkV2{1 - superRRect.width()*.5f / cornerWidth,
484 1 - superRRect.height()*.5f / cornerHeight};
Chris Dalton4e94fd12021-03-15 10:16:09 -0600485
486 // Calculate a 2x2 "derivatives" matrix that the shader will use to find the gradient.
487 //
Chris Dalton224e5e42021-04-16 11:43:39 -0600488 // f = s^n + t^n - 1 [s,t are "super" rounded corner coords in normalized 0..1 space]
Chris Dalton4e94fd12021-03-15 10:16:09 -0600489 //
Chris Dalton224e5e42021-04-16 11:43:39 -0600490 // gradient = [df/dx df/dy] = [ns^(n-1) nt^(n-1)] * |ds/dx ds/dy|
Chris Dalton4e94fd12021-03-15 10:16:09 -0600491 // |dt/dx dt/dy|
492 //
Chris Dalton224e5e42021-04-16 11:43:39 -0600493 // = [s^(n-1) t^(n-1)] * |n 0| * |ds/dx ds/dy|
Chris Dalton4e94fd12021-03-15 10:16:09 -0600494 // |0 n| |dt/dx dt/dy|
495 //
Chris Dalton224e5e42021-04-16 11:43:39 -0600496 // = [s^(n-1) t^(n-1)] * |2n/cornerWidth 0| * mat2x2(canvasMatrix)^-1
497 // |0 2n/cornerHeight|
Chris Dalton4e94fd12021-03-15 10:16:09 -0600498 //
Chris Dalton224e5e42021-04-16 11:43:39 -0600499 // = [s^(n-1) t^(n-1)] * "derivatives"
Chris Dalton4e94fd12021-03-15 10:16:09 -0600500 //
501 const SkMatrix& M = canvas->getTotalMatrix();
502 float a=M.getScaleX(), b=M.getSkewX(), c=M.getSkewY(), d=M.getScaleY();
Chris Dalton224e5e42021-04-16 11:43:39 -0600503 float determinant = a*d - b*c;
504 float dx = fPower / (cornerWidth * determinant);
505 float dy = fPower / (cornerHeight * determinant);
Chris Dalton4e94fd12021-03-15 10:16:09 -0600506 builder.uniform("derivatives") = SkV4{d*dx, -c*dy, -b*dx, a*dy};
507
Chris Dalton224e5e42021-04-16 11:43:39 -0600508 // This matrix will be inverted by the effect system, giving a matrix that converts local
509 // coordinates to (almost) coner coordinates. To get the rest of the way to the nearest
510 // corner's space, the shader will have to take the absolute value, add the stretch_factor,
511 // then clamp above zero.
512 SkMatrix cornerToLocal;
513 cornerToLocal.setScaleTranslate(cornerWidth, cornerHeight, superRRect.centerX(),
514 superRRect.centerY());
Brian Osmancd189e82022-02-09 11:56:45 -0500515 canvas->clipShader(builder.makeShader(&cornerToLocal));
Chris Dalton224e5e42021-04-16 11:43:39 -0600516
517 // Bloat the outer edges of the rect we will draw so it contains all the antialiased pixels.
518 // Bloat by a full pixel instead of half in case Skia is in a mode that draws this rect with
519 // unexpected AA of its own.
520 float inverseDet = 1 / fabsf(determinant);
521 float bloatX = (fabsf(d) + fabsf(c)) * inverseDet;
522 float bloatY = (fabsf(b) + fabsf(a)) * inverseDet;
523 canvas->drawRect(superRRect.makeOutset(bloatX, bloatY), paint);
524 }
525
526 void onDraw(SkCanvas* canvas) override {
527 SkRandom rand(2);
528
529 canvas->save();
530 canvas->translate(canvas->imageInfo().width() / 2.f, canvas->imageInfo().height() / 2.f);
531
532 canvas->save();
533 canvas->rotate(21);
534 this->drawSuperRRect(canvas, SkRect::MakeXYWH(-5, 25, 175, 100), 50, 30,
535 rand.nextU() | 0xff808080);
536 canvas->restore();
537
538 canvas->save();
539 canvas->rotate(94);
540 this->drawSuperRRect(canvas, SkRect::MakeXYWH(95, 75, 125, 100), 30, 30,
541 rand.nextU() | 0xff808080);
542 canvas->restore();
543
544 canvas->save();
545 canvas->rotate(132);
546 this->drawSuperRRect(canvas, SkRect::MakeXYWH(0, 75, 150, 100), 40, 30,
547 rand.nextU() | 0xff808080);
548 canvas->restore();
549
550 canvas->save();
551 canvas->rotate(282);
552 this->drawSuperRRect(canvas, SkRect::MakeXYWH(15, -20, 100, 100), 20, 20,
553 rand.nextU() | 0xff808080);
554 canvas->restore();
555
556 canvas->save();
557 canvas->rotate(0);
558 this->drawSuperRRect(canvas, SkRect::MakeXYWH(140, -50, 90, 110), 25, 25,
559 rand.nextU() | 0xff808080);
560 canvas->restore();
561
562 canvas->save();
563 canvas->rotate(-35);
564 this->drawSuperRRect(canvas, SkRect::MakeXYWH(160, -60, 60, 90), 18, 18,
565 rand.nextU() | 0xff808080);
566 canvas->restore();
567
568 canvas->save();
569 canvas->rotate(65);
570 this->drawSuperRRect(canvas, SkRect::MakeXYWH(220, -120, 60, 90), 18, 18,
571 rand.nextU() | 0xff808080);
572 canvas->restore();
573
574 canvas->save();
575 canvas->rotate(265);
576 this->drawSuperRRect(canvas, SkRect::MakeXYWH(150, -129, 80, 160), 24, 39,
577 rand.nextU() | 0xff808080);
578 canvas->restore();
Chris Dalton4e94fd12021-03-15 10:16:09 -0600579
580 canvas->restore();
581 }
Chris Dalton224e5e42021-04-16 11:43:39 -0600582
583private:
584 const float fPower;
Chris Dalton4e94fd12021-03-15 10:16:09 -0600585};
Chris Dalton224e5e42021-04-16 11:43:39 -0600586DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow2", 2);)
587// DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow3", 3);)
588DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow3.5", 3.5);)
589// DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow4", 4);)
590// DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow4.5", 4.5);)
591// DEF_GM(return new ClipSuperRRect("clip_super_rrect_pow5", 5);)
Mike Klein71d420d2021-02-03 09:54:07 -0600592
Brian Osman2f2977e2021-12-07 16:05:39 -0500593class LinearGradientRT : public RuntimeShaderGM {
594public:
595 LinearGradientRT() : RuntimeShaderGM("linear_gradient_rt", {256 + 10, 128 + 15}, R"(
596 layout(color) uniform vec4 in_colors0;
597 layout(color) uniform vec4 in_colors1;
598
599 vec4 main(vec2 p) {
600 float t = p.x / 256;
601 if (p.y < 32) {
602 return mix(in_colors0, in_colors1, t);
603 } else {
604 vec3 linColor0 = toLinearSrgb(in_colors0.rgb);
605 vec3 linColor1 = toLinearSrgb(in_colors1.rgb);
606 vec3 linColor = mix(linColor0, linColor1, t);
607 return fromLinearSrgb(linColor).rgb1;
608 }
609 }
610 )") {}
611
612 void onDraw(SkCanvas* canvas) override {
613 // Colors chosen to use values other than 0 and 1 - so that it's obvious if the conversion
614 // intrinsics are doing anything. (Most transfer functions map 0 -> 0 and 1 -> 1).
615 SkRuntimeShaderBuilder builder(fEffect);
616 builder.uniform("in_colors0") = SkColor4f{0.75f, 0.25f, 0.0f, 1.0f};
617 builder.uniform("in_colors1") = SkColor4f{0.0f, 0.75f, 0.25f, 1.0f};
618 SkPaint paint;
Brian Osmancd189e82022-02-09 11:56:45 -0500619 paint.setShader(builder.makeShader());
Brian Osman2f2977e2021-12-07 16:05:39 -0500620
621 canvas->save();
622 canvas->clear(SK_ColorWHITE);
623 canvas->translate(5, 5);
624
625 // We draw everything twice. First to a surface with no color management, where the
626 // intrinsics should do nothing (eg, the top bar should look the same in the top and bottom
627 // halves). Then to an sRGB surface, where they should produce linearly interpolated
628 // gradients (the bottom half of the second bar should be brighter than the top half).
629 for (auto cs : {static_cast<SkColorSpace*>(nullptr), sk_srgb_singleton()}) {
630 SkImageInfo info = SkImageInfo::Make(
631 256, 64, kN32_SkColorType, kPremul_SkAlphaType, sk_ref_sp(cs));
632 auto surface = canvas->makeSurface(info);
633 if (!surface) {
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400634 surface = SkSurfaces::Raster(info);
Brian Osman2f2977e2021-12-07 16:05:39 -0500635 }
636
637 surface->getCanvas()->drawRect({0, 0, 256, 64}, paint);
638 canvas->drawImage(surface->makeImageSnapshot(), 0, 0);
639 canvas->translate(0, 64 + 5);
640 }
641
642 canvas->restore();
643 }
644};
645DEF_GM(return new LinearGradientRT;)
646
Mike Klein71d420d2021-02-03 09:54:07 -0600647DEF_SIMPLE_GM(child_sampling_rt, canvas, 256,256) {
648 static constexpr char scale[] =
649 "uniform shader child;"
650 "half4 main(float2 xy) {"
Brian Osmancbfa34a2021-09-02 09:26:27 -0400651 " return child.eval(xy*0.1);"
Mike Klein71d420d2021-02-03 09:54:07 -0600652 "}";
653
654 SkPaint p;
655 p.setColor(SK_ColorRED);
656 p.setAntiAlias(true);
657 p.setStyle(SkPaint::kStroke_Style);
658 p.setStrokeWidth(1);
659
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400660 auto surf = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(100, 100));
Mike Klein71d420d2021-02-03 09:54:07 -0600661 surf->getCanvas()->drawLine(0, 0, 100, 100, p);
662 auto shader = surf->makeImageSnapshot()->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
663
Brian Osmanf6123f12021-04-15 13:52:43 -0400664 SkRuntimeShaderBuilder builder(SkRuntimeEffect::MakeForShader(SkString(scale)).effect);
Mike Klein71d420d2021-02-03 09:54:07 -0600665 builder.child("child") = shader;
Brian Osmancd189e82022-02-09 11:56:45 -0500666 p.setShader(builder.makeShader());
Mike Klein71d420d2021-02-03 09:54:07 -0600667
668 canvas->drawPaint(p);
669}
Brian Osmand34b49f2021-10-18 14:07:43 -0400670
671static sk_sp<SkShader> normal_map_shader() {
672 // Produces a hemispherical normal:
673 static const char* kSrc = R"(
674 half4 main(vec2 p) {
675 p = (p / 256) * 2 - 1;
676 float p2 = dot(p, p);
677 vec3 v = (p2 > 1) ? vec3(0, 0, 1) : vec3(p, sqrt(1 - p2));
678 return (v * 0.5 + 0.5).xyz1;
679 }
680 )";
681 auto effect = SkRuntimeEffect::MakeForShader(SkString(kSrc)).effect;
Brian Osmancd189e82022-02-09 11:56:45 -0500682 return effect->makeShader(nullptr, {});
Brian Osmand34b49f2021-10-18 14:07:43 -0400683}
684
Brian Osman20c6a942021-11-29 12:27:00 -0500685static sk_sp<SkImage> normal_map_image() {
Brian Osmand34b49f2021-10-18 14:07:43 -0400686 // Above, baked into an image:
Brian Osman20c6a942021-11-29 12:27:00 -0500687 auto info = SkImageInfo::Make(256, 256, kN32_SkColorType, kPremul_SkAlphaType);
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400688 auto surface = SkSurfaces::Raster(info);
Brian Osmand34b49f2021-10-18 14:07:43 -0400689 SkPaint p;
690 p.setShader(normal_map_shader());
691 surface->getCanvas()->drawPaint(p);
Brian Osman20c6a942021-11-29 12:27:00 -0500692 return surface->makeImageSnapshot();
693}
694
695static sk_sp<SkShader> normal_map_image_shader() {
Michael Ludwig2c49e602023-05-30 13:12:19 -0400696 return normal_map_image()->makeShader(SkFilterMode::kNearest);
Brian Osman20c6a942021-11-29 12:27:00 -0500697}
698
699static sk_sp<SkShader> normal_map_raw_image_shader() {
Michael Ludwig2c49e602023-05-30 13:12:19 -0400700 return normal_map_image()->makeRawShader(SkFilterMode::kNearest);
Brian Osman20c6a942021-11-29 12:27:00 -0500701}
702
703static sk_sp<SkImage> normal_map_unpremul_image() {
704 auto image = normal_map_image();
705 SkPixmap pm;
706 SkAssertResult(image->peekPixels(&pm));
707 SkBitmap bmp;
708 bmp.allocPixels(image->imageInfo().makeAlphaType(kUnpremul_SkAlphaType));
709 // Copy all pixels over, but set alpha to 0
710 for (int y = 0; y < pm.height(); y++) {
711 for (int x = 0; x < pm.width(); x++) {
712 *bmp.getAddr32(x, y) = *pm.addr32(x, y) & 0x00FFFFFF;
713 }
714 }
715 return bmp.asImage();
716}
717
718static sk_sp<SkShader> normal_map_unpremul_image_shader() {
Michael Ludwig2c49e602023-05-30 13:12:19 -0400719 return normal_map_unpremul_image()->makeShader(SkFilterMode::kNearest);
Brian Osman20c6a942021-11-29 12:27:00 -0500720}
721
722static sk_sp<SkShader> normal_map_raw_unpremul_image_shader() {
Michael Ludwig2c49e602023-05-30 13:12:19 -0400723 return normal_map_unpremul_image()->makeRawShader(SkFilterMode::kNearest);
Brian Osmand34b49f2021-10-18 14:07:43 -0400724}
725
726static sk_sp<SkShader> lit_shader(sk_sp<SkShader> normals) {
Brian Osman2f2977e2021-12-07 16:05:39 -0500727 // Simple N-dot-L against a fixed, directional light:
Brian Osmand34b49f2021-10-18 14:07:43 -0400728 static const char* kSrc = R"(
729 uniform shader normals;
730 half4 main(vec2 p) {
731 vec3 n = normalize(normals.eval(p).xyz * 2 - 1);
732 vec3 l = normalize(vec3(1, -1, 1));
Brian Osmanf893df92021-11-09 10:10:45 -0500733 return saturate(dot(n, l)).xxx1;
Brian Osmand34b49f2021-10-18 14:07:43 -0400734 }
735 )";
736 auto effect = SkRuntimeEffect::MakeForShader(SkString(kSrc)).effect;
Brian Osmancd189e82022-02-09 11:56:45 -0500737 return effect->makeShader(nullptr, &normals, 1);
Brian Osmand34b49f2021-10-18 14:07:43 -0400738}
739
Brian Osman2f2977e2021-12-07 16:05:39 -0500740static sk_sp<SkShader> lit_shader_linear(sk_sp<SkShader> normals) {
741 // Simple N-dot-L against a fixed, directional light, done in linear space:
742 static const char* kSrc = R"(
743 uniform shader normals;
744 half4 main(vec2 p) {
745 vec3 n = normalize(normals.eval(p).xyz * 2 - 1);
746 vec3 l = normalize(vec3(1, -1, 1));
747 return fromLinearSrgb(saturate(dot(n, l)).xxx).xxx1;
748 }
749 )";
750 auto effect = SkRuntimeEffect::MakeForShader(SkString(kSrc)).effect;
Brian Osmancd189e82022-02-09 11:56:45 -0500751 return effect->makeShader(nullptr, &normals, 1);
Brian Osman2f2977e2021-12-07 16:05:39 -0500752}
753
Brian Osmand34b49f2021-10-18 14:07:43 -0400754DEF_SIMPLE_GM(paint_alpha_normals_rt, canvas, 512,512) {
755 // Various draws, with non-opaque paint alpha. This demonstrates several issues around how
756 // paint alpha is applied differently on CPU (globally, after all shaders) and GPU (per shader,
757 // inconsistently). See: skbug.com/11942
758 //
759 // When this works, it will be a demo of applying paint alpha to fade out a complex effect.
760 auto draw_shader = [=](int x, int y, sk_sp<SkShader> shader) {
761 SkPaint p;
762 p.setAlpha(164);
763 p.setShader(shader);
764
765 canvas->save();
766 canvas->translate(x, y);
767 canvas->clipRect({0, 0, 256, 256});
768 canvas->drawPaint(p);
769 canvas->restore();
770 };
771
772 draw_shader(0, 0, normal_map_shader());
773 draw_shader(0, 256, normal_map_image_shader());
774
775 draw_shader(256, 0, lit_shader(normal_map_shader()));
776 draw_shader(256, 256, lit_shader(normal_map_image_shader()));
777}
Brian Osman20c6a942021-11-29 12:27:00 -0500778
779DEF_SIMPLE_GM(raw_image_shader_normals_rt, canvas, 768, 512) {
780 // Demonstrates the utility of SkImage::makeRawShader, for non-color child shaders.
781
782 // First, make an offscreen surface, so we can control the destination color space:
783 auto surfInfo = SkImageInfo::Make(512, 512,
784 kN32_SkColorType,
785 kPremul_SkAlphaType,
786 SkColorSpace::MakeSRGB()->makeColorSpin());
787 auto surface = canvas->makeSurface(surfInfo);
788 if (!surface) {
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400789 surface = SkSurfaces::Raster(surfInfo);
Brian Osman20c6a942021-11-29 12:27:00 -0500790 }
791
792 auto draw_shader = [](int x, int y, sk_sp<SkShader> shader, SkCanvas* canvas) {
793 SkPaint p;
794 p.setShader(shader);
795
796 canvas->save();
797 canvas->translate(x, y);
798 canvas->clipRect({0, 0, 256, 256});
799 canvas->drawPaint(p);
800 canvas->restore();
801 };
802
803 sk_sp<SkShader> colorNormals = normal_map_image_shader(),
804 rawNormals = normal_map_raw_image_shader();
805
806 // Draw our normal map as colors (will be color-rotated), and raw (untransformed)
807 draw_shader(0, 0, colorNormals, surface->getCanvas());
808 draw_shader(0, 256, rawNormals, surface->getCanvas());
809
810 // Now draw our lighting shader using the normal and raw versions of the normals as children.
811 // The top image will have the normals rotated (incorrectly), so the lighting is very dark.
812 draw_shader(256, 0, lit_shader(colorNormals), surface->getCanvas());
813 draw_shader(256, 256, lit_shader(rawNormals), surface->getCanvas());
814
815 // Now draw the offscreen surface back to our original canvas. If we do this naively, the image
816 // will be un-transformed back to the canvas' color space. That will have the effect of undoing
817 // the color spin on the upper-left, and APPLYING a color-spin on the bottom left. To preserve
818 // the intent of this GM (and make it draw consistently whether or not the original surface has
819 // a color space attached), we reinterpret the offscreen image as being in sRGB:
820 canvas->drawImage(
821 surface->makeImageSnapshot()->reinterpretColorSpace(SkColorSpace::MakeSRGB()), 0, 0);
822
823 // Finally, to demonstrate that raw unpremul image shaders don't premul, draw lighting two more
824 // times, with an unpremul normal map (containing ZERO in the alpha channel). THe top will
825 // premultiply the normals, resulting in totally dark lighting. The bottom will retain the RGB
826 // encoded normals, even with zero alpha:
827 draw_shader(512, 0, lit_shader(normal_map_unpremul_image_shader()), canvas);
828 draw_shader(512, 256, lit_shader(normal_map_raw_unpremul_image_shader()), canvas);
829}
Brian Osman2f2977e2021-12-07 16:05:39 -0500830
831DEF_SIMPLE_GM(lit_shader_linear_rt, canvas, 512, 256) {
832 // First, make an offscreen surface, so we can control the destination color space:
833 auto surfInfo = SkImageInfo::Make(512, 256,
834 kN32_SkColorType,
835 kPremul_SkAlphaType,
836 SkColorSpace::MakeSRGB());
837 auto surface = canvas->makeSurface(surfInfo);
838 if (!surface) {
Kevin Lubick5c93acf2023-05-09 12:11:43 -0400839 surface = SkSurfaces::Raster(surfInfo);
Brian Osman2f2977e2021-12-07 16:05:39 -0500840 }
841
842 auto draw_shader = [](int x, int y, sk_sp<SkShader> shader, SkCanvas* canvas) {
843 SkPaint p;
844 p.setShader(shader);
845
846 canvas->save();
847 canvas->translate(x, y);
848 canvas->clipRect({0, 0, 256, 256});
849 canvas->drawPaint(p);
850 canvas->restore();
851 };
852
853 // We draw two lit spheres - one does math in the working space (so gamma-encoded). The second
854 // works in linear space, then converts to sRGB. This produces (more accurate) sharp falloff:
855 draw_shader(0, 0, lit_shader(normal_map_shader()), surface->getCanvas());
856 draw_shader(256, 0, lit_shader_linear(normal_map_shader()), surface->getCanvas());
857
858 // Now draw the offscreen surface back to our original canvas:
859 canvas->drawImage(surface->makeImageSnapshot(), 0, 0);
860}
Brian Salomon544059c2022-07-29 12:55:47 -0400861
862// skbug.com/13598 GPU was double applying the local matrix.
863DEF_SIMPLE_GM(local_matrix_shader_rt, canvas, 256, 256) {
864 SkString passthrough(R"(
865 uniform shader s;
866 half4 main(float2 p) { return s.eval(p); }
867 )");
868 auto [rte, error] = SkRuntimeEffect::MakeForShader(passthrough, {});
869 if (!rte) {
870 SkDebugf("%s\n", error.c_str());
871 return;
872 }
873
Kevin Lubick8b741882023-10-06 11:41:38 -0400874 auto image = ToolUtils::GetResourceAsImage("images/mandrill_128.png");
Michael Ludwig2c49e602023-05-30 13:12:19 -0400875 auto imgShader = image->makeShader(SkFilterMode::kNearest);
Brian Salomon544059c2022-07-29 12:55:47 -0400876
877 auto r = SkRect::MakeWH(image->width(), image->height());
878
879 auto lm = SkMatrix::RotateDeg(90.f, {image->width()/2.f, image->height()/2.f});
880
881 SkPaint paint;
882
883 // image
884 paint.setShader(imgShader);
885 canvas->drawRect(r, paint);
886
887 // passthrough(image)
888 canvas->save();
889 canvas->translate(image->width(), 0);
890 paint.setShader(rte->makeShader(nullptr, &imgShader, 1));
891 canvas->drawRect(r, paint);
892 canvas->restore();
893
894 // localmatrix(image)
895 canvas->save();
896 canvas->translate(0, image->height());
897 paint.setShader(imgShader->makeWithLocalMatrix(lm));
898 canvas->drawRect(r, paint);
899 canvas->restore();
900
901 // localmatrix(passthrough(image)) This was the bug.
902 canvas->save();
903 canvas->translate(image->width(), image->height());
904 paint.setShader(rte->makeShader(nullptr, &imgShader, 1)->makeWithLocalMatrix(lm));
905 canvas->drawRect(r, paint);
906 canvas->restore();
907}
John Stiles402be962022-09-12 14:23:13 -0400908
Brian Osman4f26f222023-09-13 17:14:08 -0400909DEF_SIMPLE_GM(null_child_rt, canvas, 150, 100) {
John Stiles402be962022-09-12 14:23:13 -0400910 using ChildPtr = SkRuntimeEffect::ChildPtr;
911
912 // Every swatch should evaluate to the same shade of purple.
913 // Paint with a shader evaluating a null shader.
Brian Osman4f26f222023-09-13 17:14:08 -0400914 // Point passed to eval() is ignored; transparent black is returned.
John Stiles402be962022-09-12 14:23:13 -0400915 {
916 const SkString kEvalShader{R"(
917 uniform shader s;
Brian Osman4f26f222023-09-13 17:14:08 -0400918 half4 main(float2 p) { return s.eval(p) + half4(0.5, 0, 0.5, 1); }
John Stiles402be962022-09-12 14:23:13 -0400919 )"};
John Stilesdeac56e2022-09-13 11:07:14 -0400920 auto [rtShader, error] = SkRuntimeEffect::MakeForShader(kEvalShader);
John Stiles402be962022-09-12 14:23:13 -0400921 SkASSERT(rtShader);
922
923 SkPaint paint;
924 ChildPtr children[1] = {ChildPtr{sk_sp<SkShader>{nullptr}}};
925 paint.setShader(rtShader->makeShader(/*uniforms=*/nullptr, children));
Brian Osman4f26f222023-09-13 17:14:08 -0400926 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00)); // green (ignored)
John Stiles402be962022-09-12 14:23:13 -0400927 canvas->drawRect({0, 0, 48, 48}, paint);
928 canvas->translate(50, 0);
929 }
930 // Paint with a shader evaluating a null color filter.
John Stilesdeac56e2022-09-13 11:07:14 -0400931 // Color passed to eval() is returned; paint color is ignored.
John Stiles402be962022-09-12 14:23:13 -0400932 {
933 const SkString kEvalColorFilter{R"(
934 uniform colorFilter cf;
John Stilesdeac56e2022-09-13 11:07:14 -0400935 half4 main(float2 p) { return cf.eval(half4(0.5, 0, 0.5, 1)); }
John Stiles402be962022-09-12 14:23:13 -0400936 )"};
John Stilesdeac56e2022-09-13 11:07:14 -0400937 auto [rtShader, error] = SkRuntimeEffect::MakeForShader(kEvalColorFilter);
John Stiles402be962022-09-12 14:23:13 -0400938 SkASSERT(rtShader);
939
940 SkPaint paint;
941 ChildPtr children[1] = {ChildPtr{sk_sp<SkColorFilter>{nullptr}}};
942 paint.setShader(rtShader->makeShader(/*uniforms=*/nullptr, children));
John Stilesdeac56e2022-09-13 11:07:14 -0400943 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0x00, 0xFF)); // green (does not contribute)
John Stiles402be962022-09-12 14:23:13 -0400944 canvas->drawRect({0, 0, 48, 48}, paint);
945 canvas->translate(50, 0);
946 }
947 // Paint with a shader evaluating a null blender.
John Stilesdeac56e2022-09-13 11:07:14 -0400948 // Colors passed to eval() are blended via src-over; paint color is ignored.
John Stiles402be962022-09-12 14:23:13 -0400949 {
950 const SkString kEvalBlender{R"(
951 uniform blender b;
John Stilesdeac56e2022-09-13 11:07:14 -0400952 half4 main(float2 p) { return b.eval(half4(0.5, 0, 0, 0.5), half4(0, 0, 1, 1)); }
John Stiles402be962022-09-12 14:23:13 -0400953 )"};
John Stilesdeac56e2022-09-13 11:07:14 -0400954 auto [rtShader, error] = SkRuntimeEffect::MakeForShader(kEvalBlender);
John Stiles402be962022-09-12 14:23:13 -0400955 SkASSERT(rtShader);
956
957 SkPaint paint;
958 ChildPtr children[1] = {ChildPtr{sk_sp<SkBlender>{nullptr}}};
959 paint.setShader(rtShader->makeShader(/*uniforms=*/nullptr, children));
John Stilesdeac56e2022-09-13 11:07:14 -0400960 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0x00, 0xFF)); // green (does not contribute)
John Stiles402be962022-09-12 14:23:13 -0400961 canvas->drawRect({0, 0, 48, 48}, paint);
962 canvas->translate(50, 0);
963 }
964
965 canvas->translate(-150, 50);
966
967 // Paint with a color filter evaluating a null shader.
Brian Osman4f26f222023-09-13 17:14:08 -0400968 // Point passed to eval() is ignored; transparent black is returned.
John Stiles402be962022-09-12 14:23:13 -0400969 {
970 const SkString kEvalShader{R"(
971 uniform shader s;
Brian Osman4f26f222023-09-13 17:14:08 -0400972 half4 main(half4 c) { return s.eval(float2(0)) + half4(0.5, 0, 0.5, 1); }
John Stiles402be962022-09-12 14:23:13 -0400973 )"};
John Stilesdeac56e2022-09-13 11:07:14 -0400974 auto [rtFilter, error] = SkRuntimeEffect::MakeForColorFilter(kEvalShader);
John Stiles402be962022-09-12 14:23:13 -0400975 SkASSERT(rtFilter);
976
977 SkPaint paint;
978 ChildPtr children[1] = {ChildPtr{sk_sp<SkShader>{nullptr}}};
979 paint.setColorFilter(rtFilter->makeColorFilter(/*uniforms=*/nullptr, children));
Brian Osman4f26f222023-09-13 17:14:08 -0400980 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00)); // green (ignored)
John Stiles402be962022-09-12 14:23:13 -0400981 canvas->drawRect({0, 0, 48, 48}, paint);
982 canvas->translate(50, 0);
983 }
984 // Paint with a color filter evaluating a null color filter.
John Stilesdeac56e2022-09-13 11:07:14 -0400985 // Color passed to eval() is returned; paint color is ignored.
John Stiles402be962022-09-12 14:23:13 -0400986 {
987 const SkString kEvalColorFilter{R"(
988 uniform colorFilter cf;
John Stilesdeac56e2022-09-13 11:07:14 -0400989 half4 main(half4 c) { return cf.eval(half4(0.5, 0, 0.5, 1)); }
John Stiles402be962022-09-12 14:23:13 -0400990 )"};
John Stilesdeac56e2022-09-13 11:07:14 -0400991 auto [rtFilter, error] = SkRuntimeEffect::MakeForColorFilter(kEvalColorFilter);
John Stiles402be962022-09-12 14:23:13 -0400992 SkASSERT(rtFilter);
993
994 SkPaint paint;
995 ChildPtr children[1] = {ChildPtr{sk_sp<SkColorFilter>{nullptr}}};
996 paint.setColorFilter(rtFilter->makeColorFilter(/*uniforms=*/nullptr, children));
John Stilesdeac56e2022-09-13 11:07:14 -0400997 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0x00, 0xFF)); // green (does not contribute)
John Stiles402be962022-09-12 14:23:13 -0400998 canvas->drawRect({0, 0, 48, 48}, paint);
999 canvas->translate(50, 0);
1000 }
1001 // Paint with a color filter evaluating a null blender.
John Stilesdeac56e2022-09-13 11:07:14 -04001002 // Colors passed to eval() are blended via src-over; paint color is ignored.
John Stiles402be962022-09-12 14:23:13 -04001003 {
1004 const SkString kEvalBlender{R"(
1005 uniform blender b;
John Stilesdeac56e2022-09-13 11:07:14 -04001006 half4 main(half4 c) { return b.eval(half4(0.5, 0, 0, 0.5), half4(0, 0, 1, 1)); }
John Stiles402be962022-09-12 14:23:13 -04001007 )"};
John Stilesdeac56e2022-09-13 11:07:14 -04001008 auto [rtFilter, error] = SkRuntimeEffect::MakeForColorFilter(kEvalBlender);
John Stiles402be962022-09-12 14:23:13 -04001009 SkASSERT(rtFilter);
1010
1011 SkPaint paint;
1012 ChildPtr children[1] = {ChildPtr{sk_sp<SkBlender>{nullptr}}};
1013 paint.setColorFilter(rtFilter->makeColorFilter(/*uniforms=*/nullptr, children));
John Stilesdeac56e2022-09-13 11:07:14 -04001014 paint.setColor(SkColorSetARGB(0xFF, 0x00, 0x00, 0xFF)); // green (does not contribute)
John Stiles402be962022-09-12 14:23:13 -04001015 canvas->drawRect({0, 0, 48, 48}, paint);
1016 canvas->translate(50, 0);
1017 }
John Stiles402be962022-09-12 14:23:13 -04001018}
Brian Osman529fb1e2023-03-08 10:13:39 -05001019
1020DEF_SIMPLE_GM_CAN_FAIL(deferred_shader_rt, canvas, errorMsg, 150, 50) {
1021 // Skip this GM on recording devices. It actually works okay on serialize-8888, but pic-8888
John Stiles0627b5c2023-06-21 20:13:13 -04001022 // does not. Ultimately, behavior on CPU is potentially strange (especially with SkRP), because
1023 // SkRP will build the shader more than once per draw.
Brian Osman529fb1e2023-03-08 10:13:39 -05001024 if (canvas->imageInfo().colorType() == kUnknown_SkColorType) {
1025 return skiagm::DrawResult::kSkip;
1026 }
1027
1028 const SkString kShader{R"(
1029 uniform half4 color;
1030 half4 main(float2 p) { return color; }
1031 )"};
1032 auto [effect, error] = SkRuntimeEffect::MakeForShader(kShader);
1033 SkASSERT(effect);
1034
1035 SkColor4f color = SkColors::kRed;
1036 auto makeUniforms = [color](const SkRuntimeEffectPriv::UniformsCallbackContext&) mutable {
1037 auto result = SkData::MakeWithCopy(&color, sizeof(color));
1038 color = {color.fB, color.fR, color.fG, color.fA};
1039 return result;
1040 };
1041
1042 auto shader =
1043 SkRuntimeEffectPriv::MakeDeferredShader(effect.get(), makeUniforms, /*children=*/{});
1044 SkASSERT(shader);
1045
1046 SkPaint paint;
1047 paint.setShader(shader);
1048
1049 for (int i = 0; i < 3; ++i) {
1050 canvas->drawRect({0, 0, 50, 50}, paint);
1051 canvas->translate(50, 0);
1052 }
1053
1054 return skiagm::DrawResult::kOk;
1055}
Brian Osman048b59f2023-09-15 16:31:13 -04001056
1057sk_sp<SkShader> paint_color_shader() {
1058 SkBitmap bmp;
1059 bmp.allocPixels(SkImageInfo::Make(1, 1, kAlpha_8_SkColorType, kPremul_SkAlphaType));
1060 bmp.eraseColor(SK_ColorWHITE);
1061 return bmp.makeShader(SkFilterMode::kNearest);
1062}
1063
1064DEF_SIMPLE_GM_CAN_FAIL(alpha_image_shader_rt, canvas, errorMsg, 350, 50) {
1065 if (!canvas->getSurface()) {
1066 // The only backend that really fails is DDL (because the color filter fails to evaluate on
1067 // the CPU when we do paint optimization). We can't identify DDL separate from other
1068 // recording backends, so skip this GM for all of them:
1069 *errorMsg = "Not supported in recording/DDL mode";
1070 return skiagm::DrawResult::kSkip;
1071 }
1072
1073 // Skia typically applies the paint color (or input color, for more complex GPU-FP trees)
1074 // to alpha-only images. This is useful in trivial cases, but surprising and inconsistent in
1075 // more complex situations, especially when using SkSL.
1076 //
1077 // This GM checks that we suppress the paint-color tinting from SkSL, and always get {0,0,0,a}.
1078 auto checkerboard = ToolUtils::create_checkerboard_shader(SK_ColorBLACK, SK_ColorWHITE, 4);
1079 auto paint_shader = paint_color_shader();
1080 SkRuntimeEffect::ChildPtr children[1] = { paint_shader };
1081
1082 SkPaint paint;
1083 paint.setColor({0.5f, 0, 0.5f, 1.0f});
1084
1085 auto rect = [&]() {
1086 canvas->drawRect({0, 0, 48, 48}, paint);
1087 canvas->translate(50, 0);
1088 };
1089
1090 // Two simple cases: just paint color, then the "paint color" shader.
1091 // These should both be PURPLE
1092 rect();
1093
1094 paint.setShader(paint_shader);
1095 rect();
1096
1097 // All remaining cases should be BLACK
1098
1099 // Shader that evaluates the "paint color" shader.
1100 // For color-filter and blender, we test them with and without an actual SkShader on the paint.
1101 // These should all be BLACK
1102 paint.setShader(
1103 SkRuntimeEffect::MakeForShader(SkString("uniform shader s;"
1104 "half4 main(float2 p) { return s.eval(p); }"))
1105 .effect->makeShader(nullptr, children));
1106 rect();
1107
1108 // Color-filter that evaluates the "paint color" shader, with and without a shader on the paint
1109 paint.setShader(nullptr);
1110 paint.setColorFilter(SkRuntimeEffect::MakeForColorFilter(
1111 SkString("uniform shader s;"
1112 "half4 main(half4 color) { return s.eval(float2(0)); }"))
1113 .effect->makeColorFilter(nullptr, children));
1114 rect();
1115
1116 paint.setShader(checkerboard);
1117 rect();
1118
1119 // Blender that evaluates the "paint color" shader, with and without a shader on the paint
1120 paint.setShader(nullptr);
1121 paint.setColorFilter(nullptr);
1122 paint.setBlender(
1123 SkRuntimeEffect::MakeForBlender(
1124 SkString("uniform shader s;"
1125 "half4 main(half4 src, half4 dst) { return s.eval(float2(0)); }"))
1126 .effect->makeBlender(nullptr, children));
1127 rect();
1128
1129 paint.setShader(checkerboard);
1130 rect();
1131
1132 return skiagm::DrawResult::kOk;
1133}