blob: 2355d985b37b60b873eb5135f6d5627e22c32ebe [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
jvanverth34524262016-05-04 13:49:13 -07008#include "Viewer.h"
jvanverth9f372462016-04-06 06:08:59 -07009
jvanverth2bb3b6d2016-04-08 07:24:09 -070010#include "GMSlide.h"
liyuqian6f163d22016-06-13 12:26:45 -070011#include "ImageSlide.h"
Greg Daniel9fcc7432016-11-29 16:35:19 -050012#include "Resources.h"
jvanverthc7027ab2016-06-16 09:52:35 -070013#include "SampleSlide.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070014#include "SKPSlide.h"
jvanverth9f372462016-04-06 06:08:59 -070015
csmartdalton61cd31a2017-02-27 17:00:53 -070016#include "GrContext.h"
Greg Daniel285db442016-10-14 09:12:53 -040017#include "SkATrace.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070018#include "SkCanvas.h"
Brian Osmana109e392017-02-24 09:49:14 -050019#include "SkColorSpace_Base.h"
Brian Osmane0d4fba2017-03-15 10:24:55 -040020#include "SkColorSpaceXformCanvas.h"
Brian Osman2dd96932016-10-18 15:33:53 -040021#include "SkCommandLineFlags.h"
Brian Osmanf9810662017-08-30 10:02:10 -040022#include "SkCommonFlagsGpuThreads.h"
csmartdalton008b9d82017-02-22 12:00:42 -070023#include "SkCommonFlagsPathRenderer.h"
liyuqian74959a12016-06-16 14:10:34 -070024#include "SkDashPathEffect.h"
Brian Osman53136aa2017-07-20 15:43:35 -040025#include "SkEventTracingPriv.h"
Greg Daniel285db442016-10-14 09:12:53 -040026#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050027#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070028#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070029#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070030#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050031#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070032#include "SkRandom.h"
Yuqian Li399b3c22017-08-03 11:08:15 -040033#include "SkScan.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070034#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070035#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050036#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050037#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070038#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040039#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070040
Brian Osman79086b92017-02-10 13:36:16 -050041#include "imgui.h"
42
Chris Dalton1a325d22017-07-14 15:17:41 -060043#include "ccpr/GrCoverageCountingPathRenderer.h"
44
csmartdalton578f0642017-02-24 16:04:47 -070045#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070046#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070047
jvanverth34524262016-05-04 13:49:13 -070048using namespace sk_app;
49
csmartdalton61cd31a2017-02-27 17:00:53 -070050static std::map<GpuPathRenderers, std::string> gPathRendererNames;
51
jvanverth9f372462016-04-06 06:08:59 -070052Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070053 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070054}
55
Christopher Dalton443ec1b2017-02-24 13:22:53 -070056static void on_backend_created_func(void* userData) {
57 Viewer* vv = reinterpret_cast<Viewer*>(userData);
58
59 return vv->onBackendCreated();
60}
61
jvanverth9f372462016-04-06 06:08:59 -070062static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070063 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070064
65 return vv->onPaint(canvas);
66}
67
jvanverth814e38d2016-06-06 08:48:47 -070068static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070069{
70 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
71
72 return viewer->onTouch(owner, state, x, y);
73}
74
liyuqiane5a6cd92016-05-27 08:52:52 -070075static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
76 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
77
78 return viewer->onUIStateChanged(stateName, stateValue);
79}
80
Brian Osman79086b92017-02-10 13:36:16 -050081static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
82 void* userData) {
83 ImGuiIO& io = ImGui::GetIO();
84 io.MousePos.x = static_cast<float>(x);
85 io.MousePos.y = static_cast<float>(y);
86 if (Window::kDown_InputState == state) {
87 io.MouseDown[0] = true;
88 } else if (Window::kUp_InputState == state) {
89 io.MouseDown[0] = false;
90 }
Jim Van Verthe7705782017-05-04 14:00:59 -040091 if (io.WantCaptureMouse) {
92 return true;
93 } else {
94 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
95 return viewer->onMouse(x, y, state, modifiers);
96 }
Brian Osman79086b92017-02-10 13:36:16 -050097}
98
99static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
100 ImGuiIO& io = ImGui::GetIO();
101 io.MouseWheel += delta;
102 return true;
103}
104
105static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
106 void* userData) {
107 ImGuiIO& io = ImGui::GetIO();
108 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
109
110 if (io.WantCaptureKeyboard) {
111 return true;
112 } else {
113 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
114 return viewer->onKey(key, state, modifiers);
115 }
116}
117
118static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
119 ImGuiIO& io = ImGui::GetIO();
120 if (io.WantTextInput) {
121 if (c > 0 && c < 0x10000) {
122 io.AddInputCharacter(c);
123 }
124 return true;
125 } else {
126 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
127 return viewer->onChar(c, modifiers);
128 }
129}
130
Brian Osman2dd96932016-10-18 15:33:53 -0400131static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400132
Brian Osman2dd96932016-10-18 15:33:53 -0400133static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700134 "[~][^]substring[$] [...] of bench name to run.\n"
135 "Multiple matches may be separated by spaces.\n"
136 "~ causes a matching bench to always be skipped\n"
137 "^ requires the start of the bench to match\n"
138 "$ requires the end of the bench to match\n"
139 "^ and $ requires an exact match\n"
140 "If a bench does not match any list entry,\n"
141 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700142
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600143static DEFINE_string(slide, "", "Start on this sample.");
144static DEFINE_bool(list, false, "List samples?");
Jim Van Verth6f449692017-02-14 15:16:46 -0500145
bsalomon6c471f72016-07-26 12:56:32 -0700146#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700147# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700148#else
149# define BACKENDS_STR "\"sw\" and \"gl\""
150#endif
151
liyuqian71491dc2016-06-09 12:02:34 -0700152#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400153static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
154static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700155#else
Brian Osman2dd96932016-10-18 15:33:53 -0400156static DEFINE_string(skps, "skps", "Directory to read skps from.");
157static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700158#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700159
Brian Osman2dd96932016-10-18 15:33:53 -0400160static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700161
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600162static DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
163static DEFINE_bool(cachePathMasks, true, "Allows path mask textures to be cached in GPU configs.");
csmartdalton008b9d82017-02-22 12:00:42 -0700164DEFINE_pathrenderer_flag;
165
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600166static DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
Brian Osman53136aa2017-07-20 15:43:35 -0400167DECLARE_int32(threads)
Brian Salomon41eac792017-03-08 14:03:56 -0500168
Brian Salomon194db172017-08-17 14:37:06 -0400169const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700170 "OpenGL",
Brian Salomon194db172017-08-17 14:37:06 -0400171#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
172 "ANGLE",
173#endif
jvanverth063ece72016-06-17 09:29:14 -0700174#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700175 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700176#endif
csmartdalton578f0642017-02-24 16:04:47 -0700177 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700178};
179
bsalomon6c471f72016-07-26 12:56:32 -0700180static sk_app::Window::BackendType get_backend_type(const char* str) {
181#ifdef SK_VULKAN
182 if (0 == strcmp(str, "vk")) {
183 return sk_app::Window::kVulkan_BackendType;
184 } else
185#endif
Brian Salomon194db172017-08-17 14:37:06 -0400186#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
187 if (0 == strcmp(str, "angle")) {
188 return sk_app::Window::kANGLE_BackendType;
189 } else
190#endif
bsalomon6c471f72016-07-26 12:56:32 -0700191 if (0 == strcmp(str, "gl")) {
192 return sk_app::Window::kNativeGL_BackendType;
193 } else if (0 == strcmp(str, "sw")) {
194 return sk_app::Window::kRaster_BackendType;
195 } else {
196 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
197 return sk_app::Window::kRaster_BackendType;
198 }
199}
200
Brian Osmana109e392017-02-24 09:49:14 -0500201static SkColorSpacePrimaries gSrgbPrimaries = {
202 0.64f, 0.33f,
203 0.30f, 0.60f,
204 0.15f, 0.06f,
205 0.3127f, 0.3290f };
206
207static SkColorSpacePrimaries gAdobePrimaries = {
208 0.64f, 0.33f,
209 0.21f, 0.71f,
210 0.15f, 0.06f,
211 0.3127f, 0.3290f };
212
213static SkColorSpacePrimaries gP3Primaries = {
214 0.680f, 0.320f,
215 0.265f, 0.690f,
216 0.150f, 0.060f,
217 0.3127f, 0.3290f };
218
219static SkColorSpacePrimaries gRec2020Primaries = {
220 0.708f, 0.292f,
221 0.170f, 0.797f,
222 0.131f, 0.046f,
223 0.3127f, 0.3290f };
224
225struct NamedPrimaries {
226 const char* fName;
227 SkColorSpacePrimaries* fPrimaries;
228} gNamedPrimaries[] = {
229 { "sRGB", &gSrgbPrimaries },
230 { "AdobeRGB", &gAdobePrimaries },
231 { "P3", &gP3Primaries },
232 { "Rec. 2020", &gRec2020Primaries },
233};
234
235static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
236 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
237}
238
liyuqiane5a6cd92016-05-27 08:52:52 -0700239const char* kName = "name";
240const char* kValue = "value";
241const char* kOptions = "options";
242const char* kSlideStateName = "Slide";
243const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700244const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700245const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500246const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700247const char* kSoftkeyStateName = "Softkey";
248const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700249const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700250const char* kON = "ON";
251const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700252const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700253
jvanverth34524262016-05-04 13:49:13 -0700254Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700255 : fCurrentMeasurement(0)
256 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700257 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500258 , fShowImGuiDebugWindow(false)
259 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500260 , fShowZoomWindow(false)
261 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700262 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500263 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500264 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700265 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400266 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700267{
Greg Daniel285db442016-10-14 09:12:53 -0400268 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700269
270 static SkOnce initPathRendererNames;
271 initPathRendererNames([]() {
Brian Osman8b0f2652017-08-29 15:18:34 -0400272 gPathRendererNames[GpuPathRenderers::kAll] = "All Path Renderers";
273 gPathRendererNames[GpuPathRenderers::kDefault] =
274 "Default Ganesh Behavior (best path renderer, not including CCPR)";
csmartdalton61cd31a2017-02-27 17:00:53 -0700275 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
276 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400277 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600278 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500279 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700280 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
281 });
282
Brian Osman1df161a2017-02-09 12:10:20 -0500283 memset(fPaintTimes, 0, sizeof(fPaintTimes));
284 memset(fFlushTimes, 0, sizeof(fFlushTimes));
285 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700286
jvanverth2bb3b6d2016-04-08 07:24:09 -0700287 SkDebugf("Command line arguments: ");
288 for (int i = 1; i < argc; ++i) {
289 SkDebugf("%s ", argv[i]);
290 }
291 SkDebugf("\n");
292
293 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500294#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400295 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500296#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700297
Brian Osmanbc8150f2017-07-24 11:38:01 -0400298 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400299 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400300
bsalomon6c471f72016-07-26 12:56:32 -0700301 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700302 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700303
csmartdalton578f0642017-02-24 16:04:47 -0700304 DisplayParams displayParams;
305 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500306 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700307 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600308 displayParams.fGrContextOptions.fAllowPathMaskCaching = FLAGS_cachePathMasks;
Brian Osmanf9810662017-08-30 10:02:10 -0400309 displayParams.fGrContextOptions.fExecutor = GpuExecutorForTools();
csmartdalton578f0642017-02-24 16:04:47 -0700310 fWindow->setRequestedDisplayParams(displayParams);
311
jvanverth9f372462016-04-06 06:08:59 -0700312 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700313 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700314 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700315 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700316 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700317 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500318 fWindow->registerMouseFunc(on_mouse_handler, this);
319 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
320 fWindow->registerKeyFunc(on_key_handler, this);
321 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700322
brianosman622c8d52016-05-10 06:50:49 -0700323 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500324 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
325 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
326 fWindow->inval();
327 });
328 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
329 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
330 fWindow->inval();
331 });
Brian Osmanf6877092017-02-13 09:39:57 -0500332 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
333 this->fShowZoomWindow = !this->fShowZoomWindow;
334 fWindow->inval();
335 });
brianosman622c8d52016-05-10 06:50:49 -0700336 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
337 this->fDisplayStats = !this->fDisplayStats;
338 fWindow->inval();
339 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500340 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500341 switch (fColorMode) {
342 case ColorMode::kLegacy:
343 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
344 break;
345 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
346 this->setColorMode(ColorMode::kColorManagedSRGB8888);
347 break;
348 case ColorMode::kColorManagedSRGB8888:
349 this->setColorMode(ColorMode::kColorManagedLinearF16);
350 break;
351 case ColorMode::kColorManagedLinearF16:
352 this->setColorMode(ColorMode::kLegacy);
353 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500354 }
brianosman622c8d52016-05-10 06:50:49 -0700355 });
356 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
357 int previousSlide = fCurrentSlide;
358 fCurrentSlide++;
359 if (fCurrentSlide >= fSlides.count()) {
360 fCurrentSlide = 0;
361 }
362 this->setupCurrentSlide(previousSlide);
363 });
364 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
365 int previousSlide = fCurrentSlide;
366 fCurrentSlide--;
367 if (fCurrentSlide < 0) {
368 fCurrentSlide = fSlides.count() - 1;
369 }
370 this->setupCurrentSlide(previousSlide);
371 });
372 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
373 this->changeZoomLevel(1.f / 32.f);
374 fWindow->inval();
375 });
376 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
377 this->changeZoomLevel(-1.f / 32.f);
378 fWindow->inval();
379 });
jvanverthaf236b52016-05-20 06:01:06 -0700380 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400381 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
382 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500383 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400384#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
385 if (newBackend == sk_app::Window::kVulkan_BackendType) {
386 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
387 sk_app::Window::kBackendTypeCount);
388 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
389 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500390 }
391#endif
Brian Osman621491e2017-02-28 15:45:01 -0500392 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700393 });
brianosman622c8d52016-05-10 06:50:49 -0700394
Yuqian Li399b3c22017-08-03 11:08:15 -0400395 fCommands.addCommand('A', "AAA", "Toggle analytic AA", [this]() {
396 if (!gSkUseAnalyticAA) {
397 gSkUseAnalyticAA = true;
398 } else if (!gSkForceAnalyticAA) {
399 gSkForceAnalyticAA = true;
400 } else {
401 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
402 }
403 this->updateTitle();
404 fWindow->inval();
405 });
406 fCommands.addCommand('D', "DAA", "Toggle delta AA", [this]() {
407 if (!gSkUseDeltaAA) {
408 gSkUseDeltaAA = true;
409 } else if (!gSkForceDeltaAA) {
410 gSkForceDeltaAA = true;
411 } else {
412 gSkUseDeltaAA = gSkForceDeltaAA = false;
413 }
414 this->updateTitle();
415 fWindow->inval();
416 });
417
jvanverth2bb3b6d2016-04-08 07:24:09 -0700418 // set up slides
419 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500420 this->setStartupSlide();
421 if (FLAGS_list) {
422 this->listNames();
423 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700424
djsollen12d62a72016-04-21 07:59:44 -0700425 fAnimTimer.run();
426
Brian Osman79086b92017-02-10 13:36:16 -0500427 // ImGui initialization:
428 ImGuiIO& io = ImGui::GetIO();
429 io.DisplaySize.x = static_cast<float>(fWindow->width());
430 io.DisplaySize.y = static_cast<float>(fWindow->height());
431
432 // Keymap...
433 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
434 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
435 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
436 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
437 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
438 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
439 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
440 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
441 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
442 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
443 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
444 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
445 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
446 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
447 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
448 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
449 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
450 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
451 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
452
453 int w, h;
454 unsigned char* pixels;
455 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
456 SkImageInfo info = SkImageInfo::MakeA8(w, h);
457 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500458 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
459 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400460 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500461 fImGuiFontPaint.setShader(fontShader);
462 fImGuiFontPaint.setColor(SK_ColorWHITE);
463 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
464 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500465
Brian Osmana109e392017-02-24 09:49:14 -0500466 auto gamutImage = GetResourceAsImage("gamut.png");
467 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400468 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500469 }
470 fImGuiGamutPaint.setColor(SK_ColorWHITE);
471 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
472
csmartdalton578f0642017-02-24 16:04:47 -0700473 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700474}
475
jvanverth34524262016-05-04 13:49:13 -0700476void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700477 fAllSlideNames = Json::Value(Json::arrayValue);
478
jvanverth2bb3b6d2016-04-08 07:24:09 -0700479 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
480 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400481 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700482
483 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
484 sk_sp<Slide> slide(new GMSlide(gm.release()));
485 fSlides.push_back(slide);
486 }
487
488 gms = gms->next();
489 }
490
491 // reverse array
492 for (int i = 0; i < fSlides.count()/2; ++i) {
493 sk_sp<Slide> temp = fSlides[i];
494 fSlides[i] = fSlides[fSlides.count() - i - 1];
495 fSlides[fSlides.count() - i - 1] = temp;
496 }
497
jvanverthc7027ab2016-06-16 09:52:35 -0700498 // samples
499 const SkViewRegister* reg = SkViewRegister::Head();
500 while (reg) {
501 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700502 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
503 fSlides.push_back(slide);
504 }
jvanverthc7027ab2016-06-16 09:52:35 -0700505 reg = reg->next();
506 }
507
jvanverth2bb3b6d2016-04-08 07:24:09 -0700508 // SKPs
509 for (int i = 0; i < FLAGS_skps.count(); i++) {
510 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700511 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
512 continue;
513 }
514
jvanverth2bb3b6d2016-04-08 07:24:09 -0700515 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700516 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700517 if (slide) {
518 fSlides.push_back(slide);
519 }
520 } else {
521 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700522 SkString skpName;
523 while (it.next(&skpName)) {
524 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
525 continue;
526 }
527
528 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
529 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700530 if (slide) {
531 fSlides.push_back(slide);
532 }
533 }
534 }
535 }
liyuqian6f163d22016-06-13 12:26:45 -0700536
537 // JPGs
538 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
539 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
540 SkString jpgName;
541 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700542 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
543 continue;
544 }
545
liyuqian6f163d22016-06-13 12:26:45 -0700546 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
547 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
548 if (slide) {
549 fSlides.push_back(slide);
550 }
551 }
552 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700553}
554
555
jvanverth34524262016-05-04 13:49:13 -0700556Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700557 fWindow->detach();
558 delete fWindow;
559}
560
brianosman05de2162016-05-06 13:28:57 -0700561void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700562 if (!fWindow) {
563 return;
564 }
565 if (fWindow->sampleCount() < 0) {
566 return; // Surface hasn't been created yet.
567 }
568
jvanverth34524262016-05-04 13:49:13 -0700569 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700570 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700571
Yuqian Li399b3c22017-08-03 11:08:15 -0400572 if (gSkUseDeltaAA) {
573 if (gSkForceDeltaAA) {
574 title.append(" <FDAA>");
575 } else {
576 title.append(" <DAA>");
577 }
578 } else if (gSkUseAnalyticAA) {
579 if (gSkForceAnalyticAA) {
580 title.append(" <FAAA>");
581 } else {
582 title.append(" <AAA>");
583 }
584 }
585
Brian Osman92004802017-03-06 11:47:26 -0500586 switch (fColorMode) {
587 case ColorMode::kLegacy:
588 title.append(" Legacy 8888");
589 break;
590 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
591 title.append(" ColorManaged 8888 (Nonlinear blending)");
592 break;
593 case ColorMode::kColorManagedSRGB8888:
594 title.append(" ColorManaged 8888");
595 break;
596 case ColorMode::kColorManagedLinearF16:
597 title.append(" ColorManaged F16");
598 break;
599 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500600
Brian Osman92004802017-03-06 11:47:26 -0500601 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500602 int curPrimaries = -1;
603 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
604 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
605 curPrimaries = i;
606 break;
607 }
608 }
609 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700610 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500611
csmartdalton578f0642017-02-24 16:04:47 -0700612 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700613 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700614 if (int msaa = fWindow->sampleCount()) {
615 title.appendf(" MSAA: %i", msaa);
616 }
617 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700618
619 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Brian Osman8b0f2652017-08-29 15:18:34 -0400620 if (GpuPathRenderers::kDefault != pr) {
csmartdalton61cd31a2017-02-27 17:00:53 -0700621 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
622 }
623
brianosman05de2162016-05-06 13:28:57 -0700624 fWindow->setTitle(title.c_str());
625}
626
Jim Van Verth6f449692017-02-14 15:16:46 -0500627void Viewer::setStartupSlide() {
628
629 if (!FLAGS_slide.isEmpty()) {
630 int count = fSlides.count();
631 for (int i = 0; i < count; i++) {
632 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
633 fCurrentSlide = i;
634 return;
635 }
636 }
637
638 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
639 this->listNames();
640 }
641
642 fCurrentSlide = 0;
643}
644
645void Viewer::listNames() {
646 int count = fSlides.count();
647 SkDebugf("All Slides:\n");
648 for (int i = 0; i < count; i++) {
649 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
650 }
651}
652
brianosman05de2162016-05-06 13:28:57 -0700653void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700654 if (fCurrentSlide == previousSlide) {
655 return; // no change; do nothing
656 }
liyuqian6f163d22016-06-13 12:26:45 -0700657 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700658 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700659
liyuqiane46e4f02016-05-20 07:32:19 -0700660 fGesture.reset();
661 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700662
Brian Osman42bb6ac2017-06-05 08:46:04 -0400663 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
664 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
665 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
666
667 // Start with a matrix that scales the slide to the available screen space
668 if (fWindow->scaleContentToFit()) {
669 if (windowRect.width() > 0 && windowRect.height() > 0) {
670 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700671 }
672 }
673
Brian Osman42bb6ac2017-06-05 08:46:04 -0400674 // Prevent the user from dragging content so far outside the window they can't find it again
675 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700676
brianosman05de2162016-05-06 13:28:57 -0700677 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700678 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700679 if (previousSlide >= 0) {
680 fSlides[previousSlide]->unload();
681 }
jvanverthc265a922016-04-08 12:51:45 -0700682 fWindow->inval();
683}
684
685#define MAX_ZOOM_LEVEL 8
686#define MIN_ZOOM_LEVEL -8
687
jvanverth34524262016-05-04 13:49:13 -0700688void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700689 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400690 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700691}
692
liyuqiand3cdbca2016-05-17 12:44:20 -0700693SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700694 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700695
Brian Osman42bb6ac2017-06-05 08:46:04 -0400696 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
697 : SK_Scalar1 + fZoomLevel;
698 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700699 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400700 m.preConcat(fDefaultMatrix);
701 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700702
liyuqiand3cdbca2016-05-17 12:44:20 -0700703 return m;
jvanverthc265a922016-04-08 12:51:45 -0700704}
705
Brian Osman621491e2017-02-28 15:45:01 -0500706void Viewer::setBackend(sk_app::Window::BackendType backendType) {
707 fBackendType = backendType;
708
709 fWindow->detach();
710
711#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Salomon194db172017-08-17 14:37:06 -0400712 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
713 // on Windows, so we just delete the window and recreate it.
Brian Osman80a82df2017-07-12 15:42:51 -0400714 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
Brian Salomon194db172017-08-17 14:37:06 -0400715 sk_app::Window::kNativeGL_BackendType == fBackendType
716#if SK_ANGLE
717 || sk_app::Window::kANGLE_BackendType == fBackendType
718#endif
719 ) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400720 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500721 delete fWindow;
722 fWindow = Window::CreateNativeWindow(nullptr);
723
724 // re-register callbacks
725 fCommands.attach(fWindow);
726 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
727 fWindow->registerPaintFunc(on_paint_handler, this);
728 fWindow->registerTouchFunc(on_touch_handler, this);
729 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
730 fWindow->registerMouseFunc(on_mouse_handler, this);
731 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
732 fWindow->registerKeyFunc(on_key_handler, this);
733 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400734 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
735 // will still include our correct sample count. But the re-created fWindow will lose that
736 // information. On Windows, we need to re-create the window when changing sample count,
737 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
738 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
739 // as if we had never changed windows at all).
740 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500741 }
742#endif
743
744 fWindow->attach(fBackendType);
745}
746
Brian Osman92004802017-03-06 11:47:26 -0500747void Viewer::setColorMode(ColorMode colorMode) {
748 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700749
Brian Osmanf750fbc2017-02-08 10:47:28 -0500750 // When we're in color managed mode, we tag our window surface as sRGB. If we've switched into
Brian Osmane0d4fba2017-03-15 10:24:55 -0400751 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700752 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500753 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400754 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
755 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500756 if (wasInLegacy != wantLegacy) {
757 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700758 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500759 }
760
761 this->updateTitle();
762 fWindow->inval();
763}
764
765void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500766 SkAutoCanvasRestore autorestore(canvas, false);
767
Brian Osmanf750fbc2017-02-08 10:47:28 -0500768 // By default, we render directly into the window's surface/canvas
769 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500770 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700771
Brian Osmane0d4fba2017-03-15 10:24:55 -0400772 // If we're in any of the color managed modes, construct the color space we're going to use
773 sk_sp<SkColorSpace> cs = nullptr;
774 if (ColorMode::kLegacy != fColorMode) {
775 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
776 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400777 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400778 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
779 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
780 }
781
782 // If we're in F16, or we're zooming, or we're in color correct 8888 and the gamut isn't sRGB,
Brian Osman92004802017-03-06 11:47:26 -0500783 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500784 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500785 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500786 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400787 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
788 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
789
Brian Osman92004802017-03-06 11:47:26 -0500790 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
791 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400792 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
793 // with a special canvas (below) that has the color space attached
794 sk_sp<SkColorSpace> offscreenColorSpace =
795 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500796 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400797 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500798 offscreenSurface = canvas->makeSurface(info);
799 slideCanvas = offscreenSurface->getCanvas();
800 }
801
Brian Osmane0d4fba2017-03-15 10:24:55 -0400802 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
803 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
804 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
805 slideCanvas = xformCanvas.get();
806 }
807
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500808 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500809 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500810 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500811 // Time the painting logic of the slide
812 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500813 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500814 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500815 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500816
817 // Force a flush so we can time that, too
818 startTime = SkTime::GetMSecs();
819 slideCanvas->flush();
820 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500821
822 // If we rendered offscreen, snap an image and push the results to the window's canvas
823 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500824 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500825
826 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400827 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500828 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400829 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500830 SkPaint paint;
831 paint.setBlendMode(SkBlendMode::kSrc);
832 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700833 }
liyuqian6f163d22016-06-13 12:26:45 -0700834}
835
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700836void Viewer::onBackendCreated() {
837 this->updateTitle();
838 this->updateUIState();
839 this->setupCurrentSlide(-1);
840 fWindow->show();
841 fWindow->inval();
842}
Jim Van Verth6f449692017-02-14 15:16:46 -0500843
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700844void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500845 // Update ImGui input
846 ImGuiIO& io = ImGui::GetIO();
847 io.DeltaTime = 1.0f / 60.0f;
848 io.DisplaySize.x = static_cast<float>(fWindow->width());
849 io.DisplaySize.y = static_cast<float>(fWindow->height());
850
851 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
852 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
853 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
854
855 ImGui::NewFrame();
856
Brian Osmanf750fbc2017-02-08 10:47:28 -0500857 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700858
Brian Osman1df161a2017-02-09 12:10:20 -0500859 // Advance our timing bookkeeping
860 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
861 SkASSERT(fCurrentMeasurement < kMeasurementCount);
862
863 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700864 if (fDisplayStats) {
865 drawStats(canvas);
866 }
brianosman622c8d52016-05-10 06:50:49 -0700867 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700868
Brian Osman79086b92017-02-10 13:36:16 -0500869 drawImGui(canvas);
870
Brian Osman1df161a2017-02-09 12:10:20 -0500871 // Update the FPS
872 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700873}
874
jvanverth814e38d2016-06-06 08:48:47 -0700875bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400876 if (GestureDevice::kMouse == fGestureDevice) {
877 return false;
878 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700879 void* castedOwner = reinterpret_cast<void*>(owner);
880 switch (state) {
881 case Window::kUp_InputState: {
882 fGesture.touchEnd(castedOwner);
883 break;
884 }
885 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400886 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700887 break;
888 }
889 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400890 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700891 break;
892 }
893 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400894 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700895 fWindow->inval();
896 return true;
897}
898
Jim Van Verthe7705782017-05-04 14:00:59 -0400899bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Jim Van Verthc9e7f9c2017-11-02 09:46:49 -0400900 if (!fSlides[fCurrentSlide]->onMouse(x, y, state, modifiers)) {
901 if (GestureDevice::kTouch == fGestureDevice) {
902 return false;
903 }
904 switch (state) {
905 case Window::kUp_InputState: {
906 fGesture.touchEnd(nullptr);
907 break;
908 }
909 case Window::kDown_InputState: {
910 fGesture.touchBegin(nullptr, x, y);
911 break;
912 }
913 case Window::kMove_InputState: {
914 fGesture.touchMoved(nullptr, x, y);
915 break;
916 }
917 }
918 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Brian Osmanb53f48c2017-06-07 10:00:30 -0400919 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400920 fWindow->inval();
921 return true;
922}
923
jvanverth34524262016-05-04 13:49:13 -0700924void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700925 static const float kPixelPerMS = 2.0f;
926 static const int kDisplayWidth = 130;
927 static const int kDisplayHeight = 100;
928 static const int kDisplayPadding = 10;
929 static const int kGraphPadding = 3;
930 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
931
Mike Reed3661bc92017-02-22 13:21:42 -0500932 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700933 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
934 SkIntToScalar(kDisplayPadding),
935 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
936 SkPaint paint;
937 canvas->save();
938
939 canvas->clipRect(rect);
940 paint.setColor(SK_ColorBLACK);
941 canvas->drawRect(rect, paint);
942 // draw the 16ms line
943 paint.setColor(SK_ColorLTGRAY);
944 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
945 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
946 paint.setColor(SK_ColorRED);
947 paint.setStyle(SkPaint::kStroke_Style);
948 canvas->drawRect(rect, paint);
949
950 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
951 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700952 int i = fCurrentMeasurement;
953 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500954 // Round to nearest values
955 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
956 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
957 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
958 int startY = SkScalarTruncToInt(rect.fBottom);
959 int endY = startY - flushHeight;
960 paint.setColor(SK_ColorRED);
961 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
962 SkIntToScalar(x), SkIntToScalar(endY), paint);
963 startY = endY;
964 endY = startY - paintHeight;
965 paint.setColor(SK_ColorGREEN);
966 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
967 SkIntToScalar(x), SkIntToScalar(endY), paint);
968 startY = endY;
969 endY = startY - animateHeight;
970 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700971 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
972 SkIntToScalar(x), SkIntToScalar(endY), paint);
973 i++;
974 i &= (kMeasurementCount - 1); // fast mod
975 x += xStep;
976 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700977
978 canvas->restore();
979}
980
Brian Osmana109e392017-02-24 09:49:14 -0500981static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
982 const ImVec2& pos, const ImVec2& size) {
983 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
984 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
985
986 // Invisible 10x10 button
987 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
988 ImGui::InvisibleButton(label, ImVec2(10, 10));
989
990 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
991 ImGuiIO& io = ImGui::GetIO();
992 // Normalized mouse position, relative to our gamut box
993 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
994 // Clamp to edge of box, convert back to primary scale
995 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
996 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
997 }
998
999 if (ImGui::IsItemHovered()) {
1000 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
1001 }
1002
1003 // Return screen coordinates for the caller. We could just return center here, but we'd have
1004 // one frame of lag during drag.
1005 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1006}
1007
1008static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1009 ImDrawList* drawList = ImGui::GetWindowDrawList();
1010
1011 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1012 // width, and scale the height to maintain aspect ratio.
1013 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1014 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1015 ImVec2 pos = ImGui::GetCursorScreenPos();
1016
1017 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1018 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1019 // Magic numbers are pixel locations of the origin and upper-right corner.
1020 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1021 ImVec2(242, 61), ImVec2(1897, 1922));
1022 ImVec2 endPos = ImGui::GetCursorPos();
1023
1024 // Primary markers
1025 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1026 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1027 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1028 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1029
1030 // Gamut triangle
1031 drawList->AddCircle(r, 5.0f, 0xFF000040);
1032 drawList->AddCircle(g, 5.0f, 0xFF004000);
1033 drawList->AddCircle(b, 5.0f, 0xFF400000);
1034 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1035 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1036
1037 // Re-position cursor immediate after the diagram for subsequent controls
1038 ImGui::SetCursorPos(endPos);
1039}
1040
Brian Osman79086b92017-02-10 13:36:16 -05001041void Viewer::drawImGui(SkCanvas* canvas) {
1042 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1043 if (fShowImGuiTestWindow) {
1044 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1045 }
1046
1047 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001048 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1049 // always visible, we can end up in a layout feedback loop.
1050 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001051 DisplayParams params = fWindow->getRequestedDisplayParams();
1052 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001053 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1054 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001055 if (ImGui::CollapsingHeader("Backend")) {
1056 int newBackend = static_cast<int>(fBackendType);
1057 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1058 ImGui::SameLine();
1059 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001060#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1061 ImGui::SameLine();
1062 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1063#endif
Brian Osman621491e2017-02-28 15:45:01 -05001064#if defined(SK_VULKAN)
1065 ImGui::SameLine();
1066 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1067#endif
1068 if (newBackend != fBackendType) {
1069 fDeferredActions.push_back([=]() {
1070 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1071 });
1072 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001073
Brian Salomon99a33902017-03-07 15:16:34 -05001074 const GrContext* ctx = fWindow->getGrContext();
1075 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1076 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1077 paramsChanged = true;
1078 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001079 bool* wire = &params.fGrContextOptions.fWireframeMode;
1080 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1081 paramsChanged = true;
1082 }
Brian Salomon99a33902017-03-07 15:16:34 -05001083
Brian Osman28b12522017-03-08 17:10:24 -05001084 if (ctx) {
1085 int sampleCount = fWindow->sampleCount();
1086 ImGui::Text("MSAA: "); ImGui::SameLine();
1087 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1088 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1089 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1090 ImGui::RadioButton("16", &sampleCount, 16);
1091
1092 if (sampleCount != params.fMSAASampleCount) {
1093 params.fMSAASampleCount = sampleCount;
1094 paramsChanged = true;
1095 }
1096 }
1097
Brian Osman8a9de3d2017-03-01 14:59:05 -05001098 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001099 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001100 auto prButton = [&](GpuPathRenderers x) {
1101 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001102 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1103 params.fGrContextOptions.fGpuPathRenderers = x;
1104 paramsChanged = true;
1105 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001106 }
1107 };
1108
1109 if (!ctx) {
1110 ImGui::RadioButton("Software", true);
1111 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001112 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001113 prButton(GpuPathRenderers::kAll);
1114 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1115 prButton(GpuPathRenderers::kStencilAndCover);
1116 }
1117 if (ctx->caps()->sampleShadingSupport()) {
1118 prButton(GpuPathRenderers::kMSAA);
1119 }
1120 prButton(GpuPathRenderers::kTessellating);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001121 prButton(GpuPathRenderers::kNone);
1122 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001123 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001124 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001125 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1126 prButton(GpuPathRenderers::kCoverageCounting);
1127 }
Jim Van Verth83010462017-03-16 08:45:39 -04001128 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001129 prButton(GpuPathRenderers::kTessellating);
1130 prButton(GpuPathRenderers::kNone);
1131 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001132 ImGui::TreePop();
1133 }
Brian Osman621491e2017-02-28 15:45:01 -05001134 }
1135
Brian Osman79086b92017-02-10 13:36:16 -05001136 if (ImGui::CollapsingHeader("Slide")) {
1137 static ImGuiTextFilter filter;
1138 filter.Draw();
1139 int previousSlide = fCurrentSlide;
1140 fCurrentSlide = 0;
1141 for (auto slide : fSlides) {
1142 if (filter.PassFilter(slide->getName().c_str())) {
1143 ImGui::BulletText("%s", slide->getName().c_str());
1144 if (ImGui::IsItemClicked()) {
1145 setupCurrentSlide(previousSlide);
1146 break;
1147 }
1148 }
1149 ++fCurrentSlide;
1150 }
1151 if (fCurrentSlide >= fSlides.count()) {
1152 fCurrentSlide = previousSlide;
1153 }
1154 }
Brian Osmana109e392017-02-24 09:49:14 -05001155
1156 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001157 ColorMode newMode = fColorMode;
1158 auto cmButton = [&](ColorMode mode, const char* label) {
1159 if (ImGui::RadioButton(label, mode == fColorMode)) {
1160 newMode = mode;
1161 }
1162 };
1163
1164 cmButton(ColorMode::kLegacy, "Legacy 8888");
1165 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1166 "Color Managed 8888 (Nonlinear blending)");
1167 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1168 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1169
1170 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001171 // It isn't safe to switch color mode now (in the middle of painting). We might
1172 // tear down the back-end, etc... Defer this change until the next onIdle.
1173 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001174 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001175 });
Brian Osmana109e392017-02-24 09:49:14 -05001176 }
1177
1178 // Pick from common gamuts:
1179 int primariesIdx = 4; // Default: Custom
1180 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1181 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1182 primariesIdx = i;
1183 break;
1184 }
1185 }
1186
1187 if (ImGui::Combo("Primaries", &primariesIdx,
1188 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1189 if (primariesIdx >= 0 && primariesIdx <= 3) {
1190 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1191 }
1192 }
1193
1194 // Allow direct editing of gamut
1195 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1196 }
Brian Osman79086b92017-02-10 13:36:16 -05001197 }
Brian Salomon99a33902017-03-07 15:16:34 -05001198 if (paramsChanged) {
1199 fDeferredActions.push_back([=]() {
1200 fWindow->setRequestedDisplayParams(params);
1201 fWindow->inval();
1202 this->updateTitle();
1203 });
1204 }
Brian Osman79086b92017-02-10 13:36:16 -05001205 ImGui::End();
1206 }
1207
Brian Osmanf6877092017-02-13 09:39:57 -05001208 SkPaint zoomImagePaint;
1209 if (fShowZoomWindow && fLastImage) {
1210 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1211 static int zoomFactor = 4;
1212 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1213
Mike Reed0acd7952017-04-28 11:12:19 -04001214 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001215 zoomImagePaint.setColor(SK_ColorWHITE);
1216
1217 // Zoom by shrinking the corner UVs towards the mouse cursor
1218 ImVec2 mousePos = ImGui::GetMousePos();
1219 ImVec2 avail = ImGui::GetContentRegionAvail();
1220
1221 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1222 (avail.y * 0.5f) / zoomFactor);
1223 ImGui::Image(&zoomImagePaint, avail,
1224 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1225 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1226 }
1227
1228 ImGui::End();
1229 }
1230
Brian Osman79086b92017-02-10 13:36:16 -05001231 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1232 // (widgets, etc...) that have been issued
1233 ImGui::Render();
1234
1235 // Then we fetch the most recent data, and convert it so we can render with Skia
1236 const ImDrawData* drawData = ImGui::GetDrawData();
1237 SkTDArray<SkPoint> pos;
1238 SkTDArray<SkPoint> uv;
1239 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001240
1241 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1242 const ImDrawList* drawList = drawData->CmdLists[i];
1243
1244 // De-interleave all vertex data (sigh), convert to Skia types
1245 pos.rewind(); uv.rewind(); color.rewind();
1246 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1247 const ImDrawVert& vert = drawList->VtxBuffer[i];
1248 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1249 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1250 color.push(vert.col);
1251 }
1252 // ImGui colors are RGBA
1253 SkSwapRB(color.begin(), color.begin(), color.count());
1254
1255 int indexOffset = 0;
1256
1257 // Draw everything with canvas.drawVertices...
1258 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1259 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1260
1261 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1262 if (drawCmd->UserCallback) {
1263 drawCmd->UserCallback(drawList, drawCmd);
1264 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001265 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1266 SkASSERT(paint);
1267
Brian Osman79086b92017-02-10 13:36:16 -05001268 canvas->save();
1269 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1270 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001271 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1272 drawList->VtxBuffer.size(), pos.begin(),
1273 uv.begin(), color.begin(),
1274 drawCmd->ElemCount,
1275 drawList->IdxBuffer.begin() + indexOffset),
1276 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001277 indexOffset += drawCmd->ElemCount;
1278 canvas->restore();
1279 }
1280 }
1281 }
1282}
1283
liyuqian2edb0f42016-07-06 14:11:32 -07001284void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001285 for (int i = 0; i < fDeferredActions.count(); ++i) {
1286 fDeferredActions[i]();
1287 }
1288 fDeferredActions.reset();
1289
Brian Osman1df161a2017-02-09 12:10:20 -05001290 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001291 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001292 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1293 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1294
Brian Osman79086b92017-02-10 13:36:16 -05001295 ImGuiIO& io = ImGui::GetIO();
1296 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001297 fWindow->inval();
1298 }
jvanverth9f372462016-04-06 06:08:59 -07001299}
liyuqiane5a6cd92016-05-27 08:52:52 -07001300
1301void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001302 if (!fWindow) {
1303 return;
1304 }
1305 if (fWindow->sampleCount() < 0) {
1306 return; // Surface hasn't been created yet.
1307 }
1308
liyuqianb73c24b2016-06-03 08:47:23 -07001309 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001310 Json::Value slideState(Json::objectValue);
1311 slideState[kName] = kSlideStateName;
1312 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001313 if (fAllSlideNames.size() == 0) {
1314 for(auto slide : fSlides) {
1315 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1316 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001317 }
liyuqian1f508fd2016-06-07 06:57:40 -07001318 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001319
liyuqianb73c24b2016-06-03 08:47:23 -07001320 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001321 Json::Value backendState(Json::objectValue);
1322 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001323 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001324 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001325 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001326 backendState[kOptions].append(Json::Value(str));
1327 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001328
csmartdalton578f0642017-02-24 16:04:47 -07001329 // MSAA state
1330 Json::Value msaaState(Json::objectValue);
1331 msaaState[kName] = kMSAAStateName;
1332 msaaState[kValue] = fWindow->sampleCount();
1333 msaaState[kOptions] = Json::Value(Json::arrayValue);
1334 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1335 msaaState[kOptions].append(Json::Value(0));
1336 } else {
1337 for (int msaa : {0, 4, 8, 16}) {
1338 msaaState[kOptions].append(Json::Value(msaa));
1339 }
1340 }
1341
csmartdalton61cd31a2017-02-27 17:00:53 -07001342 // Path renderer state
1343 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1344 Json::Value prState(Json::objectValue);
1345 prState[kName] = kPathRendererStateName;
1346 prState[kValue] = gPathRendererNames[pr];
1347 prState[kOptions] = Json::Value(Json::arrayValue);
1348 const GrContext* ctx = fWindow->getGrContext();
1349 if (!ctx) {
1350 prState[kOptions].append("Software");
1351 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001352 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001353 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1354 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1355 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1356 }
1357 if (ctx->caps()->sampleShadingSupport()) {
1358 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1359 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001360 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001361 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1362 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001363 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001364 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001365 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1366 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1367 }
Jim Van Verth83010462017-03-16 08:45:39 -04001368 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001369 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001370 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1371 }
1372
Brian Salomon99a33902017-03-07 15:16:34 -05001373 // Instanced rendering state
1374 Json::Value instState(Json::objectValue);
1375 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001376 instState[kValue] = kOFF;
1377 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001378 if (ctx) {
1379 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1380 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001381 }
Brian Salomon99a33902017-03-07 15:16:34 -05001382 instState[kOptions].append(kOFF);
1383 instState[kOptions].append(kON);
1384 }
1385
liyuqianb73c24b2016-06-03 08:47:23 -07001386 // Softkey state
1387 Json::Value softkeyState(Json::objectValue);
1388 softkeyState[kName] = kSoftkeyStateName;
1389 softkeyState[kValue] = kSoftkeyHint;
1390 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1391 softkeyState[kOptions].append(kSoftkeyHint);
1392 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1393 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1394 }
1395
liyuqian1f508fd2016-06-07 06:57:40 -07001396 // FPS state
1397 Json::Value fpsState(Json::objectValue);
1398 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001399 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1400 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1401 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1402 fAnimateTimes[idx],
1403 fPaintTimes[idx],
1404 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001405 fpsState[kOptions] = Json::Value(Json::arrayValue);
1406
liyuqiane5a6cd92016-05-27 08:52:52 -07001407 Json::Value state(Json::arrayValue);
1408 state.append(slideState);
1409 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001410 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001411 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001412 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001413 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001414 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001415
1416 fWindow->setUIState(state);
1417}
1418
1419void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001420 // For those who will add more features to handle the state change in this function:
1421 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1422 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1423 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001424 if (stateName.equals(kSlideStateName)) {
1425 int previousSlide = fCurrentSlide;
1426 fCurrentSlide = 0;
1427 for(auto slide : fSlides) {
1428 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001429 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001430 break;
1431 }
1432 fCurrentSlide++;
1433 }
1434 if (fCurrentSlide >= fSlides.count()) {
1435 fCurrentSlide = previousSlide;
1436 SkDebugf("Slide not found: %s", stateValue.c_str());
1437 }
liyuqian6cb70252016-06-02 12:16:25 -07001438 } else if (stateName.equals(kBackendStateName)) {
1439 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1440 if (stateValue.equals(kBackendTypeStrings[i])) {
1441 if (fBackendType != i) {
1442 fBackendType = (sk_app::Window::BackendType)i;
1443 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001444 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001445 }
1446 break;
1447 }
1448 }
csmartdalton578f0642017-02-24 16:04:47 -07001449 } else if (stateName.equals(kMSAAStateName)) {
1450 DisplayParams params = fWindow->getRequestedDisplayParams();
1451 int sampleCount = atoi(stateValue.c_str());
1452 if (sampleCount != params.fMSAASampleCount) {
1453 params.fMSAASampleCount = sampleCount;
1454 fWindow->setRequestedDisplayParams(params);
1455 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001456 this->updateTitle();
1457 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001458 }
1459 } else if (stateName.equals(kPathRendererStateName)) {
1460 DisplayParams params = fWindow->getRequestedDisplayParams();
1461 for (const auto& pair : gPathRendererNames) {
1462 if (pair.second == stateValue.c_str()) {
1463 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1464 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1465 fWindow->setRequestedDisplayParams(params);
1466 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001467 this->updateTitle();
1468 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001469 }
1470 break;
1471 }
csmartdalton578f0642017-02-24 16:04:47 -07001472 }
Brian Salomon99a33902017-03-07 15:16:34 -05001473 } else if (stateName.equals(kInstancedRenderingStateName)) {
1474 DisplayParams params = fWindow->getRequestedDisplayParams();
1475 bool value = !strcmp(stateValue.c_str(), kON);
1476 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1477 params.fGrContextOptions.fEnableInstancedRendering = value;
1478 fWindow->setRequestedDisplayParams(params);
1479 fWindow->inval();
1480 this->updateTitle();
1481 this->updateUIState();
1482 }
liyuqianb73c24b2016-06-03 08:47:23 -07001483 } else if (stateName.equals(kSoftkeyStateName)) {
1484 if (!stateValue.equals(kSoftkeyHint)) {
1485 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001486 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001487 }
liyuqian2edb0f42016-07-06 14:11:32 -07001488 } else if (stateName.equals(kRefreshStateName)) {
1489 // This state is actually NOT in the UI state.
1490 // We use this to allow Android to quickly set bool fRefresh.
1491 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001492 } else {
1493 SkDebugf("Unknown stateName: %s", stateName.c_str());
1494 }
1495}
Brian Osman79086b92017-02-10 13:36:16 -05001496
1497bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1498 return fCommands.onKey(key, state, modifiers);
1499}
1500
1501bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001502 if (fSlides[fCurrentSlide]->onChar(c)) {
1503 fWindow->inval();
1504 return true;
1505 }
1506
Brian Osman79086b92017-02-10 13:36:16 -05001507 return fCommands.onChar(c, modifiers);
1508}