blob: 24d848840e7b4ee7d717bd25e355034632dcc37a [file] [log] [blame]
jvanverth9f372462016-04-06 06:08:59 -07001/*
2* Copyright 2016 Google Inc.
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/core/SkCanvas.h"
9#include "include/core/SkData.h"
10#include "include/core/SkGraphics.h"
11#include "include/core/SkPictureRecorder.h"
12#include "include/core/SkStream.h"
13#include "include/core/SkSurface.h"
Robert Phillipsed653392020-07-10 13:55:21 -040014#include "include/gpu/GrDirectContext.h"
Mike Klein8aa0edf2020-10-16 11:04:18 -050015#include "include/private/SkTPin.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050016#include "include/private/SkTo.h"
17#include "include/utils/SkPaintFilterCanvas.h"
18#include "src/core/SkColorSpacePriv.h"
19#include "src/core/SkImagePriv.h"
20#include "src/core/SkMD5.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/core/SkOSFile.h"
22#include "src/core/SkScan.h"
John Stilesdf078002020-07-14 09:44:57 -040023#include "src/core/SkTSort.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "src/core/SkTaskGroup.h"
Robert Phillipse19babf2020-04-06 13:57:30 -040025#include "src/core/SkTextBlobPriv.h"
Adlai Hollera0693042020-10-14 11:23:11 -040026#include "src/gpu/GrDirectContextPriv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050027#include "src/gpu/GrGpu.h"
28#include "src/gpu/GrPersistentCacheUtils.h"
Chris Dalton77912982019-12-16 11:18:13 -070029#include "src/gpu/GrShaderUtils.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050030#include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
Chris Daltonff18ff62020-12-07 17:39:26 -070031#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
Adlai Hollerbcfc5542020-08-27 12:44:07 -040032#include "src/image/SkImage_Base.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050033#include "src/utils/SkJSONWriter.h"
34#include "src/utils/SkOSPath.h"
35#include "tools/Resources.h"
36#include "tools/ToolUtils.h"
37#include "tools/flags/CommandLineFlags.h"
38#include "tools/flags/CommonFlags.h"
39#include "tools/trace/EventTracingPriv.h"
40#include "tools/viewer/BisectSlide.h"
41#include "tools/viewer/GMSlide.h"
42#include "tools/viewer/ImageSlide.h"
43#include "tools/viewer/ParticlesSlide.h"
44#include "tools/viewer/SKPSlide.h"
45#include "tools/viewer/SampleSlide.h"
Brian Osmand927bd22019-12-18 11:23:12 -050046#include "tools/viewer/SkSLSlide.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050047#include "tools/viewer/SlideDir.h"
48#include "tools/viewer/SvgSlide.h"
49#include "tools/viewer/Viewer.h"
csmartdalton578f0642017-02-24 16:04:47 -070050
Chris Dalton17dc4182020-03-25 16:18:16 -060051#include <cstdlib>
Hal Canaryc640d0d2018-06-13 09:59:02 -040052#include <map>
53
Hal Canary8a001442018-09-19 11:31:27 -040054#include "imgui.h"
Brian Osman0b8bb882019-04-12 11:47:19 -040055#include "misc/cpp/imgui_stdlib.h" // For ImGui support of std::string
Florin Malita3b526b02018-05-25 12:43:51 -040056
Brian Osmanc85f1fa2020-06-16 15:11:34 -040057#ifdef SK_VULKAN
58#include "spirv-tools/libspirv.hpp"
59#endif
60
Florin Malita87ccf332018-05-04 12:23:24 -040061#if defined(SK_ENABLE_SKOTTIE)
Mike Kleinc0bd9f92019-04-23 12:05:21 -050062 #include "tools/viewer/SkottieSlide.h"
Florin Malita87ccf332018-05-04 12:23:24 -040063#endif
Florin Malita45cd2002020-06-09 14:00:54 -040064#if defined(SK_ENABLE_SKRIVE)
65 #include "tools/viewer/SkRiveSlide.h"
66#endif
Florin Malita87ccf332018-05-04 12:23:24 -040067
John Stiles8ef4d6c2021-03-05 16:01:45 -050068namespace SkSL {
John Stiles7247b482021-03-08 10:40:35 -050069extern bool gSkSLOptimizer;
70extern bool gSkSLInliner;
John Stiles8ef4d6c2021-03-05 16:01:45 -050071}
72
Brian Osman5e7fbfd2019-05-03 13:13:35 -040073class CapturingShaderErrorHandler : public GrContextOptions::ShaderErrorHandler {
74public:
75 void compileError(const char* shader, const char* errors) override {
76 fShaders.push_back(SkString(shader));
77 fErrors.push_back(SkString(errors));
78 }
79
80 void reset() {
81 fShaders.reset();
82 fErrors.reset();
83 }
84
85 SkTArray<SkString> fShaders;
86 SkTArray<SkString> fErrors;
87};
88
89static CapturingShaderErrorHandler gShaderErrorHandler;
90
Brian Osmanf847f312020-06-18 14:18:27 -040091GrContextOptions::ShaderErrorHandler* Viewer::ShaderErrorHandler() { return &gShaderErrorHandler; }
92
jvanverth34524262016-05-04 13:49:13 -070093using namespace sk_app;
94
csmartdalton61cd31a2017-02-27 17:00:53 -070095static std::map<GpuPathRenderers, std::string> gPathRendererNames;
96
jvanverth9f372462016-04-06 06:08:59 -070097Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070098 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070099}
100
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600101static DEFINE_string(slide, "", "Start on this sample.");
102static DEFINE_bool(list, false, "List samples?");
Jim Van Verth6f449692017-02-14 15:16:46 -0500103
Jim Van Verth682a2f42020-05-13 16:54:09 -0400104#ifdef SK_GL
105#define GL_BACKEND_STR ", \"gl\""
bsalomon6c471f72016-07-26 12:56:32 -0700106#else
Jim Van Verth682a2f42020-05-13 16:54:09 -0400107#define GL_BACKEND_STR
bsalomon6c471f72016-07-26 12:56:32 -0700108#endif
Jim Van Verth682a2f42020-05-13 16:54:09 -0400109#ifdef SK_VULKAN
110#define VK_BACKEND_STR ", \"vk\""
111#else
112#define VK_BACKEND_STR
113#endif
114#ifdef SK_METAL
115#define MTL_BACKEND_STR ", \"mtl\""
116#else
117#define MTL_BACKEND_STR
118#endif
119#ifdef SK_DIRECT3D
120#define D3D_BACKEND_STR ", \"d3d\""
121#else
122#define D3D_BACKEND_STR
123#endif
124#ifdef SK_DAWN
125#define DAWN_BACKEND_STR ", \"dawn\""
126#else
127#define DAWN_BACKEND_STR
128#endif
129#define BACKENDS_STR_EVALUATOR(sw, gl, vk, mtl, d3d, dawn) sw gl vk mtl d3d dawn
130#define BACKENDS_STR BACKENDS_STR_EVALUATOR( \
131 "\"sw\"", GL_BACKEND_STR, VK_BACKEND_STR, MTL_BACKEND_STR, D3D_BACKEND_STR, DAWN_BACKEND_STR)
bsalomon6c471f72016-07-26 12:56:32 -0700132
Brian Osman2dd96932016-10-18 15:33:53 -0400133static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700134
Mike Klein5b3f3432019-03-21 11:42:21 -0500135static DEFINE_int(msaa, 1, "Number of subpixel samples. 0 for no HW antialiasing.");
Chris Daltonfd708652021-03-17 21:10:17 -0600136static DEFINE_bool(dmsaa, false, "Use internal MSAA to render to non-MSAA surfaces?");
csmartdalton008b9d82017-02-22 12:00:42 -0700137
Mike Klein84836b72019-03-21 11:31:36 -0500138static DEFINE_string(bisect, "", "Path to a .skp or .svg file to bisect.");
Chris Dalton2d18f412018-02-20 13:23:32 -0700139
Mike Klein84836b72019-03-21 11:31:36 -0500140static DEFINE_string2(file, f, "", "Open a single file for viewing.");
Florin Malita38792ce2018-05-08 10:36:18 -0400141
Mike Kleinc6142d82019-03-25 10:54:59 -0500142static DEFINE_string2(match, m, nullptr,
143 "[~][^]substring[$] [...] of name to run.\n"
144 "Multiple matches may be separated by spaces.\n"
145 "~ causes a matching name to always be skipped\n"
146 "^ requires the start of the name to match\n"
147 "$ requires the end of the name to match\n"
148 "^ and $ requires an exact match\n"
149 "If a name does not match any list entry,\n"
150 "it is skipped unless some list entry starts with ~");
151
Mike Klein19fb3972019-03-21 13:08:08 -0500152#if defined(SK_BUILD_FOR_ANDROID)
153 static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
Mike Kleinc6142d82019-03-25 10:54:59 -0500154 static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
155 static DEFINE_string(lotties, "/data/local/tmp/lotties",
156 "Directory to read (Bodymovin) jsons from.");
Florin Malita45cd2002020-06-09 14:00:54 -0400157 static DEFINE_string(rives, "/data/local/tmp/rives",
158 "Directory to read Rive (Flare) files from.");
Mike Klein19fb3972019-03-21 13:08:08 -0500159#else
160 static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
Mike Kleinc6142d82019-03-25 10:54:59 -0500161 static DEFINE_string(skps, "skps", "Directory to read skps from.");
162 static DEFINE_string(lotties, "lotties", "Directory to read (Bodymovin) jsons from.");
Florin Malita45cd2002020-06-09 14:00:54 -0400163 static DEFINE_string(rives, "rives", "Directory to read Rive (Flare) files from.");
Mike Klein19fb3972019-03-21 13:08:08 -0500164#endif
165
Mike Kleinc6142d82019-03-25 10:54:59 -0500166static DEFINE_string(svgs, "", "Directory to read SVGs from, or a single SVG file.");
167
168static DEFINE_int_2(threads, j, -1,
169 "Run threadsafe tests on a threadpool with this many extra threads, "
170 "defaulting to one extra thread per core.");
171
Jim Van Verth7b558182019-11-14 16:47:01 -0500172static DEFINE_bool(redraw, false, "Toggle continuous redraw.");
173
Chris Daltonc8877332020-01-06 09:48:30 -0700174static DEFINE_bool(offscreen, false, "Force rendering to an offscreen surface.");
Mike Klein813e8cc2020-08-05 09:33:38 -0500175static DEFINE_bool(skvm, false, "Force skvm blitters for raster.");
176static DEFINE_bool(jit, true, "JIT SkVM?");
Mike Klein1e0884d2020-04-28 15:04:16 -0500177static DEFINE_bool(dylib, false, "JIT via dylib (much slower compile but easier to debug/profile)");
Mike Kleine42af162020-04-29 07:55:53 -0500178static DEFINE_bool(stats, false, "Display stats overlay on startup.");
Jim Van Verthecc91082020-11-20 15:30:25 -0500179static DEFINE_bool(binaryarchive, false, "Enable MTLBinaryArchive use (if available).");
Mike Kleinc6142d82019-03-25 10:54:59 -0500180
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400181#ifndef SK_GL
182static_assert(false, "viewer requires GL backend for raster.")
183#endif
184
Brian Salomon194db172017-08-17 14:37:06 -0400185const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700186 "OpenGL",
Brian Salomon194db172017-08-17 14:37:06 -0400187#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
188 "ANGLE",
189#endif
Stephen Whitea800ec92019-08-02 15:04:52 -0400190#ifdef SK_DAWN
191 "Dawn",
192#endif
jvanverth063ece72016-06-17 09:29:14 -0700193#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700194 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700195#endif
Jim Van Verthe58d5322019-09-03 09:42:57 -0400196#ifdef SK_METAL
Jim Van Verthbe39f712019-02-08 15:36:14 -0500197 "Metal",
198#endif
Jim Van Verth682a2f42020-05-13 16:54:09 -0400199#ifdef SK_DIRECT3D
200 "Direct3D",
201#endif
csmartdalton578f0642017-02-24 16:04:47 -0700202 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700203};
204
bsalomon6c471f72016-07-26 12:56:32 -0700205static sk_app::Window::BackendType get_backend_type(const char* str) {
Stephen Whitea800ec92019-08-02 15:04:52 -0400206#ifdef SK_DAWN
207 if (0 == strcmp(str, "dawn")) {
208 return sk_app::Window::kDawn_BackendType;
209 } else
210#endif
bsalomon6c471f72016-07-26 12:56:32 -0700211#ifdef SK_VULKAN
212 if (0 == strcmp(str, "vk")) {
213 return sk_app::Window::kVulkan_BackendType;
214 } else
215#endif
Brian Salomon194db172017-08-17 14:37:06 -0400216#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
217 if (0 == strcmp(str, "angle")) {
218 return sk_app::Window::kANGLE_BackendType;
219 } else
220#endif
Jim Van Verthe58d5322019-09-03 09:42:57 -0400221#ifdef SK_METAL
222 if (0 == strcmp(str, "mtl")) {
223 return sk_app::Window::kMetal_BackendType;
224 } else
Jim Van Verthbe39f712019-02-08 15:36:14 -0500225#endif
Jim Van Verth682a2f42020-05-13 16:54:09 -0400226#ifdef SK_DIRECT3D
227 if (0 == strcmp(str, "d3d")) {
228 return sk_app::Window::kDirect3D_BackendType;
229 } else
230#endif
231
bsalomon6c471f72016-07-26 12:56:32 -0700232 if (0 == strcmp(str, "gl")) {
233 return sk_app::Window::kNativeGL_BackendType;
234 } else if (0 == strcmp(str, "sw")) {
235 return sk_app::Window::kRaster_BackendType;
236 } else {
237 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
238 return sk_app::Window::kRaster_BackendType;
239 }
240}
241
Brian Osmana109e392017-02-24 09:49:14 -0500242static SkColorSpacePrimaries gSrgbPrimaries = {
243 0.64f, 0.33f,
244 0.30f, 0.60f,
245 0.15f, 0.06f,
246 0.3127f, 0.3290f };
247
248static SkColorSpacePrimaries gAdobePrimaries = {
249 0.64f, 0.33f,
250 0.21f, 0.71f,
251 0.15f, 0.06f,
252 0.3127f, 0.3290f };
253
254static SkColorSpacePrimaries gP3Primaries = {
255 0.680f, 0.320f,
256 0.265f, 0.690f,
257 0.150f, 0.060f,
258 0.3127f, 0.3290f };
259
260static SkColorSpacePrimaries gRec2020Primaries = {
261 0.708f, 0.292f,
262 0.170f, 0.797f,
263 0.131f, 0.046f,
264 0.3127f, 0.3290f };
265
266struct NamedPrimaries {
267 const char* fName;
268 SkColorSpacePrimaries* fPrimaries;
269} gNamedPrimaries[] = {
270 { "sRGB", &gSrgbPrimaries },
271 { "AdobeRGB", &gAdobePrimaries },
272 { "P3", &gP3Primaries },
273 { "Rec. 2020", &gRec2020Primaries },
274};
275
276static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
277 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
278}
279
Brian Osman70d2f432017-11-08 09:54:10 -0500280static Window::BackendType backend_type_for_window(Window::BackendType backendType) {
281 // In raster mode, we still use GL for the window.
282 // This lets us render the GUI faster (and correct).
283 return Window::kRaster_BackendType == backendType ? Window::kNativeGL_BackendType : backendType;
284}
285
Jim Van Verth74826c82019-03-01 14:37:30 -0500286class NullSlide : public Slide {
287 SkISize getDimensions() const override {
288 return SkISize::Make(640, 480);
289 }
290
291 void draw(SkCanvas* canvas) override {
292 canvas->clear(0xffff11ff);
293 }
294};
295
John Stiles31964fd2020-05-05 16:05:47 -0400296static const char kName[] = "name";
297static const char kValue[] = "value";
298static const char kOptions[] = "options";
299static const char kSlideStateName[] = "Slide";
300static const char kBackendStateName[] = "Backend";
301static const char kMSAAStateName[] = "MSAA";
302static const char kPathRendererStateName[] = "Path renderer";
303static const char kSoftkeyStateName[] = "Softkey";
304static const char kSoftkeyHint[] = "Please select a softkey";
305static const char kON[] = "ON";
306static const char kRefreshStateName[] = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700307
Mike Reed862818b2020-03-21 15:07:13 -0400308extern bool gUseSkVMBlitter;
Mike Klein813e8cc2020-08-05 09:33:38 -0500309extern bool gSkVMAllowJIT;
Mike Klein1e0884d2020-04-28 15:04:16 -0500310extern bool gSkVMJITViaDylib;
Mike Reed862818b2020-03-21 15:07:13 -0400311
jvanverth34524262016-05-04 13:49:13 -0700312Viewer::Viewer(int argc, char** argv, void* platformData)
Florin Malitaab99c342018-01-16 16:23:03 -0500313 : fCurrentSlide(-1)
314 , fRefresh(false)
Brian Osman3ac99cf2017-12-01 11:23:53 -0500315 , fSaveToSKP(false)
Mike Reed376d8122019-03-14 11:39:02 -0400316 , fShowSlideDimensions(false)
Brian Osman79086b92017-02-10 13:36:16 -0500317 , fShowImGuiDebugWindow(false)
Brian Osmanfce09c52017-11-14 15:32:20 -0500318 , fShowSlidePicker(false)
Brian Osman79086b92017-02-10 13:36:16 -0500319 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500320 , fShowZoomWindow(false)
Ben Wagner3627d2e2018-06-26 14:23:20 -0400321 , fZoomWindowFixed(false)
322 , fZoomWindowLocation{0.0f, 0.0f}
Brian Osmanf6877092017-02-13 09:39:57 -0500323 , fLastImage(nullptr)
Brian Osmanb63f6002018-07-24 18:01:53 -0400324 , fZoomUI(false)
jvanverth063ece72016-06-17 09:29:14 -0700325 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500326 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500327 , fColorSpacePrimaries(gSrgbPrimaries)
Brian Osmanfdab5762017-11-09 10:27:55 -0500328 // Our UI can only tweak gamma (currently), so start out gamma-only
Brian Osman82ebe042019-01-04 17:03:00 -0500329 , fColorSpaceTransferFn(SkNamedTransferFn::k2Dot2)
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -0500330 , fApplyBackingScale(true)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700331 , fZoomLevel(0.0f)
Ben Wagnerd02a74d2018-04-23 12:55:06 -0400332 , fRotation(0.0f)
Ben Wagner897dfa22018-08-09 15:18:46 -0400333 , fOffset{0.5f, 0.5f}
Brian Osmanb53f48c2017-06-07 10:00:30 -0400334 , fGestureDevice(GestureDevice::kNone)
Brian Osmane9ed0f02018-11-26 14:50:05 -0500335 , fTiled(false)
336 , fDrawTileBoundaries(false)
337 , fTileScale{0.25f, 0.25f}
Brian Osman805a7272018-05-02 15:40:20 -0400338 , fPerspectiveMode(kPerspective_Off)
jvanverthc265a922016-04-08 12:51:45 -0700339{
Greg Daniel285db442016-10-14 09:12:53 -0400340 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700341
Chris Dalton37ae4b02019-12-28 14:51:11 -0700342 gPathRendererNames[GpuPathRenderers::kDefault] = "Default Path Renderers";
Chris Dalton0a22b1e2020-03-26 11:52:15 -0600343 gPathRendererNames[GpuPathRenderers::kTessellation] = "Tessellation";
Brian Osmanf09e35e2017-12-15 14:48:09 -0500344 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Daltonc3318f02019-07-19 14:20:53 -0600345 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "CCPR";
Chris Dalton17dc4182020-03-25 16:18:16 -0600346 gPathRendererNames[GpuPathRenderers::kTriangulating] = "Triangulating";
Brian Osmanf09e35e2017-12-15 14:48:09 -0500347 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
csmartdalton61cd31a2017-02-27 17:00:53 -0700348
jvanverth2bb3b6d2016-04-08 07:24:09 -0700349 SkDebugf("Command line arguments: ");
350 for (int i = 1; i < argc; ++i) {
351 SkDebugf("%s ", argv[i]);
352 }
353 SkDebugf("\n");
354
Mike Klein88544fb2019-03-20 10:50:33 -0500355 CommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500356#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400357 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500358#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700359
Mike Reed862818b2020-03-21 15:07:13 -0400360 gUseSkVMBlitter = FLAGS_skvm;
Mike Klein813e8cc2020-08-05 09:33:38 -0500361 gSkVMAllowJIT = FLAGS_jit;
Mike Klein1e0884d2020-04-28 15:04:16 -0500362 gSkVMJITViaDylib = FLAGS_dylib;
Mike Reed862818b2020-03-21 15:07:13 -0400363
Mike Klein19cc0f62019-03-22 15:30:07 -0500364 ToolUtils::SetDefaultFontMgr();
Ben Wagner483c7722018-02-20 17:06:07 -0500365
Brian Osmanbc8150f2017-07-24 11:38:01 -0400366 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400367 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400368
bsalomon6c471f72016-07-26 12:56:32 -0700369 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700370 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700371
csmartdalton578f0642017-02-24 16:04:47 -0700372 DisplayParams displayParams;
373 displayParams.fMSAASampleCount = FLAGS_msaa;
Jim Van Verthecc91082020-11-20 15:30:25 -0500374 displayParams.fEnableBinaryArchive = FLAGS_binaryarchive;
Chris Dalton040238b2017-12-18 14:22:34 -0700375 SetCtxOptionsFromCommonFlags(&displayParams.fGrContextOptions);
Brian Osman0b8bb882019-04-12 11:47:19 -0400376 displayParams.fGrContextOptions.fPersistentCache = &fPersistentCache;
Brian Osmana66081d2019-09-03 14:59:26 -0400377 displayParams.fGrContextOptions.fShaderCacheStrategy =
378 GrContextOptions::ShaderCacheStrategy::kBackendSource;
Brian Osman5e7fbfd2019-05-03 13:13:35 -0400379 displayParams.fGrContextOptions.fShaderErrorHandler = &gShaderErrorHandler;
380 displayParams.fGrContextOptions.fSuppressPrints = true;
Chris Daltonfd708652021-03-17 21:10:17 -0600381 displayParams.fGrContextOptions.fAlwaysAntialias = FLAGS_dmsaa;
csmartdalton578f0642017-02-24 16:04:47 -0700382 fWindow->setRequestedDisplayParams(displayParams);
Ben Wagnerae4bb982020-09-24 14:49:00 -0400383 fDisplay = fWindow->getRequestedDisplayParams();
Jim Van Verth7b558182019-11-14 16:47:01 -0500384 fRefresh = FLAGS_redraw;
csmartdalton578f0642017-02-24 16:04:47 -0700385
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -0500386 fImGuiLayer.setScaleFactor(fWindow->scaleFactor());
Ben Wagner9a7fcf72021-02-23 13:18:50 -0500387 fStatsLayer.setDisplayScale((fZoomUI ? 2.0f : 1.0f) * fWindow->scaleFactor());
Ben Wagnerfa8b5e42021-01-28 14:30:59 -0500388
Brian Osman56a24812017-12-19 11:15:16 -0500389 // Configure timers
Mike Kleine42af162020-04-29 07:55:53 -0500390 fStatsLayer.setActive(FLAGS_stats);
Brian Osman56a24812017-12-19 11:15:16 -0500391 fAnimateTimer = fStatsLayer.addTimer("Animate", SK_ColorMAGENTA, 0xffff66ff);
392 fPaintTimer = fStatsLayer.addTimer("Paint", SK_ColorGREEN);
393 fFlushTimer = fStatsLayer.addTimer("Flush", SK_ColorRED, 0xffff6666);
394
jvanverth9f372462016-04-06 06:08:59 -0700395 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700396 fCommands.attach(fWindow);
Brian Osman80fc07e2017-12-08 16:45:43 -0500397 fWindow->pushLayer(this);
Brian Osman56a24812017-12-19 11:15:16 -0500398 fWindow->pushLayer(&fStatsLayer);
Brian Osmand67e5182017-12-08 16:46:09 -0500399 fWindow->pushLayer(&fImGuiLayer);
jvanverth9f372462016-04-06 06:08:59 -0700400
brianosman622c8d52016-05-10 06:50:49 -0700401 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500402 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
403 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
404 fWindow->inval();
405 });
Brian Osmanfce09c52017-11-14 15:32:20 -0500406 // Command to jump directly to the slide picker and give it focus
407 fCommands.addCommand('/', "GUI", "Jump to slide picker", [this]() {
408 this->fShowImGuiDebugWindow = true;
409 this->fShowSlidePicker = true;
410 fWindow->inval();
411 });
412 // Alias that to Backspace, to match SampleApp
Hal Canaryb1f411a2019-08-29 10:39:22 -0400413 fCommands.addCommand(skui::Key::kBack, "Backspace", "GUI", "Jump to slide picker", [this]() {
Brian Osmanfce09c52017-11-14 15:32:20 -0500414 this->fShowImGuiDebugWindow = true;
415 this->fShowSlidePicker = true;
416 fWindow->inval();
417 });
Brian Osman79086b92017-02-10 13:36:16 -0500418 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
419 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
420 fWindow->inval();
421 });
Brian Osmanf6877092017-02-13 09:39:57 -0500422 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
423 this->fShowZoomWindow = !this->fShowZoomWindow;
424 fWindow->inval();
425 });
Ben Wagner3627d2e2018-06-26 14:23:20 -0400426 fCommands.addCommand('Z', "GUI", "Toggle zoom window state", [this]() {
427 this->fZoomWindowFixed = !this->fZoomWindowFixed;
428 fWindow->inval();
429 });
Jim Van Verth7c647982020-10-23 12:47:57 -0400430 fCommands.addCommand('v', "Swapchain", "Toggle vsync on/off", [this]() {
Greg Danield0794cc2019-03-27 16:23:26 -0400431 DisplayParams params = fWindow->getRequestedDisplayParams();
432 params.fDisableVsync = !params.fDisableVsync;
433 fWindow->setRequestedDisplayParams(params);
434 this->updateTitle();
435 fWindow->inval();
436 });
Jim Van Verth7c647982020-10-23 12:47:57 -0400437 fCommands.addCommand('V', "Swapchain", "Toggle delayed acquire on/off (Metal only)", [this]() {
438 DisplayParams params = fWindow->getRequestedDisplayParams();
439 params.fDelayDrawableAcquisition = !params.fDelayDrawableAcquisition;
440 fWindow->setRequestedDisplayParams(params);
441 this->updateTitle();
442 fWindow->inval();
443 });
Mike Reedf702ed42019-07-22 17:00:49 -0400444 fCommands.addCommand('r', "Redraw", "Toggle redraw", [this]() {
445 fRefresh = !fRefresh;
446 fWindow->inval();
447 });
brianosman622c8d52016-05-10 06:50:49 -0700448 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
Brian Osman56a24812017-12-19 11:15:16 -0500449 fStatsLayer.setActive(!fStatsLayer.getActive());
brianosman622c8d52016-05-10 06:50:49 -0700450 fWindow->inval();
451 });
Jim Van Verth90dcce52017-11-03 13:36:07 -0400452 fCommands.addCommand('0', "Overlays", "Reset stats", [this]() {
Brian Osman56a24812017-12-19 11:15:16 -0500453 fStatsLayer.resetMeasurements();
Jim Van Verth90dcce52017-11-03 13:36:07 -0400454 this->updateTitle();
455 fWindow->inval();
456 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500457 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500458 switch (fColorMode) {
459 case ColorMode::kLegacy:
Brian Osman03115dc2018-11-26 13:55:19 -0500460 this->setColorMode(ColorMode::kColorManaged8888);
Brian Osman92004802017-03-06 11:47:26 -0500461 break;
Brian Osman03115dc2018-11-26 13:55:19 -0500462 case ColorMode::kColorManaged8888:
463 this->setColorMode(ColorMode::kColorManagedF16);
Brian Osman92004802017-03-06 11:47:26 -0500464 break;
Brian Osman03115dc2018-11-26 13:55:19 -0500465 case ColorMode::kColorManagedF16:
Brian Salomon8391bac2019-09-18 11:22:44 -0400466 this->setColorMode(ColorMode::kColorManagedF16Norm);
467 break;
468 case ColorMode::kColorManagedF16Norm:
Brian Osman92004802017-03-06 11:47:26 -0500469 this->setColorMode(ColorMode::kLegacy);
470 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500471 }
brianosman622c8d52016-05-10 06:50:49 -0700472 });
Chris Dalton1215cda2019-12-17 21:44:04 -0700473 fCommands.addCommand('w', "Modes", "Toggle wireframe", [this]() {
474 DisplayParams params = fWindow->getRequestedDisplayParams();
475 params.fGrContextOptions.fWireframeMode = !params.fGrContextOptions.fWireframeMode;
476 fWindow->setRequestedDisplayParams(params);
477 fWindow->inval();
478 });
Hal Canaryb1f411a2019-08-29 10:39:22 -0400479 fCommands.addCommand(skui::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
Florin Malitaab99c342018-01-16 16:23:03 -0500480 this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ? fCurrentSlide + 1 : 0);
brianosman622c8d52016-05-10 06:50:49 -0700481 });
Hal Canaryb1f411a2019-08-29 10:39:22 -0400482 fCommands.addCommand(skui::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
Florin Malitaab99c342018-01-16 16:23:03 -0500483 this->setCurrentSlide(fCurrentSlide > 0 ? fCurrentSlide - 1 : fSlides.count() - 1);
brianosman622c8d52016-05-10 06:50:49 -0700484 });
Hal Canaryb1f411a2019-08-29 10:39:22 -0400485 fCommands.addCommand(skui::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
brianosman622c8d52016-05-10 06:50:49 -0700486 this->changeZoomLevel(1.f / 32.f);
487 fWindow->inval();
488 });
Hal Canaryb1f411a2019-08-29 10:39:22 -0400489 fCommands.addCommand(skui::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
brianosman622c8d52016-05-10 06:50:49 -0700490 this->changeZoomLevel(-1.f / 32.f);
491 fWindow->inval();
492 });
jvanverthaf236b52016-05-20 06:01:06 -0700493 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400494 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
495 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500496 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400497#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
498 if (newBackend == sk_app::Window::kVulkan_BackendType) {
499 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
500 sk_app::Window::kBackendTypeCount);
501 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
502 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500503 }
504#endif
Brian Osman621491e2017-02-28 15:45:01 -0500505 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700506 });
Brian Osman3ac99cf2017-12-01 11:23:53 -0500507 fCommands.addCommand('K', "IO", "Save slide to SKP", [this]() {
508 fSaveToSKP = true;
509 fWindow->inval();
510 });
Mike Reed376d8122019-03-14 11:39:02 -0400511 fCommands.addCommand('&', "Overlays", "Show slide dimensios", [this]() {
512 fShowSlideDimensions = !fShowSlideDimensions;
513 fWindow->inval();
514 });
Ben Wagner37c54032018-04-13 14:30:23 -0400515 fCommands.addCommand('G', "Modes", "Geometry", [this]() {
516 DisplayParams params = fWindow->getRequestedDisplayParams();
517 uint32_t flags = params.fSurfaceProps.flags();
Ben Wagnerae4bb982020-09-24 14:49:00 -0400518 SkPixelGeometry defaultPixelGeometry = fDisplay.fSurfaceProps.pixelGeometry();
519 if (!fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
520 fDisplayOverrides.fSurfaceProps.fPixelGeometry = true;
Ben Wagner37c54032018-04-13 14:30:23 -0400521 params.fSurfaceProps = SkSurfaceProps(flags, kUnknown_SkPixelGeometry);
522 } else {
523 switch (params.fSurfaceProps.pixelGeometry()) {
524 case kUnknown_SkPixelGeometry:
525 params.fSurfaceProps = SkSurfaceProps(flags, kRGB_H_SkPixelGeometry);
526 break;
527 case kRGB_H_SkPixelGeometry:
528 params.fSurfaceProps = SkSurfaceProps(flags, kBGR_H_SkPixelGeometry);
529 break;
530 case kBGR_H_SkPixelGeometry:
531 params.fSurfaceProps = SkSurfaceProps(flags, kRGB_V_SkPixelGeometry);
532 break;
533 case kRGB_V_SkPixelGeometry:
534 params.fSurfaceProps = SkSurfaceProps(flags, kBGR_V_SkPixelGeometry);
535 break;
536 case kBGR_V_SkPixelGeometry:
Ben Wagnerae4bb982020-09-24 14:49:00 -0400537 params.fSurfaceProps = SkSurfaceProps(flags, defaultPixelGeometry);
538 fDisplayOverrides.fSurfaceProps.fPixelGeometry = false;
Ben Wagner37c54032018-04-13 14:30:23 -0400539 break;
540 }
541 }
542 fWindow->setRequestedDisplayParams(params);
543 this->updateTitle();
544 fWindow->inval();
545 });
Ben Wagner9613e452019-01-23 10:34:59 -0500546 fCommands.addCommand('H', "Font", "Hinting mode", [this]() {
Mike Reed3ae47332019-01-04 10:11:46 -0500547 if (!fFontOverrides.fHinting) {
548 fFontOverrides.fHinting = true;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400549 fFont.setHinting(SkFontHinting::kNone);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500550 } else {
Mike Reed3ae47332019-01-04 10:11:46 -0500551 switch (fFont.getHinting()) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400552 case SkFontHinting::kNone:
553 fFont.setHinting(SkFontHinting::kSlight);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500554 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400555 case SkFontHinting::kSlight:
556 fFont.setHinting(SkFontHinting::kNormal);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500557 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400558 case SkFontHinting::kNormal:
559 fFont.setHinting(SkFontHinting::kFull);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500560 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400561 case SkFontHinting::kFull:
562 fFont.setHinting(SkFontHinting::kNone);
Mike Reed3ae47332019-01-04 10:11:46 -0500563 fFontOverrides.fHinting = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500564 break;
565 }
566 }
567 this->updateTitle();
568 fWindow->inval();
569 });
570 fCommands.addCommand('A', "Paint", "Antialias Mode", [this]() {
Ben Wagner9613e452019-01-23 10:34:59 -0500571 if (!fPaintOverrides.fAntiAlias) {
572 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
573 fPaintOverrides.fAntiAlias = true;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500574 fPaint.setAntiAlias(false);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500575 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500576 } else {
577 fPaint.setAntiAlias(true);
Ben Wagner9613e452019-01-23 10:34:59 -0500578 switch (fPaintOverrides.fAntiAliasState) {
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500579 case SkPaintFields::AntiAliasState::Alias:
Ben Wagner9613e452019-01-23 10:34:59 -0500580 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Normal;
Ben Wagnera580fb32018-04-17 11:16:32 -0400581 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500582 break;
583 case SkPaintFields::AntiAliasState::Normal:
Ben Wagner9613e452019-01-23 10:34:59 -0500584 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::AnalyticAAEnabled;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500585 gSkUseAnalyticAA = true;
Ben Wagnera580fb32018-04-17 11:16:32 -0400586 gSkForceAnalyticAA = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500587 break;
588 case SkPaintFields::AntiAliasState::AnalyticAAEnabled:
Ben Wagner9613e452019-01-23 10:34:59 -0500589 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::AnalyticAAForced;
Ben Wagnera580fb32018-04-17 11:16:32 -0400590 gSkUseAnalyticAA = gSkForceAnalyticAA = true;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500591 break;
592 case SkPaintFields::AntiAliasState::AnalyticAAForced:
Ben Wagner9613e452019-01-23 10:34:59 -0500593 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
594 fPaintOverrides.fAntiAlias = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500595 gSkUseAnalyticAA = fPaintOverrides.fOriginalSkUseAnalyticAA;
596 gSkForceAnalyticAA = fPaintOverrides.fOriginalSkForceAnalyticAA;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500597 break;
598 }
599 }
600 this->updateTitle();
601 fWindow->inval();
602 });
Ben Wagner37c54032018-04-13 14:30:23 -0400603 fCommands.addCommand('D', "Modes", "DFT", [this]() {
604 DisplayParams params = fWindow->getRequestedDisplayParams();
605 uint32_t flags = params.fSurfaceProps.flags();
606 flags ^= SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
607 params.fSurfaceProps = SkSurfaceProps(flags, params.fSurfaceProps.pixelGeometry());
608 fWindow->setRequestedDisplayParams(params);
609 this->updateTitle();
610 fWindow->inval();
611 });
Ben Wagner9613e452019-01-23 10:34:59 -0500612 fCommands.addCommand('L', "Font", "Subpixel Antialias Mode", [this]() {
Mike Reede5f9cfa2019-01-10 13:55:35 -0500613 if (!fFontOverrides.fEdging) {
614 fFontOverrides.fEdging = true;
615 fFont.setEdging(SkFont::Edging::kAlias);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500616 } else {
Mike Reede5f9cfa2019-01-10 13:55:35 -0500617 switch (fFont.getEdging()) {
618 case SkFont::Edging::kAlias:
619 fFont.setEdging(SkFont::Edging::kAntiAlias);
620 break;
621 case SkFont::Edging::kAntiAlias:
622 fFont.setEdging(SkFont::Edging::kSubpixelAntiAlias);
623 break;
624 case SkFont::Edging::kSubpixelAntiAlias:
625 fFont.setEdging(SkFont::Edging::kAlias);
626 fFontOverrides.fEdging = false;
627 break;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500628 }
629 }
630 this->updateTitle();
631 fWindow->inval();
632 });
Ben Wagner9613e452019-01-23 10:34:59 -0500633 fCommands.addCommand('S', "Font", "Subpixel Position Mode", [this]() {
Mike Reede5f9cfa2019-01-10 13:55:35 -0500634 if (!fFontOverrides.fSubpixel) {
635 fFontOverrides.fSubpixel = true;
636 fFont.setSubpixel(false);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500637 } else {
Mike Reede5f9cfa2019-01-10 13:55:35 -0500638 if (!fFont.isSubpixel()) {
639 fFont.setSubpixel(true);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500640 } else {
Mike Reede5f9cfa2019-01-10 13:55:35 -0500641 fFontOverrides.fSubpixel = false;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500642 }
643 }
644 this->updateTitle();
645 fWindow->inval();
646 });
Ben Wagner54aa8842019-08-27 16:20:39 -0400647 fCommands.addCommand('B', "Font", "Baseline Snapping", [this]() {
648 if (!fFontOverrides.fBaselineSnap) {
649 fFontOverrides.fBaselineSnap = true;
650 fFont.setBaselineSnap(false);
651 } else {
652 if (!fFont.isBaselineSnap()) {
653 fFont.setBaselineSnap(true);
654 } else {
655 fFontOverrides.fBaselineSnap = false;
656 }
657 }
658 this->updateTitle();
659 fWindow->inval();
660 });
Brian Osman805a7272018-05-02 15:40:20 -0400661 fCommands.addCommand('p', "Transform", "Toggle Perspective Mode", [this]() {
662 fPerspectiveMode = (kPerspective_Real == fPerspectiveMode) ? kPerspective_Fake
663 : kPerspective_Real;
664 this->updateTitle();
665 fWindow->inval();
666 });
667 fCommands.addCommand('P', "Transform", "Toggle Perspective", [this]() {
668 fPerspectiveMode = (kPerspective_Off == fPerspectiveMode) ? kPerspective_Real
669 : kPerspective_Off;
670 this->updateTitle();
671 fWindow->inval();
672 });
Brian Osman207d4102019-01-10 09:40:58 -0500673 fCommands.addCommand('a', "Transform", "Toggle Animation", [this]() {
674 fAnimTimer.togglePauseResume();
675 });
Brian Osmanb63f6002018-07-24 18:01:53 -0400676 fCommands.addCommand('u', "GUI", "Zoom UI", [this]() {
677 fZoomUI = !fZoomUI;
Ben Wagner9a7fcf72021-02-23 13:18:50 -0500678 fStatsLayer.setDisplayScale((fZoomUI ? 2.0f : 1.0f) * fWindow->scaleFactor());
Brian Osmanb63f6002018-07-24 18:01:53 -0400679 fWindow->inval();
680 });
Mike Reed59295352020-03-12 13:56:34 -0400681 fCommands.addCommand('$', "ViaSerialize", "Toggle ViaSerialize", [this]() {
682 fDrawViaSerialize = !fDrawViaSerialize;
683 this->updateTitle();
684 fWindow->inval();
685 });
Mike Klein813e8cc2020-08-05 09:33:38 -0500686 fCommands.addCommand('!', "SkVM", "Toggle SkVM blitter", [this]() {
Mike Reed862818b2020-03-21 15:07:13 -0400687 gUseSkVMBlitter = !gUseSkVMBlitter;
688 this->updateTitle();
689 fWindow->inval();
690 });
Mike Klein813e8cc2020-08-05 09:33:38 -0500691 fCommands.addCommand('@', "SkVM", "Toggle SkVM JIT", [this]() {
692 gSkVMAllowJIT = !gSkVMAllowJIT;
693 this->updateTitle();
694 fWindow->inval();
695 });
Yuqian Lib2ba6642017-11-22 12:07:41 -0500696
jvanverth2bb3b6d2016-04-08 07:24:09 -0700697 // set up slides
698 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500699 if (FLAGS_list) {
700 this->listNames();
701 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700702
Brian Osman9bb47cf2018-04-26 15:55:00 -0400703 fPerspectivePoints[0].set(0, 0);
704 fPerspectivePoints[1].set(1, 0);
705 fPerspectivePoints[2].set(0, 1);
706 fPerspectivePoints[3].set(1, 1);
djsollen12d62a72016-04-21 07:59:44 -0700707 fAnimTimer.run();
708
Hal Canaryc465d132017-12-08 10:21:31 -0500709 auto gamutImage = GetResourceAsImage("images/gamut.png");
Brian Osmana109e392017-02-24 09:49:14 -0500710 if (gamutImage) {
Mike Reed5ec22382021-01-14 21:59:01 -0500711 fImGuiGamutPaint.setShader(gamutImage->makeShader(SkSamplingOptions(SkFilterMode::kLinear)));
Brian Osmana109e392017-02-24 09:49:14 -0500712 }
713 fImGuiGamutPaint.setColor(SK_ColorWHITE);
Brian Osmana109e392017-02-24 09:49:14 -0500714
jongdeok.kim804f17e2019-02-26 14:39:23 +0900715 fWindow->attach(backend_type_for_window(fBackendType));
Jim Van Verth74826c82019-03-01 14:37:30 -0500716 this->setCurrentSlide(this->startupSlide());
jvanverth9f372462016-04-06 06:08:59 -0700717}
718
jvanverth34524262016-05-04 13:49:13 -0700719void Viewer::initSlides() {
Florin Malita0ffa3222018-04-05 14:34:45 -0400720 using SlideFactory = sk_sp<Slide>(*)(const SkString& name, const SkString& path);
721 static const struct {
722 const char* fExtension;
723 const char* fDirName;
Mike Klein88544fb2019-03-20 10:50:33 -0500724 const CommandLineFlags::StringArray& fFlags;
Florin Malita0ffa3222018-04-05 14:34:45 -0400725 const SlideFactory fFactory;
726 } gExternalSlidesInfo[] = {
727 { ".skp", "skp-dir", FLAGS_skps,
728 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
729 return sk_make_sp<SKPSlide>(name, path);}
730 },
731 { ".jpg", "jpg-dir", FLAGS_jpgs,
732 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
733 return sk_make_sp<ImageSlide>(name, path);}
734 },
Florin Malita87ccf332018-05-04 12:23:24 -0400735#if defined(SK_ENABLE_SKOTTIE)
Eric Boren8c172ba2018-07-19 13:27:49 -0400736 { ".json", "skottie-dir", FLAGS_lotties,
Florin Malita0ffa3222018-04-05 14:34:45 -0400737 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
738 return sk_make_sp<SkottieSlide>(name, path);}
739 },
Florin Malita87ccf332018-05-04 12:23:24 -0400740#endif
Florin Malita45cd2002020-06-09 14:00:54 -0400741 #if defined(SK_ENABLE_SKRIVE)
742 { ".flr", "skrive-dir", FLAGS_rives,
743 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
744 return sk_make_sp<SkRiveSlide>(name, path);}
745 },
746 #endif
Florin Malita5d3ff432018-07-31 16:38:43 -0400747#if defined(SK_XML)
Florin Malita0ffa3222018-04-05 14:34:45 -0400748 { ".svg", "svg-dir", FLAGS_svgs,
749 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
750 return sk_make_sp<SvgSlide>(name, path);}
751 },
Florin Malita5d3ff432018-07-31 16:38:43 -0400752#endif
Florin Malita0ffa3222018-04-05 14:34:45 -0400753 };
jvanverthc265a922016-04-08 12:51:45 -0700754
Brian Salomon343553a2018-09-05 15:41:23 -0400755 SkTArray<sk_sp<Slide>> dirSlides;
jvanverthc265a922016-04-08 12:51:45 -0700756
Mike Klein88544fb2019-03-20 10:50:33 -0500757 const auto addSlide =
758 [&](const SkString& name, const SkString& path, const SlideFactory& fact) {
759 if (CommandLineFlags::ShouldSkip(FLAGS_match, name.c_str())) {
760 return;
761 }
liyuqian6f163d22016-06-13 12:26:45 -0700762
Mike Klein88544fb2019-03-20 10:50:33 -0500763 if (auto slide = fact(name, path)) {
764 dirSlides.push_back(slide);
765 fSlides.push_back(std::move(slide));
766 }
767 };
Florin Malita76a076b2018-02-15 18:40:48 -0500768
Florin Malita38792ce2018-05-08 10:36:18 -0400769 if (!FLAGS_file.isEmpty()) {
770 // single file mode
771 const SkString file(FLAGS_file[0]);
772
773 if (sk_exists(file.c_str(), kRead_SkFILE_Flag)) {
774 for (const auto& sinfo : gExternalSlidesInfo) {
775 if (file.endsWith(sinfo.fExtension)) {
776 addSlide(SkOSPath::Basename(file.c_str()), file, sinfo.fFactory);
777 return;
778 }
779 }
780
781 fprintf(stderr, "Unsupported file type \"%s\"\n", file.c_str());
782 } else {
783 fprintf(stderr, "Cannot read \"%s\"\n", file.c_str());
784 }
785
786 return;
787 }
788
789 // Bisect slide.
790 if (!FLAGS_bisect.isEmpty()) {
791 sk_sp<BisectSlide> bisect = BisectSlide::Create(FLAGS_bisect[0]);
Mike Klein88544fb2019-03-20 10:50:33 -0500792 if (bisect && !CommandLineFlags::ShouldSkip(FLAGS_match, bisect->getName().c_str())) {
Florin Malita38792ce2018-05-08 10:36:18 -0400793 if (FLAGS_bisect.count() >= 2) {
794 for (const char* ch = FLAGS_bisect[1]; *ch; ++ch) {
795 bisect->onChar(*ch);
796 }
797 }
798 fSlides.push_back(std::move(bisect));
799 }
800 }
801
802 // GMs
803 int firstGM = fSlides.count();
Hal Canary972eba32018-07-30 17:07:07 -0400804 for (skiagm::GMFactory gmFactory : skiagm::GMRegistry::Range()) {
Ben Wagner406ff502019-08-12 16:39:24 -0400805 std::unique_ptr<skiagm::GM> gm = gmFactory();
Mike Klein88544fb2019-03-20 10:50:33 -0500806 if (!CommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
Ben Wagner406ff502019-08-12 16:39:24 -0400807 sk_sp<Slide> slide(new GMSlide(std::move(gm)));
Florin Malita38792ce2018-05-08 10:36:18 -0400808 fSlides.push_back(std::move(slide));
809 }
Florin Malita38792ce2018-05-08 10:36:18 -0400810 }
811 // reverse gms
812 int numGMs = fSlides.count() - firstGM;
813 for (int i = 0; i < numGMs/2; ++i) {
814 std::swap(fSlides[firstGM + i], fSlides[fSlides.count() - i - 1]);
815 }
816
817 // samples
Ben Wagnerb2c4ea62018-08-08 11:36:17 -0400818 for (const SampleFactory factory : SampleRegistry::Range()) {
819 sk_sp<Slide> slide(new SampleSlide(factory));
Mike Klein88544fb2019-03-20 10:50:33 -0500820 if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
Florin Malita38792ce2018-05-08 10:36:18 -0400821 fSlides.push_back(slide);
822 }
Florin Malita38792ce2018-05-08 10:36:18 -0400823 }
824
Brian Osman7c979f52019-02-12 13:27:51 -0500825 // Particle demo
826 {
827 // TODO: Convert this to a sample
828 sk_sp<Slide> slide(new ParticlesSlide());
Mike Klein88544fb2019-03-20 10:50:33 -0500829 if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
Brian Osman7c979f52019-02-12 13:27:51 -0500830 fSlides.push_back(std::move(slide));
831 }
832 }
833
Brian Osmand927bd22019-12-18 11:23:12 -0500834 // Runtime shader editor
835 {
836 sk_sp<Slide> slide(new SkSLSlide());
837 if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
838 fSlides.push_back(std::move(slide));
839 }
840 }
841
Florin Malita0ffa3222018-04-05 14:34:45 -0400842 for (const auto& info : gExternalSlidesInfo) {
843 for (const auto& flag : info.fFlags) {
844 if (SkStrEndsWith(flag.c_str(), info.fExtension)) {
845 // single file
846 addSlide(SkOSPath::Basename(flag.c_str()), flag, info.fFactory);
847 } else {
848 // directory
Florin Malita0ffa3222018-04-05 14:34:45 -0400849 SkString name;
Tyler Denniston31dc4812020-04-09 11:17:21 -0400850 SkTArray<SkString> sortedFilenames;
851 SkOSFile::Iter it(flag.c_str(), info.fExtension);
Florin Malita0ffa3222018-04-05 14:34:45 -0400852 while (it.next(&name)) {
Tyler Denniston31dc4812020-04-09 11:17:21 -0400853 sortedFilenames.push_back(name);
854 }
855 if (sortedFilenames.count()) {
John Stiles886a9042020-07-14 16:28:33 -0400856 SkTQSort(sortedFilenames.begin(), sortedFilenames.end(),
John Stiles6e9ead92020-07-14 00:13:51 +0000857 [](const SkString& a, const SkString& b) {
858 return strcmp(a.c_str(), b.c_str()) < 0;
859 });
Tyler Denniston31dc4812020-04-09 11:17:21 -0400860 }
861 for (const SkString& filename : sortedFilenames) {
862 addSlide(filename, SkOSPath::Join(flag.c_str(), filename.c_str()),
863 info.fFactory);
Florin Malita0ffa3222018-04-05 14:34:45 -0400864 }
Florin Malitac659c2c2018-04-05 11:57:21 -0400865 }
Florin Malita0ffa3222018-04-05 14:34:45 -0400866 if (!dirSlides.empty()) {
867 fSlides.push_back(
868 sk_make_sp<SlideDir>(SkStringPrintf("%s[%s]", info.fDirName, flag.c_str()),
869 std::move(dirSlides)));
Mike Klein16885072018-12-11 09:54:31 -0500870 dirSlides.reset(); // NOLINT(bugprone-use-after-move)
Florin Malita0ffa3222018-04-05 14:34:45 -0400871 }
Florin Malitac659c2c2018-04-05 11:57:21 -0400872 }
873 }
Jim Van Verth74826c82019-03-01 14:37:30 -0500874
875 if (!fSlides.count()) {
876 sk_sp<Slide> slide(new NullSlide());
877 fSlides.push_back(std::move(slide));
878 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700879}
880
881
jvanverth34524262016-05-04 13:49:13 -0700882Viewer::~Viewer() {
Robert Phillipse9229532020-06-26 10:10:49 -0400883 for(auto& slide : fSlides) {
884 slide->gpuTeardown();
885 }
886
jvanverth9f372462016-04-06 06:08:59 -0700887 fWindow->detach();
888 delete fWindow;
889}
890
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500891struct SkPaintTitleUpdater {
892 SkPaintTitleUpdater(SkString* title) : fTitle(title), fCount(0) {}
893 void append(const char* s) {
894 if (fCount == 0) {
895 fTitle->append(" {");
896 } else {
897 fTitle->append(", ");
898 }
899 fTitle->append(s);
900 ++fCount;
901 }
902 void done() {
903 if (fCount > 0) {
904 fTitle->append("}");
905 }
906 }
907 SkString* fTitle;
908 int fCount;
909};
910
brianosman05de2162016-05-06 13:28:57 -0700911void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700912 if (!fWindow) {
913 return;
914 }
Brian Salomonbdecacf2018-02-02 20:32:49 -0500915 if (fWindow->sampleCount() < 1) {
csmartdalton578f0642017-02-24 16:04:47 -0700916 return; // Surface hasn't been created yet.
917 }
918
jvanverth34524262016-05-04 13:49:13 -0700919 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700920 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700921
Mike Kleine5acd752019-03-22 09:57:16 -0500922 if (gSkUseAnalyticAA) {
Yuqian Li399b3c22017-08-03 11:08:15 -0400923 if (gSkForceAnalyticAA) {
924 title.append(" <FAAA>");
925 } else {
926 title.append(" <AAA>");
927 }
928 }
Mike Reed59295352020-03-12 13:56:34 -0400929 if (fDrawViaSerialize) {
930 title.append(" <serialize>");
931 }
Mike Reed862818b2020-03-21 15:07:13 -0400932 if (gUseSkVMBlitter) {
Mike Klein813e8cc2020-08-05 09:33:38 -0500933 title.append(" <SkVMBlitter>");
934 }
935 if (!gSkVMAllowJIT) {
936 title.append(" <SkVM interpreter>");
Mike Reed862818b2020-03-21 15:07:13 -0400937 }
Yuqian Li399b3c22017-08-03 11:08:15 -0400938
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500939 SkPaintTitleUpdater paintTitle(&title);
Ben Wagner9613e452019-01-23 10:34:59 -0500940 auto paintFlag = [this, &paintTitle](bool SkPaintFields::* flag,
941 bool (SkPaint::* isFlag)() const,
Ben Wagner99a78dc2018-05-09 18:23:51 -0400942 const char* on, const char* off)
943 {
Ben Wagner9613e452019-01-23 10:34:59 -0500944 if (fPaintOverrides.*flag) {
Ben Wagner99a78dc2018-05-09 18:23:51 -0400945 paintTitle.append((fPaint.*isFlag)() ? on : off);
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500946 }
Ben Wagner99a78dc2018-05-09 18:23:51 -0400947 };
948
Ben Wagner9613e452019-01-23 10:34:59 -0500949 auto fontFlag = [this, &paintTitle](bool SkFontFields::* flag, bool (SkFont::* isFlag)() const,
950 const char* on, const char* off)
951 {
952 if (fFontOverrides.*flag) {
953 paintTitle.append((fFont.*isFlag)() ? on : off);
954 }
955 };
956
957 paintFlag(&SkPaintFields::fAntiAlias, &SkPaint::isAntiAlias, "Antialias", "Alias");
958 paintFlag(&SkPaintFields::fDither, &SkPaint::isDither, "DITHER", "No Dither");
959
960 fontFlag(&SkFontFields::fForceAutoHinting, &SkFont::isForceAutoHinting,
961 "Force Autohint", "No Force Autohint");
962 fontFlag(&SkFontFields::fEmbolden, &SkFont::isEmbolden, "Fake Bold", "No Fake Bold");
Ben Wagnerc17de1d2019-08-26 16:59:09 -0400963 fontFlag(&SkFontFields::fBaselineSnap, &SkFont::isBaselineSnap, "BaseSnap", "No BaseSnap");
Ben Wagner9613e452019-01-23 10:34:59 -0500964 fontFlag(&SkFontFields::fLinearMetrics, &SkFont::isLinearMetrics,
965 "Linear Metrics", "Non-Linear Metrics");
966 fontFlag(&SkFontFields::fEmbeddedBitmaps, &SkFont::isEmbeddedBitmaps,
967 "Bitmap Text", "No Bitmap Text");
968 fontFlag(&SkFontFields::fSubpixel, &SkFont::isSubpixel, "Subpixel Text", "Pixel Text");
969
970 if (fFontOverrides.fEdging) {
971 switch (fFont.getEdging()) {
972 case SkFont::Edging::kAlias:
973 paintTitle.append("Alias Text");
974 break;
975 case SkFont::Edging::kAntiAlias:
976 paintTitle.append("Antialias Text");
977 break;
978 case SkFont::Edging::kSubpixelAntiAlias:
979 paintTitle.append("Subpixel Antialias Text");
980 break;
981 }
982 }
Ben Wagner99a78dc2018-05-09 18:23:51 -0400983
Mike Reed3ae47332019-01-04 10:11:46 -0500984 if (fFontOverrides.fHinting) {
985 switch (fFont.getHinting()) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400986 case SkFontHinting::kNone:
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500987 paintTitle.append("No Hinting");
988 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400989 case SkFontHinting::kSlight:
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500990 paintTitle.append("Slight Hinting");
991 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400992 case SkFontHinting::kNormal:
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500993 paintTitle.append("Normal Hinting");
994 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400995 case SkFontHinting::kFull:
Ben Wagnerabdcc5f2018-02-12 16:37:28 -0500996 paintTitle.append("Full Hinting");
997 break;
998 }
999 }
1000 paintTitle.done();
1001
Brian Osman92004802017-03-06 11:47:26 -05001002 switch (fColorMode) {
1003 case ColorMode::kLegacy:
1004 title.append(" Legacy 8888");
1005 break;
Brian Osman03115dc2018-11-26 13:55:19 -05001006 case ColorMode::kColorManaged8888:
Brian Osman92004802017-03-06 11:47:26 -05001007 title.append(" ColorManaged 8888");
1008 break;
Brian Osman03115dc2018-11-26 13:55:19 -05001009 case ColorMode::kColorManagedF16:
Brian Osman92004802017-03-06 11:47:26 -05001010 title.append(" ColorManaged F16");
1011 break;
Brian Salomon8391bac2019-09-18 11:22:44 -04001012 case ColorMode::kColorManagedF16Norm:
1013 title.append(" ColorManaged F16 Norm");
1014 break;
Brian Osman92004802017-03-06 11:47:26 -05001015 }
Brian Osmanf750fbc2017-02-08 10:47:28 -05001016
Brian Osman92004802017-03-06 11:47:26 -05001017 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -05001018 int curPrimaries = -1;
1019 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1020 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1021 curPrimaries = i;
1022 break;
1023 }
1024 }
Brian Osman03115dc2018-11-26 13:55:19 -05001025 title.appendf(" %s Gamma %f",
1026 curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom",
Brian Osman82ebe042019-01-04 17:03:00 -05001027 fColorSpaceTransferFn.g);
brianosman05de2162016-05-06 13:28:57 -07001028 }
Brian Osmanf750fbc2017-02-08 10:47:28 -05001029
Ben Wagner37c54032018-04-13 14:30:23 -04001030 const DisplayParams& params = fWindow->getRequestedDisplayParams();
Ben Wagnerae4bb982020-09-24 14:49:00 -04001031 if (fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
Ben Wagner37c54032018-04-13 14:30:23 -04001032 switch (params.fSurfaceProps.pixelGeometry()) {
1033 case kUnknown_SkPixelGeometry:
1034 title.append( " Flat");
1035 break;
1036 case kRGB_H_SkPixelGeometry:
1037 title.append( " RGB");
1038 break;
1039 case kBGR_H_SkPixelGeometry:
1040 title.append( " BGR");
1041 break;
1042 case kRGB_V_SkPixelGeometry:
1043 title.append( " RGBV");
1044 break;
1045 case kBGR_V_SkPixelGeometry:
1046 title.append( " BGRV");
1047 break;
1048 }
1049 }
1050
1051 if (params.fSurfaceProps.isUseDeviceIndependentFonts()) {
1052 title.append(" DFT");
1053 }
1054
csmartdalton578f0642017-02-24 16:04:47 -07001055 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -07001056 title.append(kBackendTypeStrings[fBackendType]);
Brian Salomonbdecacf2018-02-02 20:32:49 -05001057 int msaa = fWindow->sampleCount();
1058 if (msaa > 1) {
csmartdalton578f0642017-02-24 16:04:47 -07001059 title.appendf(" MSAA: %i", msaa);
1060 }
1061 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -07001062
1063 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Chris Dalton37ae4b02019-12-28 14:51:11 -07001064 if (GpuPathRenderers::kDefault != pr) {
csmartdalton61cd31a2017-02-27 17:00:53 -07001065 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
1066 }
1067
Brian Osman805a7272018-05-02 15:40:20 -04001068 if (kPerspective_Real == fPerspectiveMode) {
1069 title.append(" Perpsective (Real)");
1070 } else if (kPerspective_Fake == fPerspectiveMode) {
1071 title.append(" Perspective (Fake)");
1072 }
1073
brianosman05de2162016-05-06 13:28:57 -07001074 fWindow->setTitle(title.c_str());
1075}
1076
Florin Malitaab99c342018-01-16 16:23:03 -05001077int Viewer::startupSlide() const {
Jim Van Verth6f449692017-02-14 15:16:46 -05001078
1079 if (!FLAGS_slide.isEmpty()) {
1080 int count = fSlides.count();
1081 for (int i = 0; i < count; i++) {
1082 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
Florin Malitaab99c342018-01-16 16:23:03 -05001083 return i;
Jim Van Verth6f449692017-02-14 15:16:46 -05001084 }
1085 }
1086
1087 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
1088 this->listNames();
1089 }
1090
Florin Malitaab99c342018-01-16 16:23:03 -05001091 return 0;
Jim Van Verth6f449692017-02-14 15:16:46 -05001092}
1093
Florin Malitaab99c342018-01-16 16:23:03 -05001094void Viewer::listNames() const {
Jim Van Verth6f449692017-02-14 15:16:46 -05001095 SkDebugf("All Slides:\n");
Florin Malitaab99c342018-01-16 16:23:03 -05001096 for (const auto& slide : fSlides) {
1097 SkDebugf(" %s\n", slide->getName().c_str());
Jim Van Verth6f449692017-02-14 15:16:46 -05001098 }
1099}
1100
Florin Malitaab99c342018-01-16 16:23:03 -05001101void Viewer::setCurrentSlide(int slide) {
1102 SkASSERT(slide >= 0 && slide < fSlides.count());
liyuqian6f163d22016-06-13 12:26:45 -07001103
Florin Malitaab99c342018-01-16 16:23:03 -05001104 if (slide == fCurrentSlide) {
1105 return;
1106 }
1107
1108 if (fCurrentSlide >= 0) {
1109 fSlides[fCurrentSlide]->unload();
1110 }
1111
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -05001112 SkScalar scaleFactor = 1.0;
1113 if (fApplyBackingScale) {
1114 scaleFactor = fWindow->scaleFactor();
1115 }
1116 fSlides[slide]->load(SkIntToScalar(fWindow->width()) / scaleFactor,
1117 SkIntToScalar(fWindow->height()) / scaleFactor);
Florin Malitaab99c342018-01-16 16:23:03 -05001118 fCurrentSlide = slide;
1119 this->setupCurrentSlide();
1120}
1121
1122void Viewer::setupCurrentSlide() {
Jim Van Verth0848fb02018-01-22 13:39:30 -05001123 if (fCurrentSlide >= 0) {
1124 // prepare dimensions for image slides
1125 fGesture.resetTouchState();
1126 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -07001127
Jim Van Verth0848fb02018-01-22 13:39:30 -05001128 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1129 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
1130 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
Brian Osman42bb6ac2017-06-05 08:46:04 -04001131
Jim Van Verth0848fb02018-01-22 13:39:30 -05001132 // Start with a matrix that scales the slide to the available screen space
1133 if (fWindow->scaleContentToFit()) {
1134 if (windowRect.width() > 0 && windowRect.height() > 0) {
Mike Reed2ac6ce82021-01-15 12:26:22 -05001135 fDefaultMatrix = SkMatrix::RectToRect(slideBounds, windowRect,
1136 SkMatrix::kStart_ScaleToFit);
Jim Van Verth0848fb02018-01-22 13:39:30 -05001137 }
liyuqiane46e4f02016-05-20 07:32:19 -07001138 }
Jim Van Verth0848fb02018-01-22 13:39:30 -05001139
1140 // Prevent the user from dragging content so far outside the window they can't find it again
Yuqian Li755778c2018-03-28 16:23:31 -04001141 fGesture.setTransLimit(slideBounds, windowRect, this->computePreTouchMatrix());
Jim Van Verth0848fb02018-01-22 13:39:30 -05001142
1143 this->updateTitle();
1144 this->updateUIState();
1145
1146 fStatsLayer.resetMeasurements();
1147
1148 fWindow->inval();
liyuqiane46e4f02016-05-20 07:32:19 -07001149 }
jvanverthc265a922016-04-08 12:51:45 -07001150}
1151
Brian Osmanaba642c2020-02-06 12:52:25 -05001152#define MAX_ZOOM_LEVEL 8.0f
1153#define MIN_ZOOM_LEVEL -8.0f
jvanverthc265a922016-04-08 12:51:45 -07001154
jvanverth34524262016-05-04 13:49:13 -07001155void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -07001156 fZoomLevel += delta;
Brian Osmanaba642c2020-02-06 12:52:25 -05001157 fZoomLevel = SkTPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001158 this->preTouchMatrixChanged();
1159}
Yuqian Li755778c2018-03-28 16:23:31 -04001160
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001161void Viewer::preTouchMatrixChanged() {
1162 // Update the trans limit as the transform changes.
Yuqian Li755778c2018-03-28 16:23:31 -04001163 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1164 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
1165 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
1166 fGesture.setTransLimit(slideBounds, windowRect, this->computePreTouchMatrix());
1167}
1168
Brian Osman805a7272018-05-02 15:40:20 -04001169SkMatrix Viewer::computePerspectiveMatrix() {
1170 SkScalar w = fWindow->width(), h = fWindow->height();
1171 SkPoint orthoPts[4] = { { 0, 0 }, { w, 0 }, { 0, h }, { w, h } };
1172 SkPoint perspPts[4] = {
1173 { fPerspectivePoints[0].fX * w, fPerspectivePoints[0].fY * h },
1174 { fPerspectivePoints[1].fX * w, fPerspectivePoints[1].fY * h },
1175 { fPerspectivePoints[2].fX * w, fPerspectivePoints[2].fY * h },
1176 { fPerspectivePoints[3].fX * w, fPerspectivePoints[3].fY * h }
1177 };
1178 SkMatrix m;
1179 m.setPolyToPoly(orthoPts, perspPts, 4);
1180 return m;
1181}
1182
Yuqian Li755778c2018-03-28 16:23:31 -04001183SkMatrix Viewer::computePreTouchMatrix() {
1184 SkMatrix m = fDefaultMatrix;
Ben Wagnercc8eb862019-03-21 16:50:22 -04001185
1186 SkScalar zoomScale = exp(fZoomLevel);
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -05001187 if (fApplyBackingScale) {
1188 zoomScale *= fWindow->scaleFactor();
1189 }
Ben Wagner897dfa22018-08-09 15:18:46 -04001190 m.preTranslate((fOffset.x() - 0.5f) * 2.0f, (fOffset.y() - 0.5f) * 2.0f);
Yuqian Li755778c2018-03-28 16:23:31 -04001191 m.preScale(zoomScale, zoomScale);
Brian Osmanbdaf97b2018-04-26 16:22:42 -04001192
1193 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1194 m.preRotate(fRotation, slideSize.width() * 0.5f, slideSize.height() * 0.5f);
Brian Osman9bb47cf2018-04-26 15:55:00 -04001195
Brian Osman805a7272018-05-02 15:40:20 -04001196 if (kPerspective_Real == fPerspectiveMode) {
1197 SkMatrix persp = this->computePerspectiveMatrix();
Brian Osmanbdaf97b2018-04-26 16:22:42 -04001198 m.postConcat(persp);
Brian Osman9bb47cf2018-04-26 15:55:00 -04001199 }
1200
Yuqian Li755778c2018-03-28 16:23:31 -04001201 return m;
jvanverthc265a922016-04-08 12:51:45 -07001202}
1203
liyuqiand3cdbca2016-05-17 12:44:20 -07001204SkMatrix Viewer::computeMatrix() {
Yuqian Li755778c2018-03-28 16:23:31 -04001205 SkMatrix m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -07001206 m.preConcat(fGesture.globalM());
Yuqian Li755778c2018-03-28 16:23:31 -04001207 m.preConcat(this->computePreTouchMatrix());
liyuqiand3cdbca2016-05-17 12:44:20 -07001208 return m;
jvanverthc265a922016-04-08 12:51:45 -07001209}
1210
Brian Osman621491e2017-02-28 15:45:01 -05001211void Viewer::setBackend(sk_app::Window::BackendType backendType) {
Brian Osman5bee3902019-05-07 09:55:45 -04001212 fPersistentCache.reset();
Brian Osmanc85f1fa2020-06-16 15:11:34 -04001213 fCachedShaders.reset();
Brian Osman621491e2017-02-28 15:45:01 -05001214 fBackendType = backendType;
1215
Robert Phillipse9229532020-06-26 10:10:49 -04001216 // The active context is going away in 'detach'
1217 for(auto& slide : fSlides) {
1218 slide->gpuTeardown();
1219 }
1220
Brian Osman621491e2017-02-28 15:45:01 -05001221 fWindow->detach();
1222
Brian Osman70d2f432017-11-08 09:54:10 -05001223#if defined(SK_BUILD_FOR_WIN)
Brian Salomon194db172017-08-17 14:37:06 -04001224 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
1225 // on Windows, so we just delete the window and recreate it.
Brian Osman70d2f432017-11-08 09:54:10 -05001226 DisplayParams params = fWindow->getRequestedDisplayParams();
1227 delete fWindow;
1228 fWindow = Window::CreateNativeWindow(nullptr);
Brian Osman621491e2017-02-28 15:45:01 -05001229
Brian Osman70d2f432017-11-08 09:54:10 -05001230 // re-register callbacks
1231 fCommands.attach(fWindow);
Brian Osman80fc07e2017-12-08 16:45:43 -05001232 fWindow->pushLayer(this);
Brian Osman56a24812017-12-19 11:15:16 -05001233 fWindow->pushLayer(&fStatsLayer);
Brian Osmand67e5182017-12-08 16:46:09 -05001234 fWindow->pushLayer(&fImGuiLayer);
1235
Brian Osman70d2f432017-11-08 09:54:10 -05001236 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
1237 // will still include our correct sample count. But the re-created fWindow will lose that
1238 // information. On Windows, we need to re-create the window when changing sample count,
1239 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
1240 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
1241 // as if we had never changed windows at all).
1242 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -05001243#endif
1244
Brian Osman70d2f432017-11-08 09:54:10 -05001245 fWindow->attach(backend_type_for_window(fBackendType));
Brian Osman621491e2017-02-28 15:45:01 -05001246}
1247
Brian Osman92004802017-03-06 11:47:26 -05001248void Viewer::setColorMode(ColorMode colorMode) {
1249 fColorMode = colorMode;
Brian Osmanf750fbc2017-02-08 10:47:28 -05001250 this->updateTitle();
1251 fWindow->inval();
1252}
1253
Ben Wagnerabdcc5f2018-02-12 16:37:28 -05001254class OveridePaintFilterCanvas : public SkPaintFilterCanvas {
1255public:
Mike Reed3ae47332019-01-04 10:11:46 -05001256 OveridePaintFilterCanvas(SkCanvas* canvas, SkPaint* paint, Viewer::SkPaintFields* pfields,
1257 SkFont* font, Viewer::SkFontFields* ffields)
1258 : SkPaintFilterCanvas(canvas), fPaint(paint), fPaintOverrides(pfields), fFont(font), fFontOverrides(ffields)
Ben Wagnerabdcc5f2018-02-12 16:37:28 -05001259 { }
Ben Wagner41e40472018-09-24 13:01:54 -04001260 const SkTextBlob* filterTextBlob(const SkPaint& paint, const SkTextBlob* blob,
1261 sk_sp<SkTextBlob>* cache) {
1262 bool blobWillChange = false;
1263 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
Mike Reed3ae47332019-01-04 10:11:46 -05001264 SkTCopyOnFirstWrite<SkFont> filteredFont(it.font());
1265 bool shouldDraw = this->filterFont(&filteredFont);
1266 if (it.font() != *filteredFont || !shouldDraw) {
Ben Wagner41e40472018-09-24 13:01:54 -04001267 blobWillChange = true;
1268 break;
1269 }
1270 }
1271 if (!blobWillChange) {
1272 return blob;
1273 }
1274
1275 SkTextBlobBuilder builder;
1276 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
Mike Reed3ae47332019-01-04 10:11:46 -05001277 SkTCopyOnFirstWrite<SkFont> filteredFont(it.font());
1278 bool shouldDraw = this->filterFont(&filteredFont);
Ben Wagner41e40472018-09-24 13:01:54 -04001279 if (!shouldDraw) {
1280 continue;
1281 }
1282
Mike Reed3ae47332019-01-04 10:11:46 -05001283 SkFont font = *filteredFont;
Mike Reed6d595682018-12-05 17:28:14 -05001284
Ben Wagner41e40472018-09-24 13:01:54 -04001285 const SkTextBlobBuilder::RunBuffer& runBuffer
1286 = it.positioning() == SkTextBlobRunIterator::kDefault_Positioning
Ben Wagner5d9c20e2021-02-24 11:43:07 -05001287 ? builder.allocRunText(font, it.glyphCount(), it.offset().x(),it.offset().y(),
1288 it.textSize())
Ben Wagner41e40472018-09-24 13:01:54 -04001289 : it.positioning() == SkTextBlobRunIterator::kHorizontal_Positioning
Ben Wagner5d9c20e2021-02-24 11:43:07 -05001290 ? builder.allocRunTextPosH(font, it.glyphCount(), it.offset().y(),
1291 it.textSize())
Ben Wagner41e40472018-09-24 13:01:54 -04001292 : it.positioning() == SkTextBlobRunIterator::kFull_Positioning
Ben Wagner5d9c20e2021-02-24 11:43:07 -05001293 ? builder.allocRunTextPos(font, it.glyphCount(), it.textSize())
Ben Wagnere5736262021-02-08 16:52:08 -05001294 : it.positioning() == SkTextBlobRunIterator::kRSXform_Positioning
Ben Wagner5d9c20e2021-02-24 11:43:07 -05001295 ? builder.allocRunTextRSXform(font, it.glyphCount(), it.textSize())
Ben Wagner41e40472018-09-24 13:01:54 -04001296 : (SkASSERT_RELEASE(false), SkTextBlobBuilder::RunBuffer());
1297 uint32_t glyphCount = it.glyphCount();
1298 if (it.glyphs()) {
1299 size_t glyphSize = sizeof(decltype(*it.glyphs()));
1300 memcpy(runBuffer.glyphs, it.glyphs(), glyphCount * glyphSize);
1301 }
1302 if (it.pos()) {
1303 size_t posSize = sizeof(decltype(*it.pos()));
Ben Wagnere5736262021-02-08 16:52:08 -05001304 unsigned posPerGlyph = it.scalarsPerGlyph();
1305 memcpy(runBuffer.pos, it.pos(), glyphCount * posPerGlyph * posSize);
Ben Wagner41e40472018-09-24 13:01:54 -04001306 }
1307 if (it.text()) {
1308 size_t textSize = sizeof(decltype(*it.text()));
1309 uint32_t textCount = it.textSize();
1310 memcpy(runBuffer.utf8text, it.text(), textCount * textSize);
1311 }
1312 if (it.clusters()) {
1313 size_t clusterSize = sizeof(decltype(*it.clusters()));
1314 memcpy(runBuffer.clusters, it.clusters(), glyphCount * clusterSize);
1315 }
1316 }
1317 *cache = builder.make();
1318 return cache->get();
1319 }
1320 void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
1321 const SkPaint& paint) override {
1322 sk_sp<SkTextBlob> cache;
1323 this->SkPaintFilterCanvas::onDrawTextBlob(
1324 this->filterTextBlob(paint, blob, &cache), x, y, paint);
1325 }
Mike Reed3ae47332019-01-04 10:11:46 -05001326 bool filterFont(SkTCopyOnFirstWrite<SkFont>* font) const {
Ben Wagner15a8d572019-03-21 13:35:44 -04001327 if (fFontOverrides->fSize) {
Mike Reed3ae47332019-01-04 10:11:46 -05001328 font->writable()->setSize(fFont->getSize());
1329 }
Ben Wagner15a8d572019-03-21 13:35:44 -04001330 if (fFontOverrides->fScaleX) {
1331 font->writable()->setScaleX(fFont->getScaleX());
1332 }
1333 if (fFontOverrides->fSkewX) {
1334 font->writable()->setSkewX(fFont->getSkewX());
1335 }
Mike Reed3ae47332019-01-04 10:11:46 -05001336 if (fFontOverrides->fHinting) {
1337 font->writable()->setHinting(fFont->getHinting());
1338 }
Ben Wagner9613e452019-01-23 10:34:59 -05001339 if (fFontOverrides->fEdging) {
1340 font->writable()->setEdging(fFont->getEdging());
Hal Canary02738a82019-01-21 18:51:32 +00001341 }
Ben Wagner9613e452019-01-23 10:34:59 -05001342 if (fFontOverrides->fEmbolden) {
1343 font->writable()->setEmbolden(fFont->isEmbolden());
Hal Canary02738a82019-01-21 18:51:32 +00001344 }
Ben Wagnerc17de1d2019-08-26 16:59:09 -04001345 if (fFontOverrides->fBaselineSnap) {
1346 font->writable()->setBaselineSnap(fFont->isBaselineSnap());
1347 }
Ben Wagner9613e452019-01-23 10:34:59 -05001348 if (fFontOverrides->fLinearMetrics) {
1349 font->writable()->setLinearMetrics(fFont->isLinearMetrics());
Hal Canary02738a82019-01-21 18:51:32 +00001350 }
Ben Wagner9613e452019-01-23 10:34:59 -05001351 if (fFontOverrides->fSubpixel) {
1352 font->writable()->setSubpixel(fFont->isSubpixel());
Hal Canary02738a82019-01-21 18:51:32 +00001353 }
Ben Wagner9613e452019-01-23 10:34:59 -05001354 if (fFontOverrides->fEmbeddedBitmaps) {
1355 font->writable()->setEmbeddedBitmaps(fFont->isEmbeddedBitmaps());
Hal Canary02738a82019-01-21 18:51:32 +00001356 }
Ben Wagner9613e452019-01-23 10:34:59 -05001357 if (fFontOverrides->fForceAutoHinting) {
1358 font->writable()->setForceAutoHinting(fFont->isForceAutoHinting());
Hal Canary02738a82019-01-21 18:51:32 +00001359 }
Ben Wagner9613e452019-01-23 10:34:59 -05001360
Mike Reed3ae47332019-01-04 10:11:46 -05001361 return true;
1362 }
Ben Wagnerf55fa0d2018-08-27 18:11:57 -04001363 bool onFilter(SkPaint& paint) const override {
Ben Wagner9613e452019-01-23 10:34:59 -05001364 if (fPaintOverrides->fAntiAlias) {
Ben Wagnerf55fa0d2018-08-27 18:11:57 -04001365 paint.setAntiAlias(fPaint->isAntiAlias());
Ben Wagnerabdcc5f2018-02-12 16:37:28 -05001366 }
Ben Wagner9613e452019-01-23 10:34:59 -05001367 if (fPaintOverrides->fDither) {
Ben Wagnerf55fa0d2018-08-27 18:11:57 -04001368 paint.setDither(fPaint->isDither());
Ben Wagner99a78dc2018-05-09 18:23:51 -04001369 }
Ben Wagnerf5cbbc62021-02-08 22:02:14 -05001370 if (fPaintOverrides->fStyle) {
1371 paint.setStyle(fPaint->getStyle());
1372 }
1373 if (fPaintOverrides->fWidth) {
1374 paint.setStrokeWidth(fPaint->getStrokeWidth());
1375 }
1376 if (fPaintOverrides->fMiterLimit) {
1377 paint.setStrokeMiter(fPaint->getStrokeMiter());
1378 }
1379 if (fPaintOverrides->fCapType) {
1380 paint.setStrokeCap(fPaint->getStrokeCap());
1381 }
1382 if (fPaintOverrides->fJoinType) {
1383 paint.setStrokeJoin(fPaint->getStrokeJoin());
1384 }
Ben Wagnerabdcc5f2018-02-12 16:37:28 -05001385 return true;
1386 }
1387 SkPaint* fPaint;
1388 Viewer::SkPaintFields* fPaintOverrides;
Mike Reed3ae47332019-01-04 10:11:46 -05001389 SkFont* fFont;
1390 Viewer::SkFontFields* fFontOverrides;
Ben Wagnerabdcc5f2018-02-12 16:37:28 -05001391};
1392
Robert Phillips9882dae2019-03-04 11:00:10 -05001393void Viewer::drawSlide(SkSurface* surface) {
Jim Van Verth74826c82019-03-01 14:37:30 -05001394 if (fCurrentSlide < 0) {
1395 return;
1396 }
1397
Robert Phillips9882dae2019-03-04 11:00:10 -05001398 SkAutoCanvasRestore autorestore(surface->getCanvas(), false);
Brian Salomonbf52e3d2017-02-22 15:21:11 -05001399
Brian Osmanf750fbc2017-02-08 10:47:28 -05001400 // By default, we render directly into the window's surface/canvas
Robert Phillips9882dae2019-03-04 11:00:10 -05001401 SkSurface* slideSurface = surface;
1402 SkCanvas* slideCanvas = surface->getCanvas();
Brian Osmanf6877092017-02-13 09:39:57 -05001403 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -07001404
Brian Osmane0d4fba2017-03-15 10:24:55 -04001405 // If we're in any of the color managed modes, construct the color space we're going to use
Brian Osman03115dc2018-11-26 13:55:19 -05001406 sk_sp<SkColorSpace> colorSpace = nullptr;
Brian Osmane0d4fba2017-03-15 10:24:55 -04001407 if (ColorMode::kLegacy != fColorMode) {
Brian Osman82ebe042019-01-04 17:03:00 -05001408 skcms_Matrix3x3 toXYZ;
Brian Osmane0d4fba2017-03-15 10:24:55 -04001409 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
Brian Osman03115dc2018-11-26 13:55:19 -05001410 colorSpace = SkColorSpace::MakeRGB(fColorSpaceTransferFn, toXYZ);
Brian Osmane0d4fba2017-03-15 10:24:55 -04001411 }
1412
Brian Osman3ac99cf2017-12-01 11:23:53 -05001413 if (fSaveToSKP) {
1414 SkPictureRecorder recorder;
1415 SkCanvas* recorderCanvas = recorder.beginRecording(
1416 SkRect::Make(fSlides[fCurrentSlide]->getDimensions()));
Brian Osman3ac99cf2017-12-01 11:23:53 -05001417 fSlides[fCurrentSlide]->draw(recorderCanvas);
1418 sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
1419 SkFILEWStream stream("sample_app.skp");
1420 picture->serialize(&stream);
1421 fSaveToSKP = false;
1422 }
1423
Brian Osmane9ed0f02018-11-26 14:50:05 -05001424 // Grab some things we'll need to make surfaces (for tiling or general offscreen rendering)
Brian Salomon8391bac2019-09-18 11:22:44 -04001425 SkColorType colorType;
1426 switch (fColorMode) {
1427 case ColorMode::kLegacy:
1428 case ColorMode::kColorManaged8888:
1429 colorType = kN32_SkColorType;
1430 break;
1431 case ColorMode::kColorManagedF16:
1432 colorType = kRGBA_F16_SkColorType;
1433 break;
1434 case ColorMode::kColorManagedF16Norm:
1435 colorType = kRGBA_F16Norm_SkColorType;
1436 break;
1437 }
Brian Osmane9ed0f02018-11-26 14:50:05 -05001438
1439 auto make_surface = [=](int w, int h) {
Ben Wagnerae4bb982020-09-24 14:49:00 -04001440 SkSurfaceProps props(fWindow->getRequestedDisplayParams().fSurfaceProps);
Robert Phillips9882dae2019-03-04 11:00:10 -05001441 slideCanvas->getProps(&props);
1442
Brian Osmane9ed0f02018-11-26 14:50:05 -05001443 SkImageInfo info = SkImageInfo::Make(w, h, colorType, kPremul_SkAlphaType, colorSpace);
1444 return Window::kRaster_BackendType == this->fBackendType
1445 ? SkSurface::MakeRaster(info, &props)
Robert Phillips9882dae2019-03-04 11:00:10 -05001446 : slideCanvas->makeSurface(info, &props);
Brian Osmane9ed0f02018-11-26 14:50:05 -05001447 };
1448
Brian Osman03115dc2018-11-26 13:55:19 -05001449 // We need to render offscreen if we're...
1450 // ... in fake perspective or zooming (so we have a snapped copy of the results)
1451 // ... in any raster mode, because the window surface is actually GL
1452 // ... in any color managed mode, because we always make the window surface with no color space
Chris Daltonc8877332020-01-06 09:48:30 -07001453 // ... or if the user explicitly requested offscreen rendering
Brian Osmanf750fbc2017-02-08 10:47:28 -05001454 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman03115dc2018-11-26 13:55:19 -05001455 if (kPerspective_Fake == fPerspectiveMode ||
Brian Osman92004802017-03-06 11:47:26 -05001456 fShowZoomWindow ||
Brian Osman03115dc2018-11-26 13:55:19 -05001457 Window::kRaster_BackendType == fBackendType ||
Chris Daltonc8877332020-01-06 09:48:30 -07001458 colorSpace != nullptr ||
1459 FLAGS_offscreen) {
Brian Osmane0d4fba2017-03-15 10:24:55 -04001460
Brian Osmane9ed0f02018-11-26 14:50:05 -05001461 offscreenSurface = make_surface(fWindow->width(), fWindow->height());
Robert Phillips9882dae2019-03-04 11:00:10 -05001462 slideSurface = offscreenSurface.get();
Mike Klein48b64902018-07-25 13:28:44 -04001463 slideCanvas = offscreenSurface->getCanvas();
Brian Osmanf750fbc2017-02-08 10:47:28 -05001464 }
1465
Mike Reed59295352020-03-12 13:56:34 -04001466 SkPictureRecorder recorder;
1467 SkCanvas* recorderRestoreCanvas = nullptr;
1468 if (fDrawViaSerialize) {
1469 recorderRestoreCanvas = slideCanvas;
1470 slideCanvas = recorder.beginRecording(
1471 SkRect::Make(fSlides[fCurrentSlide]->getDimensions()));
1472 }
1473
Brian Salomonbf52e3d2017-02-22 15:21:11 -05001474 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -05001475 slideCanvas->clear(SK_ColorWHITE);
Brian Osman1df161a2017-02-09 12:10:20 -05001476 // Time the painting logic of the slide
Brian Osman56a24812017-12-19 11:15:16 -05001477 fStatsLayer.beginTiming(fPaintTimer);
Brian Osmane9ed0f02018-11-26 14:50:05 -05001478 if (fTiled) {
1479 int tileW = SkScalarCeilToInt(fWindow->width() * fTileScale.width());
1480 int tileH = SkScalarCeilToInt(fWindow->height() * fTileScale.height());
Brian Osmane9ed0f02018-11-26 14:50:05 -05001481 for (int y = 0; y < fWindow->height(); y += tileH) {
1482 for (int x = 0; x < fWindow->width(); x += tileW) {
Florin Malitaf0d5ea12020-02-19 09:23:08 -05001483 SkAutoCanvasRestore acr(slideCanvas, true);
1484 slideCanvas->clipRect(SkRect::MakeXYWH(x, y, tileW, tileH));
1485 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osmane9ed0f02018-11-26 14:50:05 -05001486 }
1487 }
1488
1489 // Draw borders between tiles
1490 if (fDrawTileBoundaries) {
1491 SkPaint border;
1492 border.setColor(0x60FF00FF);
1493 border.setStyle(SkPaint::kStroke_Style);
1494 for (int y = 0; y < fWindow->height(); y += tileH) {
1495 for (int x = 0; x < fWindow->width(); x += tileW) {
1496 slideCanvas->drawRect(SkRect::MakeXYWH(x, y, tileW, tileH), border);
1497 }
1498 }
1499 }
1500 } else {
1501 slideCanvas->concat(this->computeMatrix());
1502 if (kPerspective_Real == fPerspectiveMode) {
1503 slideCanvas->clipRect(SkRect::MakeWH(fWindow->width(), fWindow->height()));
1504 }
Mike Reed3ae47332019-01-04 10:11:46 -05001505 OveridePaintFilterCanvas filterCanvas(slideCanvas, &fPaint, &fPaintOverrides, &fFont, &fFontOverrides);
Brian Osmane9ed0f02018-11-26 14:50:05 -05001506 fSlides[fCurrentSlide]->draw(&filterCanvas);
1507 }
Brian Osman56a24812017-12-19 11:15:16 -05001508 fStatsLayer.endTiming(fPaintTimer);
Brian Salomonbf52e3d2017-02-22 15:21:11 -05001509 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -05001510
Mike Reed59295352020-03-12 13:56:34 -04001511 if (recorderRestoreCanvas) {
1512 sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
1513 auto data = picture->serialize();
1514 slideCanvas = recorderRestoreCanvas;
1515 slideCanvas->drawPicture(SkPicture::MakeFromData(data.get()));
1516 }
1517
Brian Osman1df161a2017-02-09 12:10:20 -05001518 // Force a flush so we can time that, too
Brian Osman56a24812017-12-19 11:15:16 -05001519 fStatsLayer.beginTiming(fFlushTimer);
Greg Daniel0a2464f2020-05-14 15:45:44 -04001520 slideSurface->flushAndSubmit();
Brian Osman56a24812017-12-19 11:15:16 -05001521 fStatsLayer.endTiming(fFlushTimer);
Brian Osmanf750fbc2017-02-08 10:47:28 -05001522
1523 // If we rendered offscreen, snap an image and push the results to the window's canvas
1524 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -05001525 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -05001526
Robert Phillips9882dae2019-03-04 11:00:10 -05001527 SkCanvas* canvas = surface->getCanvas();
Brian Salomonbf52e3d2017-02-22 15:21:11 -05001528 SkPaint paint;
1529 paint.setBlendMode(SkBlendMode::kSrc);
Mike Reedb339d052021-01-28 11:20:41 -05001530 SkSamplingOptions sampling;
Brian Osman805a7272018-05-02 15:40:20 -04001531 int prePerspectiveCount = canvas->save();
1532 if (kPerspective_Fake == fPerspectiveMode) {
Mike Reedb339d052021-01-28 11:20:41 -05001533 sampling = SkSamplingOptions({1.0f/3, 1.0f/3});
Brian Osman805a7272018-05-02 15:40:20 -04001534 canvas->clear(SK_ColorWHITE);
1535 canvas->concat(this->computePerspectiveMatrix());
1536 }
Mike Reedb339d052021-01-28 11:20:41 -05001537 canvas->drawImage(fLastImage, 0, 0, sampling, &paint);
Brian Osman805a7272018-05-02 15:40:20 -04001538 canvas->restoreToCount(prePerspectiveCount);
liyuqian74959a12016-06-16 14:10:34 -07001539 }
Mike Reed376d8122019-03-14 11:39:02 -04001540
1541 if (fShowSlideDimensions) {
1542 SkRect r = SkRect::Make(fSlides[fCurrentSlide]->getDimensions());
1543 SkPaint paint;
1544 paint.setColor(0x40FFFF00);
1545 surface->getCanvas()->drawRect(r, paint);
1546 }
liyuqian6f163d22016-06-13 12:26:45 -07001547}
1548
Christopher Dalton443ec1b2017-02-24 13:22:53 -07001549void Viewer::onBackendCreated() {
Florin Malitaab99c342018-01-16 16:23:03 -05001550 this->setupCurrentSlide();
Christopher Dalton443ec1b2017-02-24 13:22:53 -07001551 fWindow->show();
Christopher Dalton443ec1b2017-02-24 13:22:53 -07001552}
Jim Van Verth6f449692017-02-14 15:16:46 -05001553
Robert Phillips9882dae2019-03-04 11:00:10 -05001554void Viewer::onPaint(SkSurface* surface) {
1555 this->drawSlide(surface);
jvanverthc265a922016-04-08 12:51:45 -07001556
Robert Phillips9882dae2019-03-04 11:00:10 -05001557 fCommands.drawHelp(surface->getCanvas());
liyuqian2edb0f42016-07-06 14:11:32 -07001558
Brian Osmand67e5182017-12-08 16:46:09 -05001559 this->drawImGui();
Chris Dalton89305752018-11-01 10:52:34 -06001560
Greg Daniel427d8eb2020-09-28 15:04:18 -04001561 fLastImage.reset();
1562
Robert Phillipsed653392020-07-10 13:55:21 -04001563 if (auto direct = fWindow->directContext()) {
Chris Dalton89305752018-11-01 10:52:34 -06001564 // Clean out cache items that haven't been used in more than 10 seconds.
Robert Phillipsed653392020-07-10 13:55:21 -04001565 direct->performDeferredCleanup(std::chrono::seconds(10));
Chris Dalton89305752018-11-01 10:52:34 -06001566 }
jvanverth3d6ed3a2016-04-07 11:09:51 -07001567}
1568
Ben Wagnera1915972018-08-09 15:06:19 -04001569void Viewer::onResize(int width, int height) {
Jim Van Verthb35c6552018-08-13 10:42:17 -04001570 if (fCurrentSlide >= 0) {
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -05001571 SkScalar scaleFactor = 1.0;
1572 if (fApplyBackingScale) {
1573 scaleFactor = fWindow->scaleFactor();
1574 }
1575 fSlides[fCurrentSlide]->resize(width / scaleFactor, height / scaleFactor);
Jim Van Verthb35c6552018-08-13 10:42:17 -04001576 }
Ben Wagnera1915972018-08-09 15:06:19 -04001577}
1578
Florin Malitacefc1b92018-02-19 21:43:47 -05001579SkPoint Viewer::mapEvent(float x, float y) {
1580 const auto m = this->computeMatrix();
1581 SkMatrix inv;
1582
1583 SkAssertResult(m.invert(&inv));
1584
1585 return inv.mapXY(x, y);
1586}
1587
Hal Canaryb1f411a2019-08-29 10:39:22 -04001588bool Viewer::onTouch(intptr_t owner, skui::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -04001589 if (GestureDevice::kMouse == fGestureDevice) {
1590 return false;
1591 }
Florin Malitacefc1b92018-02-19 21:43:47 -05001592
1593 const auto slidePt = this->mapEvent(x, y);
Hal Canaryb1f411a2019-08-29 10:39:22 -04001594 if (fSlides[fCurrentSlide]->onMouse(slidePt.x(), slidePt.y(), state, skui::ModifierKey::kNone)) {
Florin Malitacefc1b92018-02-19 21:43:47 -05001595 fWindow->inval();
1596 return true;
1597 }
1598
liyuqiand3cdbca2016-05-17 12:44:20 -07001599 void* castedOwner = reinterpret_cast<void*>(owner);
1600 switch (state) {
Hal Canaryb1f411a2019-08-29 10:39:22 -04001601 case skui::InputState::kUp: {
liyuqiand3cdbca2016-05-17 12:44:20 -07001602 fGesture.touchEnd(castedOwner);
Jim Van Verth234e5a22018-07-23 13:46:01 -04001603#if defined(SK_BUILD_FOR_IOS)
1604 // TODO: move IOS swipe detection higher up into the platform code
1605 SkPoint dir;
1606 if (fGesture.isFling(&dir)) {
1607 // swiping left or right
1608 if (SkTAbs(dir.fX) > SkTAbs(dir.fY)) {
1609 if (dir.fX < 0) {
1610 this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ?
1611 fCurrentSlide + 1 : 0);
1612 } else {
1613 this->setCurrentSlide(fCurrentSlide > 0 ?
1614 fCurrentSlide - 1 : fSlides.count() - 1);
1615 }
1616 }
1617 fGesture.reset();
1618 }
1619#endif
liyuqiand3cdbca2016-05-17 12:44:20 -07001620 break;
1621 }
Hal Canaryb1f411a2019-08-29 10:39:22 -04001622 case skui::InputState::kDown: {
Brian Osman42bb6ac2017-06-05 08:46:04 -04001623 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -07001624 break;
1625 }
Hal Canaryb1f411a2019-08-29 10:39:22 -04001626 case skui::InputState::kMove: {
Brian Osman42bb6ac2017-06-05 08:46:04 -04001627 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -07001628 break;
1629 }
Jim Van Verthd0cf5da2019-09-09 16:53:39 -04001630 default: {
1631 // kLeft and kRight are only for swipes
1632 SkASSERT(false);
1633 break;
1634 }
liyuqiand3cdbca2016-05-17 12:44:20 -07001635 }
Brian Osmanb53f48c2017-06-07 10:00:30 -04001636 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -07001637 fWindow->inval();
1638 return true;
1639}
1640
Hal Canaryb1f411a2019-08-29 10:39:22 -04001641bool Viewer::onMouse(int x, int y, skui::InputState state, skui::ModifierKey modifiers) {
Brian Osman16c81a12017-12-20 11:58:34 -05001642 if (GestureDevice::kTouch == fGestureDevice) {
1643 return false;
Brian Osman80fc07e2017-12-08 16:45:43 -05001644 }
Brian Osman16c81a12017-12-20 11:58:34 -05001645
Florin Malitacefc1b92018-02-19 21:43:47 -05001646 const auto slidePt = this->mapEvent(x, y);
1647 if (fSlides[fCurrentSlide]->onMouse(slidePt.x(), slidePt.y(), state, modifiers)) {
1648 fWindow->inval();
1649 return true;
Brian Osman16c81a12017-12-20 11:58:34 -05001650 }
1651
1652 switch (state) {
Hal Canaryb1f411a2019-08-29 10:39:22 -04001653 case skui::InputState::kUp: {
Brian Osman16c81a12017-12-20 11:58:34 -05001654 fGesture.touchEnd(nullptr);
1655 break;
1656 }
Hal Canaryb1f411a2019-08-29 10:39:22 -04001657 case skui::InputState::kDown: {
Brian Osman16c81a12017-12-20 11:58:34 -05001658 fGesture.touchBegin(nullptr, x, y);
1659 break;
1660 }
Hal Canaryb1f411a2019-08-29 10:39:22 -04001661 case skui::InputState::kMove: {
Brian Osman16c81a12017-12-20 11:58:34 -05001662 fGesture.touchMoved(nullptr, x, y);
1663 break;
1664 }
Jim Van Verthd0cf5da2019-09-09 16:53:39 -04001665 default: {
1666 SkASSERT(false); // shouldn't see kRight or kLeft here
1667 break;
1668 }
Brian Osman16c81a12017-12-20 11:58:34 -05001669 }
1670 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
1671
Hal Canaryb1f411a2019-08-29 10:39:22 -04001672 if (state != skui::InputState::kMove || fGesture.isBeingTouched()) {
Brian Osman16c81a12017-12-20 11:58:34 -05001673 fWindow->inval();
1674 }
Jim Van Verthe7705782017-05-04 14:00:59 -04001675 return true;
1676}
1677
Jim Van Verthd0cf5da2019-09-09 16:53:39 -04001678bool Viewer::onFling(skui::InputState state) {
1679 if (skui::InputState::kRight == state) {
1680 this->setCurrentSlide(fCurrentSlide > 0 ? fCurrentSlide - 1 : fSlides.count() - 1);
1681 return true;
1682 } else if (skui::InputState::kLeft == state) {
1683 this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ? fCurrentSlide + 1 : 0);
1684 return true;
1685 }
1686 return false;
1687}
1688
1689bool Viewer::onPinch(skui::InputState state, float scale, float x, float y) {
1690 switch (state) {
1691 case skui::InputState::kDown:
1692 fGesture.startZoom();
1693 return true;
1694 break;
1695 case skui::InputState::kMove:
1696 fGesture.updateZoom(scale, x, y, x, y);
1697 return true;
1698 break;
1699 case skui::InputState::kUp:
1700 fGesture.endZoom();
1701 return true;
1702 break;
1703 default:
1704 SkASSERT(false);
1705 break;
1706 }
1707
1708 return false;
1709}
1710
Brian Osmana109e392017-02-24 09:49:14 -05001711static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
Brian Osman535c5e32019-02-09 16:32:58 -05001712 // The gamut image covers a (0.8 x 0.9) shaped region
1713 ImGui::DragCanvas dc(primaries, { 0.0f, 0.9f }, { 0.8f, 0.0f });
Brian Osmana109e392017-02-24 09:49:14 -05001714
1715 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1716 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1717 // Magic numbers are pixel locations of the origin and upper-right corner.
Brian Osman535c5e32019-02-09 16:32:58 -05001718 dc.fDrawList->AddImage(gamutPaint, dc.fPos,
1719 ImVec2(dc.fPos.x + dc.fSize.x, dc.fPos.y + dc.fSize.y),
1720 ImVec2(242, 61), ImVec2(1897, 1922));
Brian Osmana109e392017-02-24 09:49:14 -05001721
Brian Osman535c5e32019-02-09 16:32:58 -05001722 dc.dragPoint((SkPoint*)(&primaries->fRX), true, 0xFF000040);
1723 dc.dragPoint((SkPoint*)(&primaries->fGX), true, 0xFF004000);
1724 dc.dragPoint((SkPoint*)(&primaries->fBX), true, 0xFF400000);
1725 dc.dragPoint((SkPoint*)(&primaries->fWX), true);
1726 dc.fDrawList->AddPolyline(dc.fScreenPoints.begin(), 3, 0xFFFFFFFF, true, 1.5f);
Brian Osman9bb47cf2018-04-26 15:55:00 -04001727}
1728
Ben Wagner3627d2e2018-06-26 14:23:20 -04001729static bool ImGui_DragLocation(SkPoint* pt) {
Brian Osman535c5e32019-02-09 16:32:58 -05001730 ImGui::DragCanvas dc(pt);
1731 dc.fillColor(IM_COL32(0, 0, 0, 128));
1732 dc.dragPoint(pt);
1733 return dc.fDragging;
Ben Wagner3627d2e2018-06-26 14:23:20 -04001734}
1735
Brian Osman9bb47cf2018-04-26 15:55:00 -04001736static bool ImGui_DragQuad(SkPoint* pts) {
Brian Osman535c5e32019-02-09 16:32:58 -05001737 ImGui::DragCanvas dc(pts);
1738 dc.fillColor(IM_COL32(0, 0, 0, 128));
Brian Osman9bb47cf2018-04-26 15:55:00 -04001739
Brian Osman535c5e32019-02-09 16:32:58 -05001740 for (int i = 0; i < 4; ++i) {
1741 dc.dragPoint(pts + i);
1742 }
Brian Osman9bb47cf2018-04-26 15:55:00 -04001743
Brian Osman535c5e32019-02-09 16:32:58 -05001744 dc.fDrawList->AddLine(dc.fScreenPoints[0], dc.fScreenPoints[1], 0xFFFFFFFF);
1745 dc.fDrawList->AddLine(dc.fScreenPoints[1], dc.fScreenPoints[3], 0xFFFFFFFF);
1746 dc.fDrawList->AddLine(dc.fScreenPoints[3], dc.fScreenPoints[2], 0xFFFFFFFF);
1747 dc.fDrawList->AddLine(dc.fScreenPoints[2], dc.fScreenPoints[0], 0xFFFFFFFF);
Brian Osman9bb47cf2018-04-26 15:55:00 -04001748
Brian Osman535c5e32019-02-09 16:32:58 -05001749 return dc.fDragging;
Brian Osmana109e392017-02-24 09:49:14 -05001750}
1751
John Stiles38b7d2f2020-06-24 12:13:31 -04001752static SkSL::String build_sksl_highlight_shader() {
1753 return SkSL::String("out half4 sk_FragColor;\n"
1754 "void main() { sk_FragColor = half4(1, 0, 1, 0.5); }");
1755}
1756
1757static SkSL::String build_metal_highlight_shader(const SkSL::String& inShader) {
1758 // Metal fragment shaders need a lot of non-trivial boilerplate that we don't want to recompute
1759 // here. So keep all shader code, but right before `return *_out;`, swap out the sk_FragColor.
1760 size_t pos = inShader.rfind("return *_out;\n");
1761 if (pos == std::string::npos) {
1762 return inShader;
1763 }
1764
1765 SkSL::String replacementShader = inShader;
1766 replacementShader.insert(pos, "_out->sk_FragColor = float4(1.0, 0.0, 1.0, 0.5); ");
1767 return replacementShader;
1768}
1769
1770static SkSL::String build_glsl_highlight_shader(const GrShaderCaps& shaderCaps) {
1771 const char* versionDecl = shaderCaps.versionDeclString();
1772 SkSL::String highlight = versionDecl ? versionDecl : "";
1773 if (shaderCaps.usesPrecisionModifiers()) {
1774 highlight.append("precision mediump float;\n");
1775 }
1776 highlight.appendf("out vec4 sk_FragColor;\n"
1777 "void main() { sk_FragColor = vec4(1, 0, 1, 0.5); }");
1778 return highlight;
1779}
1780
Brian Osmand67e5182017-12-08 16:46:09 -05001781void Viewer::drawImGui() {
Brian Osman79086b92017-02-10 13:36:16 -05001782 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1783 if (fShowImGuiTestWindow) {
Brian Osman7197e052018-06-29 14:30:48 -04001784 ImGui::ShowDemoWindow(&fShowImGuiTestWindow);
Brian Osman79086b92017-02-10 13:36:16 -05001785 }
1786
1787 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001788 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1789 // always visible, we can end up in a layout feedback loop.
Brian Osman7197e052018-06-29 14:30:48 -04001790 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001791 DisplayParams params = fWindow->getRequestedDisplayParams();
1792 bool paramsChanged = false;
Robert Phillipsed653392020-07-10 13:55:21 -04001793 auto ctx = fWindow->directContext();
Brian Osman0b8bb882019-04-12 11:47:19 -04001794
Brian Osmana109e392017-02-24 09:49:14 -05001795 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1796 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001797 if (ImGui::CollapsingHeader("Backend")) {
1798 int newBackend = static_cast<int>(fBackendType);
1799 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1800 ImGui::SameLine();
1801 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001802#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1803 ImGui::SameLine();
1804 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1805#endif
Stephen Whitea800ec92019-08-02 15:04:52 -04001806#if defined(SK_DAWN)
1807 ImGui::SameLine();
1808 ImGui::RadioButton("Dawn", &newBackend, sk_app::Window::kDawn_BackendType);
1809#endif
John Stilesf7da9232020-11-19 19:58:14 -05001810#if defined(SK_VULKAN) && !defined(SK_BUILD_FOR_MAC)
Brian Osman621491e2017-02-28 15:45:01 -05001811 ImGui::SameLine();
1812 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1813#endif
Jim Van Verthe58d5322019-09-03 09:42:57 -04001814#if defined(SK_METAL)
Jim Van Verthbe39f712019-02-08 15:36:14 -05001815 ImGui::SameLine();
1816 ImGui::RadioButton("Metal", &newBackend, sk_app::Window::kMetal_BackendType);
1817#endif
Jim Van Verth682a2f42020-05-13 16:54:09 -04001818#if defined(SK_DIRECT3D)
1819 ImGui::SameLine();
1820 ImGui::RadioButton("Direct3D", &newBackend, sk_app::Window::kDirect3D_BackendType);
1821#endif
Brian Osman621491e2017-02-28 15:45:01 -05001822 if (newBackend != fBackendType) {
1823 fDeferredActions.push_back([=]() {
1824 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1825 });
1826 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001827
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001828 bool* wire = &params.fGrContextOptions.fWireframeMode;
1829 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1830 paramsChanged = true;
1831 }
Brian Salomon99a33902017-03-07 15:16:34 -05001832
Brian Osman28b12522017-03-08 17:10:24 -05001833 if (ctx) {
John Stiles5daaa7f2020-05-06 11:06:47 -04001834 // Determine the context's max sample count for MSAA radio buttons.
Brian Osman28b12522017-03-08 17:10:24 -05001835 int sampleCount = fWindow->sampleCount();
John Stiles5daaa7f2020-05-06 11:06:47 -04001836 int maxMSAA = (fBackendType != sk_app::Window::kRaster_BackendType) ?
1837 ctx->maxSurfaceSampleCountForColorType(kRGBA_8888_SkColorType) :
1838 1;
1839
1840 // Only display the MSAA radio buttons when there are options above 1x MSAA.
1841 if (maxMSAA >= 4) {
1842 ImGui::Text("MSAA: ");
1843
1844 for (int curMSAA = 1; curMSAA <= maxMSAA; curMSAA *= 2) {
1845 // 2x MSAA works, but doesn't offer much of a visual improvement, so we
1846 // don't show it in the list.
1847 if (curMSAA == 2) {
1848 continue;
1849 }
1850 ImGui::SameLine();
1851 ImGui::RadioButton(SkStringPrintf("%d", curMSAA).c_str(),
1852 &sampleCount, curMSAA);
1853 }
1854 }
Brian Osman28b12522017-03-08 17:10:24 -05001855
1856 if (sampleCount != params.fMSAASampleCount) {
1857 params.fMSAASampleCount = sampleCount;
1858 paramsChanged = true;
1859 }
1860 }
1861
Ben Wagner37c54032018-04-13 14:30:23 -04001862 int pixelGeometryIdx = 0;
Ben Wagnerae4bb982020-09-24 14:49:00 -04001863 if (fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
Ben Wagner37c54032018-04-13 14:30:23 -04001864 pixelGeometryIdx = params.fSurfaceProps.pixelGeometry() + 1;
1865 }
1866 if (ImGui::Combo("Pixel Geometry", &pixelGeometryIdx,
1867 "Default\0Flat\0RGB\0BGR\0RGBV\0BGRV\0\0"))
1868 {
1869 uint32_t flags = params.fSurfaceProps.flags();
1870 if (pixelGeometryIdx == 0) {
Ben Wagnerae4bb982020-09-24 14:49:00 -04001871 fDisplayOverrides.fSurfaceProps.fPixelGeometry = false;
1872 SkPixelGeometry pixelGeometry = fDisplay.fSurfaceProps.pixelGeometry();
1873 params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
Ben Wagner37c54032018-04-13 14:30:23 -04001874 } else {
Ben Wagnerae4bb982020-09-24 14:49:00 -04001875 fDisplayOverrides.fSurfaceProps.fPixelGeometry = true;
Ben Wagner37c54032018-04-13 14:30:23 -04001876 SkPixelGeometry pixelGeometry = SkTo<SkPixelGeometry>(pixelGeometryIdx - 1);
1877 params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
1878 }
1879 paramsChanged = true;
1880 }
1881
1882 bool useDFT = params.fSurfaceProps.isUseDeviceIndependentFonts();
1883 if (ImGui::Checkbox("DFT", &useDFT)) {
1884 uint32_t flags = params.fSurfaceProps.flags();
1885 if (useDFT) {
1886 flags |= SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
1887 } else {
1888 flags &= ~SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
1889 }
1890 SkPixelGeometry pixelGeometry = params.fSurfaceProps.pixelGeometry();
1891 params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
1892 paramsChanged = true;
1893 }
1894
Brian Osman8a9de3d2017-03-01 14:59:05 -05001895 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001896 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001897 auto prButton = [&](GpuPathRenderers x) {
1898 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001899 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1900 params.fGrContextOptions.fGpuPathRenderers = x;
1901 paramsChanged = true;
1902 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001903 }
1904 };
1905
1906 if (!ctx) {
1907 ImGui::RadioButton("Software", true);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001908 } else {
Chris Dalton37ae4b02019-12-28 14:51:11 -07001909 const auto* caps = ctx->priv().caps();
1910 prButton(GpuPathRenderers::kDefault);
1911 if (fWindow->sampleCount() > 1 || caps->mixedSamplesSupport()) {
Chris Daltonff18ff62020-12-07 17:39:26 -07001912 if (GrTessellationPathRenderer::IsSupported(*caps)) {
Chris Dalton0a22b1e2020-03-26 11:52:15 -06001913 prButton(GpuPathRenderers::kTessellation);
Chris Daltonb832ce62020-01-06 19:49:37 -07001914 }
Chris Dalton1a325d22017-07-14 15:17:41 -06001915 }
Chris Dalton37ae4b02019-12-28 14:51:11 -07001916 if (1 == fWindow->sampleCount()) {
1917 if (GrCoverageCountingPathRenderer::IsSupported(*caps)) {
1918 prButton(GpuPathRenderers::kCoverageCounting);
1919 }
1920 prButton(GpuPathRenderers::kSmall);
1921 }
Chris Dalton17dc4182020-03-25 16:18:16 -06001922 prButton(GpuPathRenderers::kTriangulating);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001923 prButton(GpuPathRenderers::kNone);
1924 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001925 ImGui::TreePop();
1926 }
Brian Osman621491e2017-02-28 15:45:01 -05001927 }
1928
Ben Wagner964571d2019-03-08 12:35:06 -05001929 if (ImGui::CollapsingHeader("Tiling")) {
1930 ImGui::Checkbox("Enable", &fTiled);
1931 ImGui::Checkbox("Draw Boundaries", &fDrawTileBoundaries);
1932 ImGui::SliderFloat("Horizontal", &fTileScale.fWidth, 0.1f, 1.0f);
1933 ImGui::SliderFloat("Vertical", &fTileScale.fHeight, 0.1f, 1.0f);
1934 }
1935
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001936 if (ImGui::CollapsingHeader("Transform")) {
Ben Wagnerf9a0f1a2021-02-01 15:38:58 -05001937 if (ImGui::Checkbox("Apply Backing Scale", &fApplyBackingScale)) {
1938 this->preTouchMatrixChanged();
1939 this->onResize(fWindow->width(), fWindow->height());
1940 paramsChanged = true;
1941 }
1942
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001943 float zoom = fZoomLevel;
1944 if (ImGui::SliderFloat("Zoom", &zoom, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
1945 fZoomLevel = zoom;
1946 this->preTouchMatrixChanged();
1947 paramsChanged = true;
1948 }
1949 float deg = fRotation;
Ben Wagnercb139352018-05-04 10:33:04 -04001950 if (ImGui::SliderFloat("Rotate", &deg, -30, 360, "%.3f deg")) {
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001951 fRotation = deg;
1952 this->preTouchMatrixChanged();
1953 paramsChanged = true;
1954 }
Ben Wagner3627d2e2018-06-26 14:23:20 -04001955 if (ImGui::CollapsingHeader("Subpixel offset", ImGuiTreeNodeFlags_NoTreePushOnOpen)) {
1956 if (ImGui_DragLocation(&fOffset)) {
1957 this->preTouchMatrixChanged();
1958 paramsChanged = true;
1959 }
Ben Wagner897dfa22018-08-09 15:18:46 -04001960 } else if (fOffset != SkVector{0.5f, 0.5f}) {
1961 this->preTouchMatrixChanged();
1962 paramsChanged = true;
1963 fOffset = {0.5f, 0.5f};
Ben Wagner3627d2e2018-06-26 14:23:20 -04001964 }
Brian Osman805a7272018-05-02 15:40:20 -04001965 int perspectiveMode = static_cast<int>(fPerspectiveMode);
1966 if (ImGui::Combo("Perspective", &perspectiveMode, "Off\0Real\0Fake\0\0")) {
1967 fPerspectiveMode = static_cast<PerspectiveMode>(perspectiveMode);
Brian Osman9bb47cf2018-04-26 15:55:00 -04001968 this->preTouchMatrixChanged();
Ben Wagner3627d2e2018-06-26 14:23:20 -04001969 paramsChanged = true;
Brian Osman9bb47cf2018-04-26 15:55:00 -04001970 }
Ben Wagner3627d2e2018-06-26 14:23:20 -04001971 if (perspectiveMode != kPerspective_Off && ImGui_DragQuad(fPerspectivePoints)) {
Brian Osman9bb47cf2018-04-26 15:55:00 -04001972 this->preTouchMatrixChanged();
Ben Wagner3627d2e2018-06-26 14:23:20 -04001973 paramsChanged = true;
Brian Osman9bb47cf2018-04-26 15:55:00 -04001974 }
Ben Wagnerd02a74d2018-04-23 12:55:06 -04001975 }
1976
Ben Wagnera580fb32018-04-17 11:16:32 -04001977 if (ImGui::CollapsingHeader("Paint")) {
Ben Wagnera580fb32018-04-17 11:16:32 -04001978 int aliasIdx = 0;
Ben Wagner9613e452019-01-23 10:34:59 -05001979 if (fPaintOverrides.fAntiAlias) {
1980 aliasIdx = SkTo<int>(fPaintOverrides.fAntiAliasState) + 1;
Ben Wagnera580fb32018-04-17 11:16:32 -04001981 }
1982 if (ImGui::Combo("Anti-Alias", &aliasIdx,
Mike Kleine5acd752019-03-22 09:57:16 -05001983 "Default\0Alias\0Normal\0AnalyticAAEnabled\0AnalyticAAForced\0\0"))
Ben Wagnera580fb32018-04-17 11:16:32 -04001984 {
1985 gSkUseAnalyticAA = fPaintOverrides.fOriginalSkUseAnalyticAA;
1986 gSkForceAnalyticAA = fPaintOverrides.fOriginalSkForceAnalyticAA;
Ben Wagnera580fb32018-04-17 11:16:32 -04001987 if (aliasIdx == 0) {
Ben Wagner9613e452019-01-23 10:34:59 -05001988 fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
1989 fPaintOverrides.fAntiAlias = false;
Ben Wagnera580fb32018-04-17 11:16:32 -04001990 } else {
Ben Wagner9613e452019-01-23 10:34:59 -05001991 fPaintOverrides.fAntiAlias = true;
1992 fPaintOverrides.fAntiAliasState = SkTo<SkPaintFields::AntiAliasState>(aliasIdx-1);
Ben Wagnera580fb32018-04-17 11:16:32 -04001993 fPaint.setAntiAlias(aliasIdx > 1);
Ben Wagner9613e452019-01-23 10:34:59 -05001994 switch (fPaintOverrides.fAntiAliasState) {
Ben Wagnera580fb32018-04-17 11:16:32 -04001995 case SkPaintFields::AntiAliasState::Alias:
1996 break;
1997 case SkPaintFields::AntiAliasState::Normal:
1998 break;
1999 case SkPaintFields::AntiAliasState::AnalyticAAEnabled:
2000 gSkUseAnalyticAA = true;
2001 gSkForceAnalyticAA = false;
Ben Wagnera580fb32018-04-17 11:16:32 -04002002 break;
2003 case SkPaintFields::AntiAliasState::AnalyticAAForced:
2004 gSkUseAnalyticAA = gSkForceAnalyticAA = true;
Ben Wagnera580fb32018-04-17 11:16:32 -04002005 break;
2006 }
2007 }
2008 paramsChanged = true;
2009 }
2010
Ben Wagner99a78dc2018-05-09 18:23:51 -04002011 auto paintFlag = [this, &paramsChanged](const char* label, const char* items,
Ben Wagner9613e452019-01-23 10:34:59 -05002012 bool SkPaintFields::* flag,
Ben Wagner99a78dc2018-05-09 18:23:51 -04002013 bool (SkPaint::* isFlag)() const,
2014 void (SkPaint::* setFlag)(bool) )
Ben Wagnera580fb32018-04-17 11:16:32 -04002015 {
Ben Wagner99a78dc2018-05-09 18:23:51 -04002016 int itemIndex = 0;
Ben Wagner9613e452019-01-23 10:34:59 -05002017 if (fPaintOverrides.*flag) {
Ben Wagner99a78dc2018-05-09 18:23:51 -04002018 itemIndex = (fPaint.*isFlag)() ? 2 : 1;
Ben Wagnera580fb32018-04-17 11:16:32 -04002019 }
Ben Wagner99a78dc2018-05-09 18:23:51 -04002020 if (ImGui::Combo(label, &itemIndex, items)) {
2021 if (itemIndex == 0) {
Ben Wagner9613e452019-01-23 10:34:59 -05002022 fPaintOverrides.*flag = false;
Ben Wagner99a78dc2018-05-09 18:23:51 -04002023 } else {
Ben Wagner9613e452019-01-23 10:34:59 -05002024 fPaintOverrides.*flag = true;
Ben Wagner99a78dc2018-05-09 18:23:51 -04002025 (fPaint.*setFlag)(itemIndex == 2);
2026 }
2027 paramsChanged = true;
2028 }
2029 };
Ben Wagnera580fb32018-04-17 11:16:32 -04002030
Ben Wagner99a78dc2018-05-09 18:23:51 -04002031 paintFlag("Dither",
2032 "Default\0No Dither\0Dither\0\0",
Ben Wagner9613e452019-01-23 10:34:59 -05002033 &SkPaintFields::fDither,
Ben Wagner99a78dc2018-05-09 18:23:51 -04002034 &SkPaint::isDither, &SkPaint::setDither);
Ben Wagnerf5cbbc62021-02-08 22:02:14 -05002035
2036 int styleIdx = 0;
2037 if (fPaintOverrides.fStyle) {
2038 styleIdx = SkTo<int>(fPaint.getStyle()) + 1;
2039 }
2040 if (ImGui::Combo("Style", &styleIdx,
2041 "Default\0Fill\0Stroke\0Stroke and Fill\0\0"))
2042 {
2043 if (styleIdx == 0) {
2044 fPaintOverrides.fStyle = false;
2045 fPaint.setStyle(SkPaint::kFill_Style);
2046 } else {
2047 fPaint.setStyle(SkTo<SkPaint::Style>(styleIdx - 1));
2048 fPaintOverrides.fStyle = true;
2049 }
2050 paramsChanged = true;
2051 }
2052
2053 ImGui::Checkbox("Override Stroke Width", &fPaintOverrides.fWidth);
2054 if (fPaintOverrides.fWidth) {
2055 float width = fPaint.getStrokeWidth();
2056 if (ImGui::SliderFloat("Stroke Width", &width, 0, 20)) {
2057 fPaint.setStrokeWidth(width);
2058 paramsChanged = true;
2059 }
2060 }
2061
2062 ImGui::Checkbox("Override Miter Limit", &fPaintOverrides.fMiterLimit);
2063 if (fPaintOverrides.fMiterLimit) {
2064 float miterLimit = fPaint.getStrokeMiter();
2065 if (ImGui::SliderFloat("Miter Limit", &miterLimit, 0, 20)) {
2066 fPaint.setStrokeMiter(miterLimit);
2067 paramsChanged = true;
2068 }
2069 }
2070
2071 int capIdx = 0;
2072 if (fPaintOverrides.fCapType) {
2073 capIdx = SkTo<int>(fPaint.getStrokeCap()) + 1;
2074 }
2075 if (ImGui::Combo("Cap Type", &capIdx,
2076 "Default\0Butt\0Round\0Square\0\0"))
2077 {
2078 if (capIdx == 0) {
2079 fPaintOverrides.fCapType = false;
2080 fPaint.setStrokeCap(SkPaint::kDefault_Cap);
2081 } else {
2082 fPaint.setStrokeCap(SkTo<SkPaint::Cap>(capIdx - 1));
2083 fPaintOverrides.fCapType = true;
2084 }
2085 paramsChanged = true;
2086 }
2087
2088 int joinIdx = 0;
2089 if (fPaintOverrides.fJoinType) {
2090 joinIdx = SkTo<int>(fPaint.getStrokeJoin()) + 1;
2091 }
2092 if (ImGui::Combo("Join Type", &joinIdx,
2093 "Default\0Miter\0Round\0Bevel\0\0"))
2094 {
2095 if (joinIdx == 0) {
2096 fPaintOverrides.fJoinType = false;
2097 fPaint.setStrokeJoin(SkPaint::kDefault_Join);
2098 } else {
2099 fPaint.setStrokeJoin(SkTo<SkPaint::Join>(joinIdx - 1));
2100 fPaintOverrides.fJoinType = true;
2101 }
2102 paramsChanged = true;
2103 }
Ben Wagner9613e452019-01-23 10:34:59 -05002104 }
Hal Canary02738a82019-01-21 18:51:32 +00002105
Ben Wagner9613e452019-01-23 10:34:59 -05002106 if (ImGui::CollapsingHeader("Font")) {
2107 int hintingIdx = 0;
2108 if (fFontOverrides.fHinting) {
2109 hintingIdx = SkTo<int>(fFont.getHinting()) + 1;
2110 }
2111 if (ImGui::Combo("Hinting", &hintingIdx,
2112 "Default\0None\0Slight\0Normal\0Full\0\0"))
2113 {
2114 if (hintingIdx == 0) {
2115 fFontOverrides.fHinting = false;
Ben Wagner5785e4a2019-05-07 16:50:29 -04002116 fFont.setHinting(SkFontHinting::kNone);
Ben Wagner9613e452019-01-23 10:34:59 -05002117 } else {
2118 fFont.setHinting(SkTo<SkFontHinting>(hintingIdx - 1));
2119 fFontOverrides.fHinting = true;
2120 }
2121 paramsChanged = true;
2122 }
Hal Canary02738a82019-01-21 18:51:32 +00002123
Ben Wagner9613e452019-01-23 10:34:59 -05002124 auto fontFlag = [this, &paramsChanged](const char* label, const char* items,
2125 bool SkFontFields::* flag,
2126 bool (SkFont::* isFlag)() const,
2127 void (SkFont::* setFlag)(bool) )
2128 {
2129 int itemIndex = 0;
2130 if (fFontOverrides.*flag) {
2131 itemIndex = (fFont.*isFlag)() ? 2 : 1;
2132 }
2133 if (ImGui::Combo(label, &itemIndex, items)) {
2134 if (itemIndex == 0) {
2135 fFontOverrides.*flag = false;
2136 } else {
2137 fFontOverrides.*flag = true;
2138 (fFont.*setFlag)(itemIndex == 2);
2139 }
2140 paramsChanged = true;
2141 }
2142 };
Hal Canary02738a82019-01-21 18:51:32 +00002143
Ben Wagner9613e452019-01-23 10:34:59 -05002144 fontFlag("Fake Bold Glyphs",
2145 "Default\0No Fake Bold\0Fake Bold\0\0",
2146 &SkFontFields::fEmbolden,
2147 &SkFont::isEmbolden, &SkFont::setEmbolden);
Hal Canary02738a82019-01-21 18:51:32 +00002148
Ben Wagnerc17de1d2019-08-26 16:59:09 -04002149 fontFlag("Baseline Snapping",
2150 "Default\0No Baseline Snapping\0Baseline Snapping\0\0",
2151 &SkFontFields::fBaselineSnap,
2152 &SkFont::isBaselineSnap, &SkFont::setBaselineSnap);
2153
Ben Wagner9613e452019-01-23 10:34:59 -05002154 fontFlag("Linear Text",
2155 "Default\0No Linear Text\0Linear Text\0\0",
2156 &SkFontFields::fLinearMetrics,
2157 &SkFont::isLinearMetrics, &SkFont::setLinearMetrics);
Hal Canary02738a82019-01-21 18:51:32 +00002158
Ben Wagner9613e452019-01-23 10:34:59 -05002159 fontFlag("Subpixel Position Glyphs",
2160 "Default\0Pixel Text\0Subpixel Text\0\0",
2161 &SkFontFields::fSubpixel,
2162 &SkFont::isSubpixel, &SkFont::setSubpixel);
2163
2164 fontFlag("Embedded Bitmap Text",
2165 "Default\0No Embedded Bitmaps\0Embedded Bitmaps\0\0",
2166 &SkFontFields::fEmbeddedBitmaps,
2167 &SkFont::isEmbeddedBitmaps, &SkFont::setEmbeddedBitmaps);
2168
2169 fontFlag("Force Auto-Hinting",
2170 "Default\0No Force Auto-Hinting\0Force Auto-Hinting\0\0",
2171 &SkFontFields::fForceAutoHinting,
2172 &SkFont::isForceAutoHinting, &SkFont::setForceAutoHinting);
2173
2174 int edgingIdx = 0;
2175 if (fFontOverrides.fEdging) {
2176 edgingIdx = SkTo<int>(fFont.getEdging()) + 1;
2177 }
2178 if (ImGui::Combo("Edging", &edgingIdx,
2179 "Default\0Alias\0Antialias\0Subpixel Antialias\0\0"))
2180 {
2181 if (edgingIdx == 0) {
2182 fFontOverrides.fEdging = false;
2183 fFont.setEdging(SkFont::Edging::kAlias);
2184 } else {
2185 fFont.setEdging(SkTo<SkFont::Edging>(edgingIdx-1));
2186 fFontOverrides.fEdging = true;
2187 }
2188 paramsChanged = true;
2189 }
2190
Ben Wagner15a8d572019-03-21 13:35:44 -04002191 ImGui::Checkbox("Override Size", &fFontOverrides.fSize);
2192 if (fFontOverrides.fSize) {
2193 ImGui::DragFloat2("TextRange", fFontOverrides.fSizeRange,
Ben Wagnerd2ae4df2018-06-07 17:54:07 -04002194 0.001f, -10.0f, 300.0f, "%.6f", 2.0f);
Mike Reed3ae47332019-01-04 10:11:46 -05002195 float textSize = fFont.getSize();
Ben Wagnerd2ae4df2018-06-07 17:54:07 -04002196 if (ImGui::DragFloat("TextSize", &textSize, 0.001f,
Ben Wagner15a8d572019-03-21 13:35:44 -04002197 fFontOverrides.fSizeRange[0],
2198 fFontOverrides.fSizeRange[1],
Ben Wagnerd2ae4df2018-06-07 17:54:07 -04002199 "%.6f", 2.0f))
2200 {
Mike Reed3ae47332019-01-04 10:11:46 -05002201 fFont.setSize(textSize);
Ben Wagner15a8d572019-03-21 13:35:44 -04002202 paramsChanged = true;
2203 }
2204 }
2205
2206 ImGui::Checkbox("Override ScaleX", &fFontOverrides.fScaleX);
2207 if (fFontOverrides.fScaleX) {
2208 float scaleX = fFont.getScaleX();
2209 if (ImGui::SliderFloat("ScaleX", &scaleX, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
2210 fFont.setScaleX(scaleX);
2211 paramsChanged = true;
2212 }
2213 }
2214
2215 ImGui::Checkbox("Override SkewX", &fFontOverrides.fSkewX);
2216 if (fFontOverrides.fSkewX) {
2217 float skewX = fFont.getSkewX();
2218 if (ImGui::SliderFloat("SkewX", &skewX, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
2219 fFont.setSkewX(skewX);
Ben Wagnerd2ae4df2018-06-07 17:54:07 -04002220 paramsChanged = true;
2221 }
2222 }
Ben Wagnera580fb32018-04-17 11:16:32 -04002223 }
2224
Mike Reed81f60ec2018-05-15 10:09:52 -04002225 {
2226 SkMetaData controls;
2227 if (fSlides[fCurrentSlide]->onGetControls(&controls)) {
2228 if (ImGui::CollapsingHeader("Current Slide")) {
2229 SkMetaData::Iter iter(controls);
2230 const char* name;
2231 SkMetaData::Type type;
2232 int count;
Brian Osman61fb4bb2018-08-03 11:14:02 -04002233 while ((name = iter.next(&type, &count)) != nullptr) {
Mike Reed81f60ec2018-05-15 10:09:52 -04002234 if (type == SkMetaData::kScalar_Type) {
2235 float val[3];
2236 SkASSERT(count == 3);
2237 controls.findScalars(name, &count, val);
2238 if (ImGui::SliderFloat(name, &val[0], val[1], val[2])) {
2239 controls.setScalars(name, 3, val);
Mike Reed81f60ec2018-05-15 10:09:52 -04002240 }
Ben Wagner110c7032019-03-22 17:03:59 -04002241 } else if (type == SkMetaData::kBool_Type) {
2242 bool val;
2243 SkASSERT(count == 1);
2244 controls.findBool(name, &val);
2245 if (ImGui::Checkbox(name, &val)) {
2246 controls.setBool(name, val);
2247 }
Mike Reed81f60ec2018-05-15 10:09:52 -04002248 }
2249 }
Brian Osman61fb4bb2018-08-03 11:14:02 -04002250 fSlides[fCurrentSlide]->onSetControls(controls);
Mike Reed81f60ec2018-05-15 10:09:52 -04002251 }
2252 }
2253 }
2254
Ben Wagner7a3c6742018-04-23 10:01:07 -04002255 if (fShowSlidePicker) {
2256 ImGui::SetNextTreeNodeOpen(true);
2257 }
Brian Osman79086b92017-02-10 13:36:16 -05002258 if (ImGui::CollapsingHeader("Slide")) {
2259 static ImGuiTextFilter filter;
Brian Osmanf479e422017-11-08 13:11:36 -05002260 static ImVector<const char*> filteredSlideNames;
2261 static ImVector<int> filteredSlideIndices;
2262
Brian Osmanfce09c52017-11-14 15:32:20 -05002263 if (fShowSlidePicker) {
2264 ImGui::SetKeyboardFocusHere();
2265 fShowSlidePicker = false;
2266 }
2267
Brian Osman79086b92017-02-10 13:36:16 -05002268 filter.Draw();
Brian Osmanf479e422017-11-08 13:11:36 -05002269 filteredSlideNames.clear();
2270 filteredSlideIndices.clear();
2271 int filteredIndex = 0;
2272 for (int i = 0; i < fSlides.count(); ++i) {
2273 const char* slideName = fSlides[i]->getName().c_str();
2274 if (filter.PassFilter(slideName) || i == fCurrentSlide) {
2275 if (i == fCurrentSlide) {
2276 filteredIndex = filteredSlideIndices.size();
Brian Osman79086b92017-02-10 13:36:16 -05002277 }
Brian Osmanf479e422017-11-08 13:11:36 -05002278 filteredSlideNames.push_back(slideName);
2279 filteredSlideIndices.push_back(i);
Brian Osman79086b92017-02-10 13:36:16 -05002280 }
Brian Osman79086b92017-02-10 13:36:16 -05002281 }
Brian Osmanf479e422017-11-08 13:11:36 -05002282
Brian Osmanf479e422017-11-08 13:11:36 -05002283 if (ImGui::ListBox("", &filteredIndex, filteredSlideNames.begin(),
2284 filteredSlideNames.size(), 20)) {
Florin Malitaab99c342018-01-16 16:23:03 -05002285 this->setCurrentSlide(filteredSlideIndices[filteredIndex]);
Brian Osman79086b92017-02-10 13:36:16 -05002286 }
2287 }
Brian Osmana109e392017-02-24 09:49:14 -05002288
2289 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05002290 ColorMode newMode = fColorMode;
2291 auto cmButton = [&](ColorMode mode, const char* label) {
2292 if (ImGui::RadioButton(label, mode == fColorMode)) {
2293 newMode = mode;
2294 }
2295 };
2296
2297 cmButton(ColorMode::kLegacy, "Legacy 8888");
Brian Osman03115dc2018-11-26 13:55:19 -05002298 cmButton(ColorMode::kColorManaged8888, "Color Managed 8888");
2299 cmButton(ColorMode::kColorManagedF16, "Color Managed F16");
Brian Salomon8391bac2019-09-18 11:22:44 -04002300 cmButton(ColorMode::kColorManagedF16Norm, "Color Managed F16 Norm");
Brian Osman92004802017-03-06 11:47:26 -05002301
2302 if (newMode != fColorMode) {
Brian Osman03115dc2018-11-26 13:55:19 -05002303 this->setColorMode(newMode);
Brian Osmana109e392017-02-24 09:49:14 -05002304 }
2305
2306 // Pick from common gamuts:
2307 int primariesIdx = 4; // Default: Custom
2308 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
2309 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
2310 primariesIdx = i;
2311 break;
2312 }
2313 }
2314
Brian Osman03115dc2018-11-26 13:55:19 -05002315 // Let user adjust the gamma
Brian Osman82ebe042019-01-04 17:03:00 -05002316 ImGui::SliderFloat("Gamma", &fColorSpaceTransferFn.g, 0.5f, 3.5f);
Brian Osmanfdab5762017-11-09 10:27:55 -05002317
Brian Osmana109e392017-02-24 09:49:14 -05002318 if (ImGui::Combo("Primaries", &primariesIdx,
2319 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
2320 if (primariesIdx >= 0 && primariesIdx <= 3) {
2321 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
2322 }
2323 }
2324
2325 // Allow direct editing of gamut
2326 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
2327 }
Brian Osman207d4102019-01-10 09:40:58 -05002328
2329 if (ImGui::CollapsingHeader("Animation")) {
Hal Canary41248072019-07-11 16:32:53 -04002330 bool isPaused = AnimTimer::kPaused_State == fAnimTimer.state();
Brian Osman207d4102019-01-10 09:40:58 -05002331 if (ImGui::Checkbox("Pause", &isPaused)) {
2332 fAnimTimer.togglePauseResume();
2333 }
Brian Osman707d2022019-01-10 11:27:34 -05002334
2335 float speed = fAnimTimer.getSpeed();
2336 if (ImGui::DragFloat("Speed", &speed, 0.1f)) {
2337 fAnimTimer.setSpeed(speed);
2338 }
Brian Osman207d4102019-01-10 09:40:58 -05002339 }
Brian Osman0b8bb882019-04-12 11:47:19 -04002340
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002341 if (ImGui::CollapsingHeader("Shaders")) {
2342 bool sksl = params.fGrContextOptions.fShaderCacheStrategy ==
2343 GrContextOptions::ShaderCacheStrategy::kSkSL;
John Stiles7247b482021-03-08 10:40:35 -05002344
2345 int optLevel = sksl ? kShaderOptLevel_Source :
John Stiles7247b482021-03-08 10:40:35 -05002346 SkSL::gSkSLInliner ? kShaderOptLevel_Inline :
2347 SkSL::gSkSLOptimizer ? kShaderOptLevel_Optimize :
2348 kShaderOptLevel_Compile;
2349
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002350#if defined(SK_VULKAN)
2351 const bool isVulkan = fBackendType == sk_app::Window::kVulkan_BackendType;
2352#else
2353 const bool isVulkan = false;
Brian Osmanfd7657c2019-04-25 11:34:07 -04002354#endif
Brian Osmanfd7657c2019-04-25 11:34:07 -04002355
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002356 // To re-load shaders from the currently active programs, we flush all
2357 // caches on one frame, then set a flag to poll the cache on the next frame.
Brian Osman0b8bb882019-04-12 11:47:19 -04002358 static bool gLoadPending = false;
2359 if (gLoadPending) {
2360 auto collectShaders = [this](sk_sp<const SkData> key, sk_sp<SkData> data,
Brian Osmanf0de96f2021-02-26 13:54:11 -05002361 const SkString& description, int hitCount) {
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002362 CachedShader& entry(fCachedShaders.push_back());
Brian Osman0b8bb882019-04-12 11:47:19 -04002363 entry.fKey = key;
2364 SkMD5 hash;
2365 hash.write(key->bytes(), key->size());
2366 SkMD5::Digest digest = hash.finish();
2367 for (int i = 0; i < 16; ++i) {
2368 entry.fKeyString.appendf("%02x", digest.data[i]);
2369 }
Brian Osmanf0de96f2021-02-26 13:54:11 -05002370 entry.fKeyDescription = description;
Brian Osman0b8bb882019-04-12 11:47:19 -04002371
Brian Osman9e4e4c72020-06-10 07:19:34 -04002372 SkReadBuffer reader(data->data(), data->size());
Brian Osman1facd5e2020-03-16 16:21:24 -04002373 entry.fShaderType = GrPersistentCacheUtils::GetType(&reader);
Brian Osmana66081d2019-09-03 14:59:26 -04002374 GrPersistentCacheUtils::UnpackCachedShaders(&reader, entry.fShader,
2375 entry.fInputs,
2376 kGrShaderTypeCount);
Brian Osman0b8bb882019-04-12 11:47:19 -04002377 };
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002378 fCachedShaders.reset();
Brian Osman0b8bb882019-04-12 11:47:19 -04002379 fPersistentCache.foreach(collectShaders);
2380 gLoadPending = false;
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002381
2382#if defined(SK_VULKAN)
2383 if (isVulkan && !sksl) {
2384 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
2385 for (auto& entry : fCachedShaders) {
2386 for (int i = 0; i < kGrShaderTypeCount; ++i) {
2387 const SkSL::String& spirv(entry.fShader[i]);
2388 std::string disasm;
2389 tools.Disassemble((const uint32_t*)spirv.c_str(), spirv.size() / 4,
2390 &disasm);
2391 entry.fShader[i].assign(disasm);
2392 }
2393 }
2394 }
2395#endif
Brian Osman0b8bb882019-04-12 11:47:19 -04002396 }
2397
John Stilesa8f6b6f2021-03-05 16:00:42 -05002398 // Defer actually doing the View/Apply logic so that we can trigger an Apply when we
Brian Osman0b8bb882019-04-12 11:47:19 -04002399 // start or finish hovering on a tree node in the list below:
John Stilesa8f6b6f2021-03-05 16:00:42 -05002400 bool doView = ImGui::Button("View"); ImGui::SameLine();
2401 bool doApply = ImGui::Button("Apply Changes"); ImGui::SameLine();
John Stiles7247b482021-03-08 10:40:35 -05002402 bool doDump = ImGui::Button("Dump SkSL to resources/sksl/");
John Stilesa8f6b6f2021-03-05 16:00:42 -05002403
John Stiles7247b482021-03-08 10:40:35 -05002404 int newOptLevel = optLevel;
2405 ImGui::RadioButton("SkSL", &newOptLevel, kShaderOptLevel_Source);
2406 ImGui::SameLine();
2407 ImGui::RadioButton("Compile", &newOptLevel, kShaderOptLevel_Compile);
2408 ImGui::SameLine();
2409 ImGui::RadioButton("Optimize", &newOptLevel, kShaderOptLevel_Optimize);
2410 ImGui::SameLine();
2411 ImGui::RadioButton("Inline", &newOptLevel, kShaderOptLevel_Inline);
John Stilesa8f6b6f2021-03-05 16:00:42 -05002412
John Stiles7247b482021-03-08 10:40:35 -05002413 // If we are changing the compile mode, we want to reset the cache and redo
2414 // everything.
2415 if (doDump || newOptLevel != optLevel) {
2416 sksl = doDump || (newOptLevel == kShaderOptLevel_Source);
2417 SkSL::gSkSLOptimizer = (newOptLevel >= kShaderOptLevel_Optimize);
2418 SkSL::gSkSLInliner = (newOptLevel >= kShaderOptLevel_Inline);
John Stiles7247b482021-03-08 10:40:35 -05002419
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002420 params.fGrContextOptions.fShaderCacheStrategy =
2421 sksl ? GrContextOptions::ShaderCacheStrategy::kSkSL
2422 : GrContextOptions::ShaderCacheStrategy::kBackendSource;
2423 paramsChanged = true;
John Stilesa8f6b6f2021-03-05 16:00:42 -05002424 doView = true;
2425
2426 fDeferredActions.push_back([=]() {
2427 // Reset the cache.
2428 fPersistentCache.reset();
2429 // Dump the cache once we have drawn a frame with it.
2430 if (doDump) {
2431 fDeferredActions.push_back([this]() {
2432 this->dumpShadersToResources();
2433 });
2434 }
2435 });
Brian Osmancbc33b82019-04-19 14:16:19 -04002436 }
Brian Osman0b8bb882019-04-12 11:47:19 -04002437
2438 ImGui::BeginChild("##ScrollingRegion");
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002439 for (auto& entry : fCachedShaders) {
Brian Osman0b8bb882019-04-12 11:47:19 -04002440 bool inTreeNode = ImGui::TreeNode(entry.fKeyString.c_str());
2441 bool hovered = ImGui::IsItemHovered();
2442 if (hovered != entry.fHovered) {
John Stilesa8f6b6f2021-03-05 16:00:42 -05002443 // Force an Apply to patch the highlight shader in/out
Brian Osman0b8bb882019-04-12 11:47:19 -04002444 entry.fHovered = hovered;
John Stilesa8f6b6f2021-03-05 16:00:42 -05002445 doApply = true;
Brian Osman0b8bb882019-04-12 11:47:19 -04002446 }
2447 if (inTreeNode) {
Brian Osmaneb3fb902020-08-18 13:16:59 -04002448 auto stringBox = [](const char* label, std::string* str) {
2449 // Full width, and not too much space for each shader
2450 int lines = std::count(str->begin(), str->end(), '\n') + 2;
2451 ImVec2 boxSize(-1.0f, ImGui::GetTextLineHeight() * std::min(lines, 30));
2452 ImGui::InputTextMultiline(label, str, boxSize);
2453 };
Brian Osmanf0de96f2021-02-26 13:54:11 -05002454 if (ImGui::TreeNode("Key")) {
2455 ImGui::TextWrapped("%s", entry.fKeyDescription.c_str());
2456 ImGui::TreePop();
2457 }
Brian Osmaneb3fb902020-08-18 13:16:59 -04002458 stringBox("##VP", &entry.fShader[kVertex_GrShaderType]);
2459 stringBox("##FP", &entry.fShader[kFragment_GrShaderType]);
Brian Osman0b8bb882019-04-12 11:47:19 -04002460 ImGui::TreePop();
2461 }
2462 }
2463 ImGui::EndChild();
2464
John Stilesa8f6b6f2021-03-05 16:00:42 -05002465 if (doView) {
Brian Osman0b8bb882019-04-12 11:47:19 -04002466 fPersistentCache.reset();
Robert Phillipsed653392020-07-10 13:55:21 -04002467 ctx->priv().getGpu()->resetShaderCacheForTesting();
Brian Osman0b8bb882019-04-12 11:47:19 -04002468 gLoadPending = true;
2469 }
John Stilesa8f6b6f2021-03-05 16:00:42 -05002470
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002471 // We don't support updating SPIRV shaders. We could re-assemble them (with edits),
2472 // but I'm not sure anyone wants to do that.
2473 if (isVulkan && !sksl) {
John Stilesa8f6b6f2021-03-05 16:00:42 -05002474 doApply = false;
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002475 }
John Stilesa8f6b6f2021-03-05 16:00:42 -05002476 if (doApply) {
Brian Osman0b8bb882019-04-12 11:47:19 -04002477 fPersistentCache.reset();
Robert Phillipsed653392020-07-10 13:55:21 -04002478 ctx->priv().getGpu()->resetShaderCacheForTesting();
Brian Osmanc85f1fa2020-06-16 15:11:34 -04002479 for (auto& entry : fCachedShaders) {
Brian Osman0b8bb882019-04-12 11:47:19 -04002480 SkSL::String backup = entry.fShader[kFragment_GrShaderType];
John Stiles38b7d2f2020-06-24 12:13:31 -04002481 if (entry.fHovered) {
2482 // The hovered item (if any) gets a special shader to make it
2483 // identifiable.
2484 SkSL::String& fragShader = entry.fShader[kFragment_GrShaderType];
2485 switch (entry.fShaderType) {
2486 case SkSetFourByteTag('S', 'K', 'S', 'L'): {
2487 fragShader = build_sksl_highlight_shader();
2488 break;
2489 }
2490 case SkSetFourByteTag('G', 'L', 'S', 'L'): {
2491 fragShader = build_glsl_highlight_shader(
2492 *ctx->priv().caps()->shaderCaps());
2493 break;
2494 }
2495 case SkSetFourByteTag('M', 'S', 'L', ' '): {
2496 fragShader = build_metal_highlight_shader(fragShader);
2497 break;
2498 }
2499 }
Brian Osman0b8bb882019-04-12 11:47:19 -04002500 }
2501
Brian Osmana085a412019-04-25 09:44:43 -04002502 auto data = GrPersistentCacheUtils::PackCachedShaders(entry.fShaderType,
2503 entry.fShader,
2504 entry.fInputs,
Brian Osman4524e842019-09-24 16:03:41 -04002505 kGrShaderTypeCount);
Brian Osmanf0de96f2021-02-26 13:54:11 -05002506 fPersistentCache.store(*entry.fKey, *data, entry.fKeyDescription);
Brian Osman0b8bb882019-04-12 11:47:19 -04002507
2508 entry.fShader[kFragment_GrShaderType] = backup;
2509 }
2510 }
2511 }
Brian Osman79086b92017-02-10 13:36:16 -05002512 }
Brian Salomon99a33902017-03-07 15:16:34 -05002513 if (paramsChanged) {
2514 fDeferredActions.push_back([=]() {
2515 fWindow->setRequestedDisplayParams(params);
2516 fWindow->inval();
2517 this->updateTitle();
2518 });
2519 }
Brian Osman79086b92017-02-10 13:36:16 -05002520 ImGui::End();
2521 }
2522
Brian Osman5e7fbfd2019-05-03 13:13:35 -04002523 if (gShaderErrorHandler.fErrors.count()) {
2524 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
Brian Osman31890e22020-07-10 16:48:14 -04002525 ImGui::Begin("Shader Errors", nullptr, ImGuiWindowFlags_NoFocusOnAppearing);
Brian Osman5e7fbfd2019-05-03 13:13:35 -04002526 for (int i = 0; i < gShaderErrorHandler.fErrors.count(); ++i) {
2527 ImGui::TextWrapped("%s", gShaderErrorHandler.fErrors[i].c_str());
Chris Dalton77912982019-12-16 11:18:13 -07002528 SkSL::String sksl(gShaderErrorHandler.fShaders[i].c_str());
2529 GrShaderUtils::VisitLineByLine(sksl, [](int lineNumber, const char* lineText) {
2530 ImGui::TextWrapped("%4i\t%s\n", lineNumber, lineText);
2531 });
Brian Osman5e7fbfd2019-05-03 13:13:35 -04002532 }
2533 ImGui::End();
2534 gShaderErrorHandler.reset();
2535 }
2536
Brian Osmanf6877092017-02-13 09:39:57 -05002537 if (fShowZoomWindow && fLastImage) {
Brian Osman7197e052018-06-29 14:30:48 -04002538 ImGui::SetNextWindowSize(ImVec2(200, 200), ImGuiCond_FirstUseEver);
2539 if (ImGui::Begin("Zoom", &fShowZoomWindow)) {
Brian Osmanead517d2017-11-13 15:36:36 -05002540 static int zoomFactor = 8;
2541 if (ImGui::Button("<<")) {
Brian Osman788b9162020-02-07 10:36:46 -05002542 zoomFactor = std::max(zoomFactor / 2, 4);
Brian Osmanead517d2017-11-13 15:36:36 -05002543 }
2544 ImGui::SameLine(); ImGui::Text("%2d", zoomFactor); ImGui::SameLine();
2545 if (ImGui::Button(">>")) {
Brian Osman788b9162020-02-07 10:36:46 -05002546 zoomFactor = std::min(zoomFactor * 2, 32);
Brian Osmanead517d2017-11-13 15:36:36 -05002547 }
Brian Osmanf6877092017-02-13 09:39:57 -05002548
Ben Wagner3627d2e2018-06-26 14:23:20 -04002549 if (!fZoomWindowFixed) {
2550 ImVec2 mousePos = ImGui::GetMousePos();
2551 fZoomWindowLocation = SkPoint::Make(mousePos.x, mousePos.y);
2552 }
2553 SkScalar x = fZoomWindowLocation.x();
2554 SkScalar y = fZoomWindowLocation.y();
2555 int xInt = SkScalarRoundToInt(x);
2556 int yInt = SkScalarRoundToInt(y);
Brian Osmanf6877092017-02-13 09:39:57 -05002557 ImVec2 avail = ImGui::GetContentRegionAvail();
2558
Brian Osmanead517d2017-11-13 15:36:36 -05002559 uint32_t pixel = 0;
2560 SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
Adlai Hollerbcfc5542020-08-27 12:44:07 -04002561 auto dContext = fWindow->directContext();
2562 if (fLastImage->readPixels(dContext, info, &pixel, info.minRowBytes(), xInt, yInt)) {
Brian Osmanead517d2017-11-13 15:36:36 -05002563 ImGui::SameLine();
Brian Osman22eeb3c2019-02-20 10:13:06 -05002564 ImGui::Text("(X, Y): %d, %d RGBA: %X %X %X %X",
Ben Wagner3627d2e2018-06-26 14:23:20 -04002565 xInt, yInt,
Brian Osman07b56b22017-11-21 14:59:31 -05002566 SkGetPackedR32(pixel), SkGetPackedG32(pixel),
Brian Osmanead517d2017-11-13 15:36:36 -05002567 SkGetPackedB32(pixel), SkGetPackedA32(pixel));
2568 }
2569
Greg Danielfbc60b72020-11-03 17:27:02 -05002570 fImGuiLayer.skiaWidget(avail, [=, lastImage = fLastImage](SkCanvas* c) {
Brian Osmanead517d2017-11-13 15:36:36 -05002571 // Translate so the region of the image that's under the mouse cursor is centered
2572 // in the zoom canvas:
2573 c->scale(zoomFactor, zoomFactor);
Ben Wagner3627d2e2018-06-26 14:23:20 -04002574 c->translate(avail.x * 0.5f / zoomFactor - x - 0.5f,
2575 avail.y * 0.5f / zoomFactor - y - 0.5f);
Greg Danielfbc60b72020-11-03 17:27:02 -05002576 c->drawImage(lastImage, 0, 0);
Brian Osmanead517d2017-11-13 15:36:36 -05002577
2578 SkPaint outline;
2579 outline.setStyle(SkPaint::kStroke_Style);
Ben Wagner3627d2e2018-06-26 14:23:20 -04002580 c->drawRect(SkRect::MakeXYWH(x, y, 1, 1), outline);
Brian Osmanead517d2017-11-13 15:36:36 -05002581 });
Brian Osmanf6877092017-02-13 09:39:57 -05002582 }
2583
2584 ImGui::End();
2585 }
Brian Osman79086b92017-02-10 13:36:16 -05002586}
2587
John Stilesa8f6b6f2021-03-05 16:00:42 -05002588void Viewer::dumpShadersToResources() {
2589 // Sort the list of cached shaders so we can maintain some minimal level of consistency.
2590 // It doesn't really matter, but it will keep files from switching places unpredictably.
2591 std::vector<const CachedShader*> shaders;
2592 shaders.reserve(fCachedShaders.size());
2593 for (const CachedShader& shader : fCachedShaders) {
2594 shaders.push_back(&shader);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05002595 }
John Stilesa8f6b6f2021-03-05 16:00:42 -05002596
2597 std::sort(shaders.begin(), shaders.end(), [](const CachedShader* a, const CachedShader* b) {
2598 return std::tie(a->fShader[kFragment_GrShaderType], a->fShader[kVertex_GrShaderType]) <
2599 std::tie(b->fShader[kFragment_GrShaderType], b->fShader[kVertex_GrShaderType]);
2600 });
2601
2602 // Make the resources/sksl/SlideName/ directory.
2603 SkString directory = SkStringPrintf("%ssksl/%s",
2604 GetResourcePath().c_str(),
2605 fSlides[fCurrentSlide]->getName().c_str());
2606 if (!sk_mkdir(directory.c_str())) {
2607 SkDEBUGFAILF("Unable to create directory '%s'", directory.c_str());
2608 return;
2609 }
2610
2611 int index = 0;
2612 for (const auto& entry : shaders) {
2613 SkString vertPath = SkStringPrintf("%s/Vertex_%02d.vert", directory.c_str(), index);
2614 FILE* vertFile = sk_fopen(vertPath.c_str(), kWrite_SkFILE_Flag);
2615 if (vertFile) {
2616 const SkSL::String& vertText = entry->fShader[kVertex_GrShaderType];
2617 SkAssertResult(sk_fwrite(vertText.c_str(), vertText.size(), vertFile));
2618 sk_fclose(vertFile);
2619 } else {
2620 SkDEBUGFAILF("Unable to write shader to path '%s'", vertPath.c_str());
2621 }
2622
2623 SkString fragPath = SkStringPrintf("%s/Fragment_%02d.frag", directory.c_str(), index);
2624 FILE* fragFile = sk_fopen(fragPath.c_str(), kWrite_SkFILE_Flag);
2625 if (fragFile) {
2626 const SkSL::String& fragText = entry->fShader[kFragment_GrShaderType];
2627 SkAssertResult(sk_fwrite(fragText.c_str(), fragText.size(), fragFile));
2628 sk_fclose(fragFile);
2629 } else {
2630 SkDEBUGFAILF("Unable to write shader to path '%s'", fragPath.c_str());
2631 }
2632
2633 ++index;
2634 }
2635}
2636
2637void Viewer::onIdle() {
2638 SkTArray<std::function<void()>> actionsToRun;
2639 actionsToRun.swap(fDeferredActions);
2640
2641 for (const auto& fn : actionsToRun) {
2642 fn();
2643 }
Brian Osmanfd8f4d52017-02-24 11:57:23 -05002644
Brian Osman56a24812017-12-19 11:15:16 -05002645 fStatsLayer.beginTiming(fAnimateTimer);
jvanverthc265a922016-04-08 12:51:45 -07002646 fAnimTimer.updateTime();
Hal Canary41248072019-07-11 16:32:53 -04002647 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer.nanos());
Brian Osman56a24812017-12-19 11:15:16 -05002648 fStatsLayer.endTiming(fAnimateTimer);
Brian Osman1df161a2017-02-09 12:10:20 -05002649
Brian Osman79086b92017-02-10 13:36:16 -05002650 ImGuiIO& io = ImGui::GetIO();
Brian Osmanffee60f2018-08-03 13:03:19 -04002651 // ImGui always has at least one "active" window, which is the default "Debug" window. It may
2652 // not be visible, though. So we need to redraw if there is at least one visible window, or
2653 // more than one active window. Newly created windows are active but not visible for one frame
2654 // while they determine their layout and sizing.
2655 if (animateWantsInval || fStatsLayer.getActive() || fRefresh ||
2656 io.MetricsActiveWindows > 1 || io.MetricsRenderWindows > 0) {
jvanverthc265a922016-04-08 12:51:45 -07002657 fWindow->inval();
2658 }
jvanverth9f372462016-04-06 06:08:59 -07002659}
liyuqiane5a6cd92016-05-27 08:52:52 -07002660
Florin Malitab632df72018-06-18 21:23:06 -04002661template <typename OptionsFunc>
2662static void WriteStateObject(SkJSONWriter& writer, const char* name, const char* value,
2663 OptionsFunc&& optionsFunc) {
2664 writer.beginObject();
2665 {
2666 writer.appendString(kName , name);
2667 writer.appendString(kValue, value);
2668
2669 writer.beginArray(kOptions);
2670 {
2671 optionsFunc(writer);
2672 }
2673 writer.endArray();
2674 }
2675 writer.endObject();
2676}
2677
2678
liyuqiane5a6cd92016-05-27 08:52:52 -07002679void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07002680 if (!fWindow) {
2681 return;
2682 }
Brian Salomonbdecacf2018-02-02 20:32:49 -05002683 if (fWindow->sampleCount() < 1) {
csmartdalton578f0642017-02-24 16:04:47 -07002684 return; // Surface hasn't been created yet.
2685 }
2686
Florin Malitab632df72018-06-18 21:23:06 -04002687 SkDynamicMemoryWStream memStream;
2688 SkJSONWriter writer(&memStream);
2689 writer.beginArray();
2690
liyuqianb73c24b2016-06-03 08:47:23 -07002691 // Slide state
Florin Malitab632df72018-06-18 21:23:06 -04002692 WriteStateObject(writer, kSlideStateName, fSlides[fCurrentSlide]->getName().c_str(),
2693 [this](SkJSONWriter& writer) {
2694 for(const auto& slide : fSlides) {
2695 writer.appendString(slide->getName().c_str());
2696 }
2697 });
liyuqiane5a6cd92016-05-27 08:52:52 -07002698
liyuqianb73c24b2016-06-03 08:47:23 -07002699 // Backend state
Florin Malitab632df72018-06-18 21:23:06 -04002700 WriteStateObject(writer, kBackendStateName, kBackendTypeStrings[fBackendType],
2701 [](SkJSONWriter& writer) {
2702 for (const auto& str : kBackendTypeStrings) {
2703 writer.appendString(str);
2704 }
2705 });
liyuqiane5a6cd92016-05-27 08:52:52 -07002706
csmartdalton578f0642017-02-24 16:04:47 -07002707 // MSAA state
Florin Malitab632df72018-06-18 21:23:06 -04002708 const auto countString = SkStringPrintf("%d", fWindow->sampleCount());
2709 WriteStateObject(writer, kMSAAStateName, countString.c_str(),
2710 [this](SkJSONWriter& writer) {
2711 writer.appendS32(0);
2712
2713 if (sk_app::Window::kRaster_BackendType == fBackendType) {
2714 return;
2715 }
2716
2717 for (int msaa : {4, 8, 16}) {
2718 writer.appendS32(msaa);
2719 }
2720 });
csmartdalton578f0642017-02-24 16:04:47 -07002721
csmartdalton61cd31a2017-02-27 17:00:53 -07002722 // Path renderer state
2723 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Florin Malitab632df72018-06-18 21:23:06 -04002724 WriteStateObject(writer, kPathRendererStateName, gPathRendererNames[pr].c_str(),
2725 [this](SkJSONWriter& writer) {
Robert Phillipsed653392020-07-10 13:55:21 -04002726 auto ctx = fWindow->directContext();
Florin Malitab632df72018-06-18 21:23:06 -04002727 if (!ctx) {
2728 writer.appendString("Software");
2729 } else {
Robert Phillips9da87e02019-02-04 13:26:26 -05002730 const auto* caps = ctx->priv().caps();
Chris Dalton37ae4b02019-12-28 14:51:11 -07002731 writer.appendString(gPathRendererNames[GpuPathRenderers::kDefault].c_str());
2732 if (fWindow->sampleCount() > 1 || caps->mixedSamplesSupport()) {
Chris Daltonff18ff62020-12-07 17:39:26 -07002733 if (GrTessellationPathRenderer::IsSupported(*caps)) {
Chris Daltonb832ce62020-01-06 19:49:37 -07002734 writer.appendString(
Chris Dalton0a22b1e2020-03-26 11:52:15 -06002735 gPathRendererNames[GpuPathRenderers::kTessellation].c_str());
Chris Daltonb832ce62020-01-06 19:49:37 -07002736 }
Chris Dalton37ae4b02019-12-28 14:51:11 -07002737 }
2738 if (1 == fWindow->sampleCount()) {
Florin Malitab632df72018-06-18 21:23:06 -04002739 if(GrCoverageCountingPathRenderer::IsSupported(*caps)) {
2740 writer.appendString(
2741 gPathRendererNames[GpuPathRenderers::kCoverageCounting].c_str());
2742 }
2743 writer.appendString(gPathRendererNames[GpuPathRenderers::kSmall].c_str());
2744 }
Chris Dalton17dc4182020-03-25 16:18:16 -06002745 writer.appendString(gPathRendererNames[GpuPathRenderers::kTriangulating].c_str());
Chris Dalton37ae4b02019-12-28 14:51:11 -07002746 writer.appendString(gPathRendererNames[GpuPathRenderers::kNone].c_str());
Florin Malitab632df72018-06-18 21:23:06 -04002747 }
2748 });
csmartdalton61cd31a2017-02-27 17:00:53 -07002749
liyuqianb73c24b2016-06-03 08:47:23 -07002750 // Softkey state
Florin Malitab632df72018-06-18 21:23:06 -04002751 WriteStateObject(writer, kSoftkeyStateName, kSoftkeyHint,
2752 [this](SkJSONWriter& writer) {
2753 writer.appendString(kSoftkeyHint);
2754 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
2755 writer.appendString(softkey.c_str());
2756 }
2757 });
liyuqianb73c24b2016-06-03 08:47:23 -07002758
Florin Malitab632df72018-06-18 21:23:06 -04002759 writer.endArray();
2760 writer.flush();
liyuqiane5a6cd92016-05-27 08:52:52 -07002761
Florin Malitab632df72018-06-18 21:23:06 -04002762 auto data = memStream.detachAsData();
2763
2764 // TODO: would be cool to avoid this copy
2765 const SkString cstring(static_cast<const char*>(data->data()), data->size());
2766
2767 fWindow->setUIState(cstring.c_str());
liyuqiane5a6cd92016-05-27 08:52:52 -07002768}
2769
2770void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07002771 // For those who will add more features to handle the state change in this function:
2772 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
2773 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
2774 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07002775 if (stateName.equals(kSlideStateName)) {
Florin Malitaab99c342018-01-16 16:23:03 -05002776 for (int i = 0; i < fSlides.count(); ++i) {
2777 if (fSlides[i]->getName().equals(stateValue)) {
2778 this->setCurrentSlide(i);
2779 return;
liyuqiane5a6cd92016-05-27 08:52:52 -07002780 }
liyuqiane5a6cd92016-05-27 08:52:52 -07002781 }
Florin Malitaab99c342018-01-16 16:23:03 -05002782
2783 SkDebugf("Slide not found: %s", stateValue.c_str());
liyuqian6cb70252016-06-02 12:16:25 -07002784 } else if (stateName.equals(kBackendStateName)) {
2785 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
2786 if (stateValue.equals(kBackendTypeStrings[i])) {
2787 if (fBackendType != i) {
2788 fBackendType = (sk_app::Window::BackendType)i;
Robert Phillipse9229532020-06-26 10:10:49 -04002789 for(auto& slide : fSlides) {
2790 slide->gpuTeardown();
2791 }
liyuqian6cb70252016-06-02 12:16:25 -07002792 fWindow->detach();
Brian Osman70d2f432017-11-08 09:54:10 -05002793 fWindow->attach(backend_type_for_window(fBackendType));
liyuqian6cb70252016-06-02 12:16:25 -07002794 }
2795 break;
2796 }
2797 }
csmartdalton578f0642017-02-24 16:04:47 -07002798 } else if (stateName.equals(kMSAAStateName)) {
2799 DisplayParams params = fWindow->getRequestedDisplayParams();
2800 int sampleCount = atoi(stateValue.c_str());
2801 if (sampleCount != params.fMSAASampleCount) {
2802 params.fMSAASampleCount = sampleCount;
2803 fWindow->setRequestedDisplayParams(params);
2804 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05002805 this->updateTitle();
2806 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07002807 }
2808 } else if (stateName.equals(kPathRendererStateName)) {
2809 DisplayParams params = fWindow->getRequestedDisplayParams();
2810 for (const auto& pair : gPathRendererNames) {
2811 if (pair.second == stateValue.c_str()) {
2812 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
2813 params.fGrContextOptions.fGpuPathRenderers = pair.first;
2814 fWindow->setRequestedDisplayParams(params);
2815 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05002816 this->updateTitle();
2817 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07002818 }
2819 break;
2820 }
csmartdalton578f0642017-02-24 16:04:47 -07002821 }
liyuqianb73c24b2016-06-03 08:47:23 -07002822 } else if (stateName.equals(kSoftkeyStateName)) {
2823 if (!stateValue.equals(kSoftkeyHint)) {
2824 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05002825 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07002826 }
liyuqian2edb0f42016-07-06 14:11:32 -07002827 } else if (stateName.equals(kRefreshStateName)) {
2828 // This state is actually NOT in the UI state.
2829 // We use this to allow Android to quickly set bool fRefresh.
2830 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07002831 } else {
2832 SkDebugf("Unknown stateName: %s", stateName.c_str());
2833 }
2834}
Brian Osman79086b92017-02-10 13:36:16 -05002835
Hal Canaryb1f411a2019-08-29 10:39:22 -04002836bool Viewer::onKey(skui::Key key, skui::InputState state, skui::ModifierKey modifiers) {
Brian Osmand67e5182017-12-08 16:46:09 -05002837 return fCommands.onKey(key, state, modifiers);
Brian Osman79086b92017-02-10 13:36:16 -05002838}
2839
Hal Canaryb1f411a2019-08-29 10:39:22 -04002840bool Viewer::onChar(SkUnichar c, skui::ModifierKey modifiers) {
Brian Osmand67e5182017-12-08 16:46:09 -05002841 if (fSlides[fCurrentSlide]->onChar(c)) {
Jim Van Verth6f449692017-02-14 15:16:46 -05002842 fWindow->inval();
2843 return true;
Brian Osman80fc07e2017-12-08 16:45:43 -05002844 } else {
2845 return fCommands.onChar(c, modifiers);
Jim Van Verth6f449692017-02-14 15:16:46 -05002846 }
Brian Osman79086b92017-02-10 13:36:16 -05002847}