blob: dd8d3303f8e99872c86e5ec0771f566a6923526f [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"
csmartdalton008b9d82017-02-22 12:00:42 -070022#include "SkCommonFlagsPathRenderer.h"
liyuqian74959a12016-06-16 14:10:34 -070023#include "SkDashPathEffect.h"
Brian Osman53136aa2017-07-20 15:43:35 -040024#include "SkEventTracingPriv.h"
Greg Daniel285db442016-10-14 09:12:53 -040025#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050026#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070027#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070028#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070029#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050030#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070031#include "SkRandom.h"
Yuqian Li399b3c22017-08-03 11:08:15 -040032#include "SkScan.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070033#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070034#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050035#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050036#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070037#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040038#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070039
Brian Osman79086b92017-02-10 13:36:16 -050040#include "imgui.h"
41
Chris Dalton1a325d22017-07-14 15:17:41 -060042#include "ccpr/GrCoverageCountingPathRenderer.h"
43
csmartdalton578f0642017-02-24 16:04:47 -070044#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070045#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070046
jvanverth34524262016-05-04 13:49:13 -070047using namespace sk_app;
48
csmartdalton61cd31a2017-02-27 17:00:53 -070049using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
50static 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
Jim Van Verth6f449692017-02-14 15:16:46 -0500143DEFINE_string(slide, "", "Start on this sample.");
144DEFINE_bool(list, false, "List samples?");
145
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
csmartdalton578f0642017-02-24 16:04:47 -0700162DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700163DEFINE_pathrenderer_flag;
164
Brian Salomon41eac792017-03-08 14:03:56 -0500165DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
Brian Osman53136aa2017-07-20 15:43:35 -0400166DECLARE_int32(threads)
Brian Salomon41eac792017-03-08 14:03:56 -0500167
Brian Salomon194db172017-08-17 14:37:06 -0400168const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700169 "OpenGL",
Brian Salomon194db172017-08-17 14:37:06 -0400170#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
171 "ANGLE",
172#endif
jvanverth063ece72016-06-17 09:29:14 -0700173#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700174 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700175#endif
csmartdalton578f0642017-02-24 16:04:47 -0700176 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700177};
178
bsalomon6c471f72016-07-26 12:56:32 -0700179static sk_app::Window::BackendType get_backend_type(const char* str) {
180#ifdef SK_VULKAN
181 if (0 == strcmp(str, "vk")) {
182 return sk_app::Window::kVulkan_BackendType;
183 } else
184#endif
Brian Salomon194db172017-08-17 14:37:06 -0400185#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
186 if (0 == strcmp(str, "angle")) {
187 return sk_app::Window::kANGLE_BackendType;
188 } else
189#endif
bsalomon6c471f72016-07-26 12:56:32 -0700190 if (0 == strcmp(str, "gl")) {
191 return sk_app::Window::kNativeGL_BackendType;
192 } else if (0 == strcmp(str, "sw")) {
193 return sk_app::Window::kRaster_BackendType;
194 } else {
195 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
196 return sk_app::Window::kRaster_BackendType;
197 }
198}
199
Brian Osmana109e392017-02-24 09:49:14 -0500200static SkColorSpacePrimaries gSrgbPrimaries = {
201 0.64f, 0.33f,
202 0.30f, 0.60f,
203 0.15f, 0.06f,
204 0.3127f, 0.3290f };
205
206static SkColorSpacePrimaries gAdobePrimaries = {
207 0.64f, 0.33f,
208 0.21f, 0.71f,
209 0.15f, 0.06f,
210 0.3127f, 0.3290f };
211
212static SkColorSpacePrimaries gP3Primaries = {
213 0.680f, 0.320f,
214 0.265f, 0.690f,
215 0.150f, 0.060f,
216 0.3127f, 0.3290f };
217
218static SkColorSpacePrimaries gRec2020Primaries = {
219 0.708f, 0.292f,
220 0.170f, 0.797f,
221 0.131f, 0.046f,
222 0.3127f, 0.3290f };
223
224struct NamedPrimaries {
225 const char* fName;
226 SkColorSpacePrimaries* fPrimaries;
227} gNamedPrimaries[] = {
228 { "sRGB", &gSrgbPrimaries },
229 { "AdobeRGB", &gAdobePrimaries },
230 { "P3", &gP3Primaries },
231 { "Rec. 2020", &gRec2020Primaries },
232};
233
234static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
235 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
236}
237
liyuqiane5a6cd92016-05-27 08:52:52 -0700238const char* kName = "name";
239const char* kValue = "value";
240const char* kOptions = "options";
241const char* kSlideStateName = "Slide";
242const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700243const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700244const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500245const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700246const char* kSoftkeyStateName = "Softkey";
247const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700248const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700249const char* kON = "ON";
250const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700251const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700252
jvanverth34524262016-05-04 13:49:13 -0700253Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700254 : fCurrentMeasurement(0)
255 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700256 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500257 , fShowImGuiDebugWindow(false)
258 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500259 , fShowZoomWindow(false)
260 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700261 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500262 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500263 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700264 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400265 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700266{
Greg Daniel285db442016-10-14 09:12:53 -0400267 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700268
269 static SkOnce initPathRendererNames;
270 initPathRendererNames([]() {
271 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
272 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
273 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400274 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600275 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500276 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700277 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
278 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
279 });
280
Brian Osman1df161a2017-02-09 12:10:20 -0500281 memset(fPaintTimes, 0, sizeof(fPaintTimes));
282 memset(fFlushTimes, 0, sizeof(fFlushTimes));
283 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700284
jvanverth2bb3b6d2016-04-08 07:24:09 -0700285 SkDebugf("Command line arguments: ");
286 for (int i = 1; i < argc; ++i) {
287 SkDebugf("%s ", argv[i]);
288 }
289 SkDebugf("\n");
290
291 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500292#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400293 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500294#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700295
Brian Osmanbc8150f2017-07-24 11:38:01 -0400296 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400297 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400298
bsalomon6c471f72016-07-26 12:56:32 -0700299 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700300 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700301
csmartdalton578f0642017-02-24 16:04:47 -0700302 DisplayParams displayParams;
303 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500304 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700305 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700306 fWindow->setRequestedDisplayParams(displayParams);
307
jvanverth9f372462016-04-06 06:08:59 -0700308 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700309 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700310 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700311 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700312 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700313 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500314 fWindow->registerMouseFunc(on_mouse_handler, this);
315 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
316 fWindow->registerKeyFunc(on_key_handler, this);
317 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700318
brianosman622c8d52016-05-10 06:50:49 -0700319 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500320 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
321 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
322 fWindow->inval();
323 });
324 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
325 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
326 fWindow->inval();
327 });
Brian Osmanf6877092017-02-13 09:39:57 -0500328 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
329 this->fShowZoomWindow = !this->fShowZoomWindow;
330 fWindow->inval();
331 });
brianosman622c8d52016-05-10 06:50:49 -0700332 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
333 this->fDisplayStats = !this->fDisplayStats;
334 fWindow->inval();
335 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500336 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500337 switch (fColorMode) {
338 case ColorMode::kLegacy:
339 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
340 break;
341 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
342 this->setColorMode(ColorMode::kColorManagedSRGB8888);
343 break;
344 case ColorMode::kColorManagedSRGB8888:
345 this->setColorMode(ColorMode::kColorManagedLinearF16);
346 break;
347 case ColorMode::kColorManagedLinearF16:
348 this->setColorMode(ColorMode::kLegacy);
349 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500350 }
brianosman622c8d52016-05-10 06:50:49 -0700351 });
352 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
353 int previousSlide = fCurrentSlide;
354 fCurrentSlide++;
355 if (fCurrentSlide >= fSlides.count()) {
356 fCurrentSlide = 0;
357 }
358 this->setupCurrentSlide(previousSlide);
359 });
360 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
361 int previousSlide = fCurrentSlide;
362 fCurrentSlide--;
363 if (fCurrentSlide < 0) {
364 fCurrentSlide = fSlides.count() - 1;
365 }
366 this->setupCurrentSlide(previousSlide);
367 });
368 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
369 this->changeZoomLevel(1.f / 32.f);
370 fWindow->inval();
371 });
372 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
373 this->changeZoomLevel(-1.f / 32.f);
374 fWindow->inval();
375 });
jvanverthaf236b52016-05-20 06:01:06 -0700376 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400377 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
378 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500379 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400380#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
381 if (newBackend == sk_app::Window::kVulkan_BackendType) {
382 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
383 sk_app::Window::kBackendTypeCount);
384 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
385 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500386 }
387#endif
Brian Osman621491e2017-02-28 15:45:01 -0500388 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700389 });
brianosman622c8d52016-05-10 06:50:49 -0700390
Yuqian Li399b3c22017-08-03 11:08:15 -0400391 fCommands.addCommand('A', "AAA", "Toggle analytic AA", [this]() {
392 if (!gSkUseAnalyticAA) {
393 gSkUseAnalyticAA = true;
394 } else if (!gSkForceAnalyticAA) {
395 gSkForceAnalyticAA = true;
396 } else {
397 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
398 }
399 this->updateTitle();
400 fWindow->inval();
401 });
402 fCommands.addCommand('D', "DAA", "Toggle delta AA", [this]() {
403 if (!gSkUseDeltaAA) {
404 gSkUseDeltaAA = true;
405 } else if (!gSkForceDeltaAA) {
406 gSkForceDeltaAA = true;
407 } else {
408 gSkUseDeltaAA = gSkForceDeltaAA = false;
409 }
410 this->updateTitle();
411 fWindow->inval();
412 });
413
jvanverth2bb3b6d2016-04-08 07:24:09 -0700414 // set up slides
415 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500416 this->setStartupSlide();
417 if (FLAGS_list) {
418 this->listNames();
419 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700420
djsollen12d62a72016-04-21 07:59:44 -0700421 fAnimTimer.run();
422
Brian Osman79086b92017-02-10 13:36:16 -0500423 // ImGui initialization:
424 ImGuiIO& io = ImGui::GetIO();
425 io.DisplaySize.x = static_cast<float>(fWindow->width());
426 io.DisplaySize.y = static_cast<float>(fWindow->height());
427
428 // Keymap...
429 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
430 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
431 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
432 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
433 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
434 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
435 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
436 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
437 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
438 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
439 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
440 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
441 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
442 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
443 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
444 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
445 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
446 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
447 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
448
449 int w, h;
450 unsigned char* pixels;
451 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
452 SkImageInfo info = SkImageInfo::MakeA8(w, h);
453 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500454 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
455 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400456 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500457 fImGuiFontPaint.setShader(fontShader);
458 fImGuiFontPaint.setColor(SK_ColorWHITE);
459 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
460 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500461
Brian Osmana109e392017-02-24 09:49:14 -0500462 auto gamutImage = GetResourceAsImage("gamut.png");
463 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400464 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500465 }
466 fImGuiGamutPaint.setColor(SK_ColorWHITE);
467 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
468
csmartdalton578f0642017-02-24 16:04:47 -0700469 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700470}
471
jvanverth34524262016-05-04 13:49:13 -0700472void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700473 fAllSlideNames = Json::Value(Json::arrayValue);
474
jvanverth2bb3b6d2016-04-08 07:24:09 -0700475 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
476 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400477 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700478
479 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
480 sk_sp<Slide> slide(new GMSlide(gm.release()));
481 fSlides.push_back(slide);
482 }
483
484 gms = gms->next();
485 }
486
487 // reverse array
488 for (int i = 0; i < fSlides.count()/2; ++i) {
489 sk_sp<Slide> temp = fSlides[i];
490 fSlides[i] = fSlides[fSlides.count() - i - 1];
491 fSlides[fSlides.count() - i - 1] = temp;
492 }
493
jvanverthc7027ab2016-06-16 09:52:35 -0700494 // samples
495 const SkViewRegister* reg = SkViewRegister::Head();
496 while (reg) {
497 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700498 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
499 fSlides.push_back(slide);
500 }
jvanverthc7027ab2016-06-16 09:52:35 -0700501 reg = reg->next();
502 }
503
jvanverth2bb3b6d2016-04-08 07:24:09 -0700504 // SKPs
505 for (int i = 0; i < FLAGS_skps.count(); i++) {
506 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700507 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
508 continue;
509 }
510
jvanverth2bb3b6d2016-04-08 07:24:09 -0700511 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700512 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700513 if (slide) {
514 fSlides.push_back(slide);
515 }
516 } else {
517 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700518 SkString skpName;
519 while (it.next(&skpName)) {
520 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
521 continue;
522 }
523
524 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
525 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700526 if (slide) {
527 fSlides.push_back(slide);
528 }
529 }
530 }
531 }
liyuqian6f163d22016-06-13 12:26:45 -0700532
533 // JPGs
534 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
535 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
536 SkString jpgName;
537 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700538 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
539 continue;
540 }
541
liyuqian6f163d22016-06-13 12:26:45 -0700542 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
543 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
544 if (slide) {
545 fSlides.push_back(slide);
546 }
547 }
548 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700549}
550
551
jvanverth34524262016-05-04 13:49:13 -0700552Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700553 fWindow->detach();
554 delete fWindow;
555}
556
brianosman05de2162016-05-06 13:28:57 -0700557void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700558 if (!fWindow) {
559 return;
560 }
561 if (fWindow->sampleCount() < 0) {
562 return; // Surface hasn't been created yet.
563 }
564
jvanverth34524262016-05-04 13:49:13 -0700565 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700566 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700567
Yuqian Li399b3c22017-08-03 11:08:15 -0400568 if (gSkUseDeltaAA) {
569 if (gSkForceDeltaAA) {
570 title.append(" <FDAA>");
571 } else {
572 title.append(" <DAA>");
573 }
574 } else if (gSkUseAnalyticAA) {
575 if (gSkForceAnalyticAA) {
576 title.append(" <FAAA>");
577 } else {
578 title.append(" <AAA>");
579 }
580 }
581
Brian Osman92004802017-03-06 11:47:26 -0500582 switch (fColorMode) {
583 case ColorMode::kLegacy:
584 title.append(" Legacy 8888");
585 break;
586 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
587 title.append(" ColorManaged 8888 (Nonlinear blending)");
588 break;
589 case ColorMode::kColorManagedSRGB8888:
590 title.append(" ColorManaged 8888");
591 break;
592 case ColorMode::kColorManagedLinearF16:
593 title.append(" ColorManaged F16");
594 break;
595 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500596
Brian Osman92004802017-03-06 11:47:26 -0500597 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500598 int curPrimaries = -1;
599 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
600 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
601 curPrimaries = i;
602 break;
603 }
604 }
605 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700606 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500607
csmartdalton578f0642017-02-24 16:04:47 -0700608 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700609 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700610 if (int msaa = fWindow->sampleCount()) {
611 title.appendf(" MSAA: %i", msaa);
612 }
613 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700614
615 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
616 if (GpuPathRenderers::kAll != pr) {
617 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
618 }
619
brianosman05de2162016-05-06 13:28:57 -0700620 fWindow->setTitle(title.c_str());
621}
622
Jim Van Verth6f449692017-02-14 15:16:46 -0500623void Viewer::setStartupSlide() {
624
625 if (!FLAGS_slide.isEmpty()) {
626 int count = fSlides.count();
627 for (int i = 0; i < count; i++) {
628 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
629 fCurrentSlide = i;
630 return;
631 }
632 }
633
634 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
635 this->listNames();
636 }
637
638 fCurrentSlide = 0;
639}
640
641void Viewer::listNames() {
642 int count = fSlides.count();
643 SkDebugf("All Slides:\n");
644 for (int i = 0; i < count; i++) {
645 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
646 }
647}
648
brianosman05de2162016-05-06 13:28:57 -0700649void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700650 if (fCurrentSlide == previousSlide) {
651 return; // no change; do nothing
652 }
liyuqian6f163d22016-06-13 12:26:45 -0700653 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700654 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700655
liyuqiane46e4f02016-05-20 07:32:19 -0700656 fGesture.reset();
657 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700658
Brian Osman42bb6ac2017-06-05 08:46:04 -0400659 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
660 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
661 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
662
663 // Start with a matrix that scales the slide to the available screen space
664 if (fWindow->scaleContentToFit()) {
665 if (windowRect.width() > 0 && windowRect.height() > 0) {
666 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700667 }
668 }
669
Brian Osman42bb6ac2017-06-05 08:46:04 -0400670 // Prevent the user from dragging content so far outside the window they can't find it again
671 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700672
brianosman05de2162016-05-06 13:28:57 -0700673 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700674 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700675 if (previousSlide >= 0) {
676 fSlides[previousSlide]->unload();
677 }
jvanverthc265a922016-04-08 12:51:45 -0700678 fWindow->inval();
679}
680
681#define MAX_ZOOM_LEVEL 8
682#define MIN_ZOOM_LEVEL -8
683
jvanverth34524262016-05-04 13:49:13 -0700684void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700685 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400686 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700687}
688
liyuqiand3cdbca2016-05-17 12:44:20 -0700689SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700690 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700691
Brian Osman42bb6ac2017-06-05 08:46:04 -0400692 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
693 : SK_Scalar1 + fZoomLevel;
694 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700695 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400696 m.preConcat(fDefaultMatrix);
697 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700698
liyuqiand3cdbca2016-05-17 12:44:20 -0700699 return m;
jvanverthc265a922016-04-08 12:51:45 -0700700}
701
Brian Osman621491e2017-02-28 15:45:01 -0500702void Viewer::setBackend(sk_app::Window::BackendType backendType) {
703 fBackendType = backendType;
704
705 fWindow->detach();
706
707#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Salomon194db172017-08-17 14:37:06 -0400708 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
709 // on Windows, so we just delete the window and recreate it.
Brian Osman80a82df2017-07-12 15:42:51 -0400710 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
Brian Salomon194db172017-08-17 14:37:06 -0400711 sk_app::Window::kNativeGL_BackendType == fBackendType
712#if SK_ANGLE
713 || sk_app::Window::kANGLE_BackendType == fBackendType
714#endif
715 ) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400716 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500717 delete fWindow;
718 fWindow = Window::CreateNativeWindow(nullptr);
719
720 // re-register callbacks
721 fCommands.attach(fWindow);
722 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
723 fWindow->registerPaintFunc(on_paint_handler, this);
724 fWindow->registerTouchFunc(on_touch_handler, this);
725 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
726 fWindow->registerMouseFunc(on_mouse_handler, this);
727 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
728 fWindow->registerKeyFunc(on_key_handler, this);
729 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400730 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
731 // will still include our correct sample count. But the re-created fWindow will lose that
732 // information. On Windows, we need to re-create the window when changing sample count,
733 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
734 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
735 // as if we had never changed windows at all).
736 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500737 }
738#endif
739
740 fWindow->attach(fBackendType);
741}
742
Brian Osman92004802017-03-06 11:47:26 -0500743void Viewer::setColorMode(ColorMode colorMode) {
744 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700745
Brian Osmanf750fbc2017-02-08 10:47:28 -0500746 // 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 -0400747 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700748 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500749 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400750 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
751 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500752 if (wasInLegacy != wantLegacy) {
753 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700754 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500755 }
756
757 this->updateTitle();
758 fWindow->inval();
759}
760
761void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500762 SkAutoCanvasRestore autorestore(canvas, false);
763
Brian Osmanf750fbc2017-02-08 10:47:28 -0500764 // By default, we render directly into the window's surface/canvas
765 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500766 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700767
Brian Osmane0d4fba2017-03-15 10:24:55 -0400768 // If we're in any of the color managed modes, construct the color space we're going to use
769 sk_sp<SkColorSpace> cs = nullptr;
770 if (ColorMode::kLegacy != fColorMode) {
771 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
772 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400773 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400774 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
775 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
776 }
777
778 // 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 -0500779 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500780 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500781 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500782 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400783 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
784 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
785
Brian Osman92004802017-03-06 11:47:26 -0500786 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
787 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400788 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
789 // with a special canvas (below) that has the color space attached
790 sk_sp<SkColorSpace> offscreenColorSpace =
791 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500792 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400793 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500794 offscreenSurface = canvas->makeSurface(info);
795 slideCanvas = offscreenSurface->getCanvas();
796 }
797
Brian Osmane0d4fba2017-03-15 10:24:55 -0400798 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
799 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
800 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
801 slideCanvas = xformCanvas.get();
802 }
803
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500804 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500805 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500806 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500807 // Time the painting logic of the slide
808 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500809 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500810 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500811 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500812
813 // Force a flush so we can time that, too
814 startTime = SkTime::GetMSecs();
815 slideCanvas->flush();
816 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500817
818 // If we rendered offscreen, snap an image and push the results to the window's canvas
819 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500820 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500821
822 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400823 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500824 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400825 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500826 SkPaint paint;
827 paint.setBlendMode(SkBlendMode::kSrc);
828 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700829 }
liyuqian6f163d22016-06-13 12:26:45 -0700830}
831
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700832void Viewer::onBackendCreated() {
833 this->updateTitle();
834 this->updateUIState();
835 this->setupCurrentSlide(-1);
836 fWindow->show();
837 fWindow->inval();
838}
Jim Van Verth6f449692017-02-14 15:16:46 -0500839
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700840void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500841 // Update ImGui input
842 ImGuiIO& io = ImGui::GetIO();
843 io.DeltaTime = 1.0f / 60.0f;
844 io.DisplaySize.x = static_cast<float>(fWindow->width());
845 io.DisplaySize.y = static_cast<float>(fWindow->height());
846
847 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
848 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
849 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
850
851 ImGui::NewFrame();
852
Brian Osmanf750fbc2017-02-08 10:47:28 -0500853 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700854
Brian Osman1df161a2017-02-09 12:10:20 -0500855 // Advance our timing bookkeeping
856 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
857 SkASSERT(fCurrentMeasurement < kMeasurementCount);
858
859 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700860 if (fDisplayStats) {
861 drawStats(canvas);
862 }
brianosman622c8d52016-05-10 06:50:49 -0700863 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700864
Brian Osman79086b92017-02-10 13:36:16 -0500865 drawImGui(canvas);
866
Brian Osman1df161a2017-02-09 12:10:20 -0500867 // Update the FPS
868 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700869}
870
jvanverth814e38d2016-06-06 08:48:47 -0700871bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400872 if (GestureDevice::kMouse == fGestureDevice) {
873 return false;
874 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700875 void* castedOwner = reinterpret_cast<void*>(owner);
876 switch (state) {
877 case Window::kUp_InputState: {
878 fGesture.touchEnd(castedOwner);
879 break;
880 }
881 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400882 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700883 break;
884 }
885 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400886 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700887 break;
888 }
889 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400890 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700891 fWindow->inval();
892 return true;
893}
894
Jim Van Verthe7705782017-05-04 14:00:59 -0400895bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400896 if (GestureDevice::kTouch == fGestureDevice) {
897 return false;
898 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400899 switch (state) {
900 case Window::kUp_InputState: {
901 fGesture.touchEnd(nullptr);
902 break;
903 }
904 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400905 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400906 break;
907 }
908 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400909 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400910 break;
911 }
912 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400913 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400914 fWindow->inval();
915 return true;
916}
917
jvanverth34524262016-05-04 13:49:13 -0700918void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700919 static const float kPixelPerMS = 2.0f;
920 static const int kDisplayWidth = 130;
921 static const int kDisplayHeight = 100;
922 static const int kDisplayPadding = 10;
923 static const int kGraphPadding = 3;
924 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
925
Mike Reed3661bc92017-02-22 13:21:42 -0500926 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700927 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
928 SkIntToScalar(kDisplayPadding),
929 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
930 SkPaint paint;
931 canvas->save();
932
933 canvas->clipRect(rect);
934 paint.setColor(SK_ColorBLACK);
935 canvas->drawRect(rect, paint);
936 // draw the 16ms line
937 paint.setColor(SK_ColorLTGRAY);
938 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
939 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
940 paint.setColor(SK_ColorRED);
941 paint.setStyle(SkPaint::kStroke_Style);
942 canvas->drawRect(rect, paint);
943
944 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
945 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700946 int i = fCurrentMeasurement;
947 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500948 // Round to nearest values
949 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
950 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
951 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
952 int startY = SkScalarTruncToInt(rect.fBottom);
953 int endY = startY - flushHeight;
954 paint.setColor(SK_ColorRED);
955 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
956 SkIntToScalar(x), SkIntToScalar(endY), paint);
957 startY = endY;
958 endY = startY - paintHeight;
959 paint.setColor(SK_ColorGREEN);
960 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
961 SkIntToScalar(x), SkIntToScalar(endY), paint);
962 startY = endY;
963 endY = startY - animateHeight;
964 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700965 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
966 SkIntToScalar(x), SkIntToScalar(endY), paint);
967 i++;
968 i &= (kMeasurementCount - 1); // fast mod
969 x += xStep;
970 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700971
972 canvas->restore();
973}
974
Brian Osmana109e392017-02-24 09:49:14 -0500975static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
976 const ImVec2& pos, const ImVec2& size) {
977 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
978 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
979
980 // Invisible 10x10 button
981 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
982 ImGui::InvisibleButton(label, ImVec2(10, 10));
983
984 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
985 ImGuiIO& io = ImGui::GetIO();
986 // Normalized mouse position, relative to our gamut box
987 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
988 // Clamp to edge of box, convert back to primary scale
989 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
990 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
991 }
992
993 if (ImGui::IsItemHovered()) {
994 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
995 }
996
997 // Return screen coordinates for the caller. We could just return center here, but we'd have
998 // one frame of lag during drag.
999 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1000}
1001
1002static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1003 ImDrawList* drawList = ImGui::GetWindowDrawList();
1004
1005 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1006 // width, and scale the height to maintain aspect ratio.
1007 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1008 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1009 ImVec2 pos = ImGui::GetCursorScreenPos();
1010
1011 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1012 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1013 // Magic numbers are pixel locations of the origin and upper-right corner.
1014 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1015 ImVec2(242, 61), ImVec2(1897, 1922));
1016 ImVec2 endPos = ImGui::GetCursorPos();
1017
1018 // Primary markers
1019 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1020 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1021 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1022 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1023
1024 // Gamut triangle
1025 drawList->AddCircle(r, 5.0f, 0xFF000040);
1026 drawList->AddCircle(g, 5.0f, 0xFF004000);
1027 drawList->AddCircle(b, 5.0f, 0xFF400000);
1028 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1029 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1030
1031 // Re-position cursor immediate after the diagram for subsequent controls
1032 ImGui::SetCursorPos(endPos);
1033}
1034
Brian Osman79086b92017-02-10 13:36:16 -05001035void Viewer::drawImGui(SkCanvas* canvas) {
1036 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1037 if (fShowImGuiTestWindow) {
1038 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1039 }
1040
1041 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001042 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1043 // always visible, we can end up in a layout feedback loop.
1044 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001045 DisplayParams params = fWindow->getRequestedDisplayParams();
1046 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001047 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1048 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001049 if (ImGui::CollapsingHeader("Backend")) {
1050 int newBackend = static_cast<int>(fBackendType);
1051 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1052 ImGui::SameLine();
1053 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001054#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1055 ImGui::SameLine();
1056 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1057#endif
Brian Osman621491e2017-02-28 15:45:01 -05001058#if defined(SK_VULKAN)
1059 ImGui::SameLine();
1060 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1061#endif
1062 if (newBackend != fBackendType) {
1063 fDeferredActions.push_back([=]() {
1064 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1065 });
1066 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001067
Brian Salomon99a33902017-03-07 15:16:34 -05001068 const GrContext* ctx = fWindow->getGrContext();
1069 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1070 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1071 paramsChanged = true;
1072 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001073 bool* wire = &params.fGrContextOptions.fWireframeMode;
1074 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1075 paramsChanged = true;
1076 }
Brian Salomon99a33902017-03-07 15:16:34 -05001077
Brian Osman28b12522017-03-08 17:10:24 -05001078 if (ctx) {
1079 int sampleCount = fWindow->sampleCount();
1080 ImGui::Text("MSAA: "); ImGui::SameLine();
1081 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1082 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1083 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1084 ImGui::RadioButton("16", &sampleCount, 16);
1085
1086 if (sampleCount != params.fMSAASampleCount) {
1087 params.fMSAASampleCount = sampleCount;
1088 paramsChanged = true;
1089 }
1090 }
1091
Brian Osman8a9de3d2017-03-01 14:59:05 -05001092 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001093 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001094 auto prButton = [&](GpuPathRenderers x) {
1095 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001096 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1097 params.fGrContextOptions.fGpuPathRenderers = x;
1098 paramsChanged = true;
1099 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001100 }
1101 };
1102
1103 if (!ctx) {
1104 ImGui::RadioButton("Software", true);
1105 } else if (fWindow->sampleCount()) {
1106 prButton(GpuPathRenderers::kAll);
1107 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1108 prButton(GpuPathRenderers::kStencilAndCover);
1109 }
1110 if (ctx->caps()->sampleShadingSupport()) {
1111 prButton(GpuPathRenderers::kMSAA);
1112 }
1113 prButton(GpuPathRenderers::kTessellating);
1114 prButton(GpuPathRenderers::kDefault);
1115 prButton(GpuPathRenderers::kNone);
1116 } else {
1117 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001118 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1119 prButton(GpuPathRenderers::kCoverageCounting);
1120 }
Jim Van Verth83010462017-03-16 08:45:39 -04001121 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001122 prButton(GpuPathRenderers::kTessellating);
1123 prButton(GpuPathRenderers::kNone);
1124 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001125 ImGui::TreePop();
1126 }
Brian Osman621491e2017-02-28 15:45:01 -05001127 }
1128
Brian Osman79086b92017-02-10 13:36:16 -05001129 if (ImGui::CollapsingHeader("Slide")) {
1130 static ImGuiTextFilter filter;
1131 filter.Draw();
1132 int previousSlide = fCurrentSlide;
1133 fCurrentSlide = 0;
1134 for (auto slide : fSlides) {
1135 if (filter.PassFilter(slide->getName().c_str())) {
1136 ImGui::BulletText("%s", slide->getName().c_str());
1137 if (ImGui::IsItemClicked()) {
1138 setupCurrentSlide(previousSlide);
1139 break;
1140 }
1141 }
1142 ++fCurrentSlide;
1143 }
1144 if (fCurrentSlide >= fSlides.count()) {
1145 fCurrentSlide = previousSlide;
1146 }
1147 }
Brian Osmana109e392017-02-24 09:49:14 -05001148
1149 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001150 ColorMode newMode = fColorMode;
1151 auto cmButton = [&](ColorMode mode, const char* label) {
1152 if (ImGui::RadioButton(label, mode == fColorMode)) {
1153 newMode = mode;
1154 }
1155 };
1156
1157 cmButton(ColorMode::kLegacy, "Legacy 8888");
1158 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1159 "Color Managed 8888 (Nonlinear blending)");
1160 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1161 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1162
1163 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001164 // It isn't safe to switch color mode now (in the middle of painting). We might
1165 // tear down the back-end, etc... Defer this change until the next onIdle.
1166 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001167 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001168 });
Brian Osmana109e392017-02-24 09:49:14 -05001169 }
1170
1171 // Pick from common gamuts:
1172 int primariesIdx = 4; // Default: Custom
1173 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1174 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1175 primariesIdx = i;
1176 break;
1177 }
1178 }
1179
1180 if (ImGui::Combo("Primaries", &primariesIdx,
1181 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1182 if (primariesIdx >= 0 && primariesIdx <= 3) {
1183 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1184 }
1185 }
1186
1187 // Allow direct editing of gamut
1188 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1189 }
Brian Osman79086b92017-02-10 13:36:16 -05001190 }
Brian Salomon99a33902017-03-07 15:16:34 -05001191 if (paramsChanged) {
1192 fDeferredActions.push_back([=]() {
1193 fWindow->setRequestedDisplayParams(params);
1194 fWindow->inval();
1195 this->updateTitle();
1196 });
1197 }
Brian Osman79086b92017-02-10 13:36:16 -05001198 ImGui::End();
1199 }
1200
Brian Osmanf6877092017-02-13 09:39:57 -05001201 SkPaint zoomImagePaint;
1202 if (fShowZoomWindow && fLastImage) {
1203 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1204 static int zoomFactor = 4;
1205 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1206
Mike Reed0acd7952017-04-28 11:12:19 -04001207 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001208 zoomImagePaint.setColor(SK_ColorWHITE);
1209
1210 // Zoom by shrinking the corner UVs towards the mouse cursor
1211 ImVec2 mousePos = ImGui::GetMousePos();
1212 ImVec2 avail = ImGui::GetContentRegionAvail();
1213
1214 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1215 (avail.y * 0.5f) / zoomFactor);
1216 ImGui::Image(&zoomImagePaint, avail,
1217 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1218 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1219 }
1220
1221 ImGui::End();
1222 }
1223
Brian Osman79086b92017-02-10 13:36:16 -05001224 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1225 // (widgets, etc...) that have been issued
1226 ImGui::Render();
1227
1228 // Then we fetch the most recent data, and convert it so we can render with Skia
1229 const ImDrawData* drawData = ImGui::GetDrawData();
1230 SkTDArray<SkPoint> pos;
1231 SkTDArray<SkPoint> uv;
1232 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001233
1234 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1235 const ImDrawList* drawList = drawData->CmdLists[i];
1236
1237 // De-interleave all vertex data (sigh), convert to Skia types
1238 pos.rewind(); uv.rewind(); color.rewind();
1239 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1240 const ImDrawVert& vert = drawList->VtxBuffer[i];
1241 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1242 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1243 color.push(vert.col);
1244 }
1245 // ImGui colors are RGBA
1246 SkSwapRB(color.begin(), color.begin(), color.count());
1247
1248 int indexOffset = 0;
1249
1250 // Draw everything with canvas.drawVertices...
1251 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1252 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1253
1254 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1255 if (drawCmd->UserCallback) {
1256 drawCmd->UserCallback(drawList, drawCmd);
1257 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001258 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1259 SkASSERT(paint);
1260
Brian Osman79086b92017-02-10 13:36:16 -05001261 canvas->save();
1262 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1263 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001264 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1265 drawList->VtxBuffer.size(), pos.begin(),
1266 uv.begin(), color.begin(),
1267 drawCmd->ElemCount,
1268 drawList->IdxBuffer.begin() + indexOffset),
1269 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001270 indexOffset += drawCmd->ElemCount;
1271 canvas->restore();
1272 }
1273 }
1274 }
1275}
1276
liyuqian2edb0f42016-07-06 14:11:32 -07001277void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001278 for (int i = 0; i < fDeferredActions.count(); ++i) {
1279 fDeferredActions[i]();
1280 }
1281 fDeferredActions.reset();
1282
Brian Osman1df161a2017-02-09 12:10:20 -05001283 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001284 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001285 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1286 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1287
Brian Osman79086b92017-02-10 13:36:16 -05001288 ImGuiIO& io = ImGui::GetIO();
1289 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001290 fWindow->inval();
1291 }
jvanverth9f372462016-04-06 06:08:59 -07001292}
liyuqiane5a6cd92016-05-27 08:52:52 -07001293
1294void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001295 if (!fWindow) {
1296 return;
1297 }
1298 if (fWindow->sampleCount() < 0) {
1299 return; // Surface hasn't been created yet.
1300 }
1301
liyuqianb73c24b2016-06-03 08:47:23 -07001302 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001303 Json::Value slideState(Json::objectValue);
1304 slideState[kName] = kSlideStateName;
1305 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001306 if (fAllSlideNames.size() == 0) {
1307 for(auto slide : fSlides) {
1308 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1309 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001310 }
liyuqian1f508fd2016-06-07 06:57:40 -07001311 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001312
liyuqianb73c24b2016-06-03 08:47:23 -07001313 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001314 Json::Value backendState(Json::objectValue);
1315 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001316 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001317 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001318 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001319 backendState[kOptions].append(Json::Value(str));
1320 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001321
csmartdalton578f0642017-02-24 16:04:47 -07001322 // MSAA state
1323 Json::Value msaaState(Json::objectValue);
1324 msaaState[kName] = kMSAAStateName;
1325 msaaState[kValue] = fWindow->sampleCount();
1326 msaaState[kOptions] = Json::Value(Json::arrayValue);
1327 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1328 msaaState[kOptions].append(Json::Value(0));
1329 } else {
1330 for (int msaa : {0, 4, 8, 16}) {
1331 msaaState[kOptions].append(Json::Value(msaa));
1332 }
1333 }
1334
csmartdalton61cd31a2017-02-27 17:00:53 -07001335 // Path renderer state
1336 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1337 Json::Value prState(Json::objectValue);
1338 prState[kName] = kPathRendererStateName;
1339 prState[kValue] = gPathRendererNames[pr];
1340 prState[kOptions] = Json::Value(Json::arrayValue);
1341 const GrContext* ctx = fWindow->getGrContext();
1342 if (!ctx) {
1343 prState[kOptions].append("Software");
1344 } else if (fWindow->sampleCount()) {
1345 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1346 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1347 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1348 }
1349 if (ctx->caps()->sampleShadingSupport()) {
1350 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1351 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001352 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001353 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1354 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1355 } else {
1356 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001357 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1358 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1359 }
Jim Van Verth83010462017-03-16 08:45:39 -04001360 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001361 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001362 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1363 }
1364
Brian Salomon99a33902017-03-07 15:16:34 -05001365 // Instanced rendering state
1366 Json::Value instState(Json::objectValue);
1367 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001368 instState[kValue] = kOFF;
1369 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001370 if (ctx) {
1371 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1372 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001373 }
Brian Salomon99a33902017-03-07 15:16:34 -05001374 instState[kOptions].append(kOFF);
1375 instState[kOptions].append(kON);
1376 }
1377
liyuqianb73c24b2016-06-03 08:47:23 -07001378 // Softkey state
1379 Json::Value softkeyState(Json::objectValue);
1380 softkeyState[kName] = kSoftkeyStateName;
1381 softkeyState[kValue] = kSoftkeyHint;
1382 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1383 softkeyState[kOptions].append(kSoftkeyHint);
1384 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1385 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1386 }
1387
liyuqian1f508fd2016-06-07 06:57:40 -07001388 // FPS state
1389 Json::Value fpsState(Json::objectValue);
1390 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001391 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1392 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1393 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1394 fAnimateTimes[idx],
1395 fPaintTimes[idx],
1396 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001397 fpsState[kOptions] = Json::Value(Json::arrayValue);
1398
liyuqiane5a6cd92016-05-27 08:52:52 -07001399 Json::Value state(Json::arrayValue);
1400 state.append(slideState);
1401 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001402 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001403 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001404 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001405 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001406 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001407
1408 fWindow->setUIState(state);
1409}
1410
1411void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001412 // For those who will add more features to handle the state change in this function:
1413 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1414 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1415 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001416 if (stateName.equals(kSlideStateName)) {
1417 int previousSlide = fCurrentSlide;
1418 fCurrentSlide = 0;
1419 for(auto slide : fSlides) {
1420 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001421 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001422 break;
1423 }
1424 fCurrentSlide++;
1425 }
1426 if (fCurrentSlide >= fSlides.count()) {
1427 fCurrentSlide = previousSlide;
1428 SkDebugf("Slide not found: %s", stateValue.c_str());
1429 }
liyuqian6cb70252016-06-02 12:16:25 -07001430 } else if (stateName.equals(kBackendStateName)) {
1431 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1432 if (stateValue.equals(kBackendTypeStrings[i])) {
1433 if (fBackendType != i) {
1434 fBackendType = (sk_app::Window::BackendType)i;
1435 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001436 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001437 }
1438 break;
1439 }
1440 }
csmartdalton578f0642017-02-24 16:04:47 -07001441 } else if (stateName.equals(kMSAAStateName)) {
1442 DisplayParams params = fWindow->getRequestedDisplayParams();
1443 int sampleCount = atoi(stateValue.c_str());
1444 if (sampleCount != params.fMSAASampleCount) {
1445 params.fMSAASampleCount = sampleCount;
1446 fWindow->setRequestedDisplayParams(params);
1447 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001448 this->updateTitle();
1449 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001450 }
1451 } else if (stateName.equals(kPathRendererStateName)) {
1452 DisplayParams params = fWindow->getRequestedDisplayParams();
1453 for (const auto& pair : gPathRendererNames) {
1454 if (pair.second == stateValue.c_str()) {
1455 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1456 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1457 fWindow->setRequestedDisplayParams(params);
1458 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001459 this->updateTitle();
1460 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001461 }
1462 break;
1463 }
csmartdalton578f0642017-02-24 16:04:47 -07001464 }
Brian Salomon99a33902017-03-07 15:16:34 -05001465 } else if (stateName.equals(kInstancedRenderingStateName)) {
1466 DisplayParams params = fWindow->getRequestedDisplayParams();
1467 bool value = !strcmp(stateValue.c_str(), kON);
1468 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1469 params.fGrContextOptions.fEnableInstancedRendering = value;
1470 fWindow->setRequestedDisplayParams(params);
1471 fWindow->inval();
1472 this->updateTitle();
1473 this->updateUIState();
1474 }
liyuqianb73c24b2016-06-03 08:47:23 -07001475 } else if (stateName.equals(kSoftkeyStateName)) {
1476 if (!stateValue.equals(kSoftkeyHint)) {
1477 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001478 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001479 }
liyuqian2edb0f42016-07-06 14:11:32 -07001480 } else if (stateName.equals(kRefreshStateName)) {
1481 // This state is actually NOT in the UI state.
1482 // We use this to allow Android to quickly set bool fRefresh.
1483 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001484 } else {
1485 SkDebugf("Unknown stateName: %s", stateName.c_str());
1486 }
1487}
Brian Osman79086b92017-02-10 13:36:16 -05001488
1489bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1490 return fCommands.onKey(key, state, modifiers);
1491}
1492
1493bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001494 if (fSlides[fCurrentSlide]->onChar(c)) {
1495 fWindow->inval();
1496 return true;
1497 }
1498
Brian Osman79086b92017-02-10 13:36:16 -05001499 return fCommands.onChar(c, modifiers);
1500}