blob: 4e6684310fd62fc98c4447b87ebbd612ed76d950 [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 -070050using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
51static std::map<GpuPathRenderers, std::string> gPathRendererNames;
52
jvanverth9f372462016-04-06 06:08:59 -070053Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070054 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070055}
56
Christopher Dalton443ec1b2017-02-24 13:22:53 -070057static void on_backend_created_func(void* userData) {
58 Viewer* vv = reinterpret_cast<Viewer*>(userData);
59
60 return vv->onBackendCreated();
61}
62
jvanverth9f372462016-04-06 06:08:59 -070063static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070064 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070065
66 return vv->onPaint(canvas);
67}
68
jvanverth814e38d2016-06-06 08:48:47 -070069static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070070{
71 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
72
73 return viewer->onTouch(owner, state, x, y);
74}
75
liyuqiane5a6cd92016-05-27 08:52:52 -070076static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
77 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
78
79 return viewer->onUIStateChanged(stateName, stateValue);
80}
81
Brian Osman79086b92017-02-10 13:36:16 -050082static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
83 void* userData) {
84 ImGuiIO& io = ImGui::GetIO();
85 io.MousePos.x = static_cast<float>(x);
86 io.MousePos.y = static_cast<float>(y);
87 if (Window::kDown_InputState == state) {
88 io.MouseDown[0] = true;
89 } else if (Window::kUp_InputState == state) {
90 io.MouseDown[0] = false;
91 }
Jim Van Verthe7705782017-05-04 14:00:59 -040092 if (io.WantCaptureMouse) {
93 return true;
94 } else {
95 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
96 return viewer->onMouse(x, y, state, modifiers);
97 }
Brian Osman79086b92017-02-10 13:36:16 -050098}
99
100static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
101 ImGuiIO& io = ImGui::GetIO();
102 io.MouseWheel += delta;
103 return true;
104}
105
106static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
107 void* userData) {
108 ImGuiIO& io = ImGui::GetIO();
109 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
110
111 if (io.WantCaptureKeyboard) {
112 return true;
113 } else {
114 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
115 return viewer->onKey(key, state, modifiers);
116 }
117}
118
119static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
120 ImGuiIO& io = ImGui::GetIO();
121 if (io.WantTextInput) {
122 if (c > 0 && c < 0x10000) {
123 io.AddInputCharacter(c);
124 }
125 return true;
126 } else {
127 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
128 return viewer->onChar(c, modifiers);
129 }
130}
131
Brian Osman2dd96932016-10-18 15:33:53 -0400132static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400133
Brian Osman2dd96932016-10-18 15:33:53 -0400134static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700135 "[~][^]substring[$] [...] of bench name to run.\n"
136 "Multiple matches may be separated by spaces.\n"
137 "~ causes a matching bench to always be skipped\n"
138 "^ requires the start of the bench to match\n"
139 "$ requires the end of the bench to match\n"
140 "^ and $ requires an exact match\n"
141 "If a bench does not match any list entry,\n"
142 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700143
Jim Van Verth6f449692017-02-14 15:16:46 -0500144DEFINE_string(slide, "", "Start on this sample.");
145DEFINE_bool(list, false, "List samples?");
146
bsalomon6c471f72016-07-26 12:56:32 -0700147#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700148# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700149#else
150# define BACKENDS_STR "\"sw\" and \"gl\""
151#endif
152
liyuqian71491dc2016-06-09 12:02:34 -0700153#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400154static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
155static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700156#else
Brian Osman2dd96932016-10-18 15:33:53 -0400157static DEFINE_string(skps, "skps", "Directory to read skps from.");
158static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700159#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700160
Brian Osman2dd96932016-10-18 15:33:53 -0400161static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700162
csmartdalton578f0642017-02-24 16:04:47 -0700163DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700164DEFINE_pathrenderer_flag;
165
Brian Salomon41eac792017-03-08 14:03:56 -0500166DEFINE_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();
Brian Osmanf9810662017-08-30 10:02:10 -0400308 displayParams.fGrContextOptions.fExecutor = GpuExecutorForTools();
csmartdalton578f0642017-02-24 16:04:47 -0700309 fWindow->setRequestedDisplayParams(displayParams);
310
jvanverth9f372462016-04-06 06:08:59 -0700311 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700312 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700313 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700314 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700315 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700316 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500317 fWindow->registerMouseFunc(on_mouse_handler, this);
318 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
319 fWindow->registerKeyFunc(on_key_handler, this);
320 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700321
brianosman622c8d52016-05-10 06:50:49 -0700322 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500323 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
324 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
325 fWindow->inval();
326 });
327 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
328 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
329 fWindow->inval();
330 });
Brian Osmanf6877092017-02-13 09:39:57 -0500331 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
332 this->fShowZoomWindow = !this->fShowZoomWindow;
333 fWindow->inval();
334 });
brianosman622c8d52016-05-10 06:50:49 -0700335 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
336 this->fDisplayStats = !this->fDisplayStats;
337 fWindow->inval();
338 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500339 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500340 switch (fColorMode) {
341 case ColorMode::kLegacy:
342 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
343 break;
344 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
345 this->setColorMode(ColorMode::kColorManagedSRGB8888);
346 break;
347 case ColorMode::kColorManagedSRGB8888:
348 this->setColorMode(ColorMode::kColorManagedLinearF16);
349 break;
350 case ColorMode::kColorManagedLinearF16:
351 this->setColorMode(ColorMode::kLegacy);
352 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500353 }
brianosman622c8d52016-05-10 06:50:49 -0700354 });
355 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
356 int previousSlide = fCurrentSlide;
357 fCurrentSlide++;
358 if (fCurrentSlide >= fSlides.count()) {
359 fCurrentSlide = 0;
360 }
361 this->setupCurrentSlide(previousSlide);
362 });
363 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
364 int previousSlide = fCurrentSlide;
365 fCurrentSlide--;
366 if (fCurrentSlide < 0) {
367 fCurrentSlide = fSlides.count() - 1;
368 }
369 this->setupCurrentSlide(previousSlide);
370 });
371 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
372 this->changeZoomLevel(1.f / 32.f);
373 fWindow->inval();
374 });
375 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
376 this->changeZoomLevel(-1.f / 32.f);
377 fWindow->inval();
378 });
jvanverthaf236b52016-05-20 06:01:06 -0700379 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400380 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
381 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500382 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400383#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
384 if (newBackend == sk_app::Window::kVulkan_BackendType) {
385 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
386 sk_app::Window::kBackendTypeCount);
387 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
388 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500389 }
390#endif
Brian Osman621491e2017-02-28 15:45:01 -0500391 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700392 });
brianosman622c8d52016-05-10 06:50:49 -0700393
Yuqian Li399b3c22017-08-03 11:08:15 -0400394 fCommands.addCommand('A', "AAA", "Toggle analytic AA", [this]() {
395 if (!gSkUseAnalyticAA) {
396 gSkUseAnalyticAA = true;
397 } else if (!gSkForceAnalyticAA) {
398 gSkForceAnalyticAA = true;
399 } else {
400 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
401 }
402 this->updateTitle();
403 fWindow->inval();
404 });
405 fCommands.addCommand('D', "DAA", "Toggle delta AA", [this]() {
406 if (!gSkUseDeltaAA) {
407 gSkUseDeltaAA = true;
408 } else if (!gSkForceDeltaAA) {
409 gSkForceDeltaAA = true;
410 } else {
411 gSkUseDeltaAA = gSkForceDeltaAA = false;
412 }
413 this->updateTitle();
414 fWindow->inval();
415 });
416
jvanverth2bb3b6d2016-04-08 07:24:09 -0700417 // set up slides
418 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500419 this->setStartupSlide();
420 if (FLAGS_list) {
421 this->listNames();
422 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700423
djsollen12d62a72016-04-21 07:59:44 -0700424 fAnimTimer.run();
425
Brian Osman79086b92017-02-10 13:36:16 -0500426 // ImGui initialization:
427 ImGuiIO& io = ImGui::GetIO();
428 io.DisplaySize.x = static_cast<float>(fWindow->width());
429 io.DisplaySize.y = static_cast<float>(fWindow->height());
430
431 // Keymap...
432 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
433 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
434 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
435 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
436 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
437 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
438 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
439 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
440 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
441 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
442 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
443 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
444 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
445 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
446 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
447 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
448 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
449 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
450 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
451
452 int w, h;
453 unsigned char* pixels;
454 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
455 SkImageInfo info = SkImageInfo::MakeA8(w, h);
456 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500457 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
458 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400459 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500460 fImGuiFontPaint.setShader(fontShader);
461 fImGuiFontPaint.setColor(SK_ColorWHITE);
462 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
463 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500464
Brian Osmana109e392017-02-24 09:49:14 -0500465 auto gamutImage = GetResourceAsImage("gamut.png");
466 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400467 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500468 }
469 fImGuiGamutPaint.setColor(SK_ColorWHITE);
470 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
471
csmartdalton578f0642017-02-24 16:04:47 -0700472 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700473}
474
jvanverth34524262016-05-04 13:49:13 -0700475void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700476 fAllSlideNames = Json::Value(Json::arrayValue);
477
jvanverth2bb3b6d2016-04-08 07:24:09 -0700478 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
479 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400480 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700481
482 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
483 sk_sp<Slide> slide(new GMSlide(gm.release()));
484 fSlides.push_back(slide);
485 }
486
487 gms = gms->next();
488 }
489
490 // reverse array
491 for (int i = 0; i < fSlides.count()/2; ++i) {
492 sk_sp<Slide> temp = fSlides[i];
493 fSlides[i] = fSlides[fSlides.count() - i - 1];
494 fSlides[fSlides.count() - i - 1] = temp;
495 }
496
jvanverthc7027ab2016-06-16 09:52:35 -0700497 // samples
498 const SkViewRegister* reg = SkViewRegister::Head();
499 while (reg) {
500 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700501 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
502 fSlides.push_back(slide);
503 }
jvanverthc7027ab2016-06-16 09:52:35 -0700504 reg = reg->next();
505 }
506
jvanverth2bb3b6d2016-04-08 07:24:09 -0700507 // SKPs
508 for (int i = 0; i < FLAGS_skps.count(); i++) {
509 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700510 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
511 continue;
512 }
513
jvanverth2bb3b6d2016-04-08 07:24:09 -0700514 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700515 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700516 if (slide) {
517 fSlides.push_back(slide);
518 }
519 } else {
520 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700521 SkString skpName;
522 while (it.next(&skpName)) {
523 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
524 continue;
525 }
526
527 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
528 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700529 if (slide) {
530 fSlides.push_back(slide);
531 }
532 }
533 }
534 }
liyuqian6f163d22016-06-13 12:26:45 -0700535
536 // JPGs
537 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
538 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
539 SkString jpgName;
540 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700541 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
542 continue;
543 }
544
liyuqian6f163d22016-06-13 12:26:45 -0700545 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
546 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
547 if (slide) {
548 fSlides.push_back(slide);
549 }
550 }
551 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700552}
553
554
jvanverth34524262016-05-04 13:49:13 -0700555Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700556 fWindow->detach();
557 delete fWindow;
558}
559
brianosman05de2162016-05-06 13:28:57 -0700560void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700561 if (!fWindow) {
562 return;
563 }
564 if (fWindow->sampleCount() < 0) {
565 return; // Surface hasn't been created yet.
566 }
567
jvanverth34524262016-05-04 13:49:13 -0700568 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700569 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700570
Yuqian Li399b3c22017-08-03 11:08:15 -0400571 if (gSkUseDeltaAA) {
572 if (gSkForceDeltaAA) {
573 title.append(" <FDAA>");
574 } else {
575 title.append(" <DAA>");
576 }
577 } else if (gSkUseAnalyticAA) {
578 if (gSkForceAnalyticAA) {
579 title.append(" <FAAA>");
580 } else {
581 title.append(" <AAA>");
582 }
583 }
584
Brian Osman92004802017-03-06 11:47:26 -0500585 switch (fColorMode) {
586 case ColorMode::kLegacy:
587 title.append(" Legacy 8888");
588 break;
589 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
590 title.append(" ColorManaged 8888 (Nonlinear blending)");
591 break;
592 case ColorMode::kColorManagedSRGB8888:
593 title.append(" ColorManaged 8888");
594 break;
595 case ColorMode::kColorManagedLinearF16:
596 title.append(" ColorManaged F16");
597 break;
598 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500599
Brian Osman92004802017-03-06 11:47:26 -0500600 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500601 int curPrimaries = -1;
602 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
603 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
604 curPrimaries = i;
605 break;
606 }
607 }
608 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700609 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500610
csmartdalton578f0642017-02-24 16:04:47 -0700611 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700612 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700613 if (int msaa = fWindow->sampleCount()) {
614 title.appendf(" MSAA: %i", msaa);
615 }
616 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700617
618 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Brian Osman8b0f2652017-08-29 15:18:34 -0400619 if (GpuPathRenderers::kDefault != pr) {
csmartdalton61cd31a2017-02-27 17:00:53 -0700620 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
621 }
622
brianosman05de2162016-05-06 13:28:57 -0700623 fWindow->setTitle(title.c_str());
624}
625
Jim Van Verth6f449692017-02-14 15:16:46 -0500626void Viewer::setStartupSlide() {
627
628 if (!FLAGS_slide.isEmpty()) {
629 int count = fSlides.count();
630 for (int i = 0; i < count; i++) {
631 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
632 fCurrentSlide = i;
633 return;
634 }
635 }
636
637 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
638 this->listNames();
639 }
640
641 fCurrentSlide = 0;
642}
643
644void Viewer::listNames() {
645 int count = fSlides.count();
646 SkDebugf("All Slides:\n");
647 for (int i = 0; i < count; i++) {
648 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
649 }
650}
651
brianosman05de2162016-05-06 13:28:57 -0700652void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700653 if (fCurrentSlide == previousSlide) {
654 return; // no change; do nothing
655 }
liyuqian6f163d22016-06-13 12:26:45 -0700656 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700657 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700658
liyuqiane46e4f02016-05-20 07:32:19 -0700659 fGesture.reset();
660 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700661
Brian Osman42bb6ac2017-06-05 08:46:04 -0400662 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
663 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
664 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
665
666 // Start with a matrix that scales the slide to the available screen space
667 if (fWindow->scaleContentToFit()) {
668 if (windowRect.width() > 0 && windowRect.height() > 0) {
669 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700670 }
671 }
672
Brian Osman42bb6ac2017-06-05 08:46:04 -0400673 // Prevent the user from dragging content so far outside the window they can't find it again
674 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700675
brianosman05de2162016-05-06 13:28:57 -0700676 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700677 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700678 if (previousSlide >= 0) {
679 fSlides[previousSlide]->unload();
680 }
jvanverthc265a922016-04-08 12:51:45 -0700681 fWindow->inval();
682}
683
684#define MAX_ZOOM_LEVEL 8
685#define MIN_ZOOM_LEVEL -8
686
jvanverth34524262016-05-04 13:49:13 -0700687void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700688 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400689 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700690}
691
liyuqiand3cdbca2016-05-17 12:44:20 -0700692SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700693 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700694
Brian Osman42bb6ac2017-06-05 08:46:04 -0400695 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
696 : SK_Scalar1 + fZoomLevel;
697 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700698 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400699 m.preConcat(fDefaultMatrix);
700 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700701
liyuqiand3cdbca2016-05-17 12:44:20 -0700702 return m;
jvanverthc265a922016-04-08 12:51:45 -0700703}
704
Brian Osman621491e2017-02-28 15:45:01 -0500705void Viewer::setBackend(sk_app::Window::BackendType backendType) {
706 fBackendType = backendType;
707
708 fWindow->detach();
709
710#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Salomon194db172017-08-17 14:37:06 -0400711 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
712 // on Windows, so we just delete the window and recreate it.
Brian Osman80a82df2017-07-12 15:42:51 -0400713 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
Brian Salomon194db172017-08-17 14:37:06 -0400714 sk_app::Window::kNativeGL_BackendType == fBackendType
715#if SK_ANGLE
716 || sk_app::Window::kANGLE_BackendType == fBackendType
717#endif
718 ) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400719 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500720 delete fWindow;
721 fWindow = Window::CreateNativeWindow(nullptr);
722
723 // re-register callbacks
724 fCommands.attach(fWindow);
725 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
726 fWindow->registerPaintFunc(on_paint_handler, this);
727 fWindow->registerTouchFunc(on_touch_handler, this);
728 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
729 fWindow->registerMouseFunc(on_mouse_handler, this);
730 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
731 fWindow->registerKeyFunc(on_key_handler, this);
732 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400733 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
734 // will still include our correct sample count. But the re-created fWindow will lose that
735 // information. On Windows, we need to re-create the window when changing sample count,
736 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
737 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
738 // as if we had never changed windows at all).
739 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500740 }
741#endif
742
743 fWindow->attach(fBackendType);
744}
745
Brian Osman92004802017-03-06 11:47:26 -0500746void Viewer::setColorMode(ColorMode colorMode) {
747 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700748
Brian Osmanf750fbc2017-02-08 10:47:28 -0500749 // 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 -0400750 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700751 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500752 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400753 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
754 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500755 if (wasInLegacy != wantLegacy) {
756 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700757 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500758 }
759
760 this->updateTitle();
761 fWindow->inval();
762}
763
764void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500765 SkAutoCanvasRestore autorestore(canvas, false);
766
Brian Osmanf750fbc2017-02-08 10:47:28 -0500767 // By default, we render directly into the window's surface/canvas
768 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500769 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700770
Brian Osmane0d4fba2017-03-15 10:24:55 -0400771 // If we're in any of the color managed modes, construct the color space we're going to use
772 sk_sp<SkColorSpace> cs = nullptr;
773 if (ColorMode::kLegacy != fColorMode) {
774 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
775 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400776 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400777 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
778 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
779 }
780
781 // 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 -0500782 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500783 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500784 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500785 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400786 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
787 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
788
Brian Osman92004802017-03-06 11:47:26 -0500789 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
790 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400791 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
792 // with a special canvas (below) that has the color space attached
793 sk_sp<SkColorSpace> offscreenColorSpace =
794 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500795 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400796 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500797 offscreenSurface = canvas->makeSurface(info);
798 slideCanvas = offscreenSurface->getCanvas();
799 }
800
Brian Osmane0d4fba2017-03-15 10:24:55 -0400801 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
802 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
803 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
804 slideCanvas = xformCanvas.get();
805 }
806
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500807 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500808 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500809 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500810 // Time the painting logic of the slide
811 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500812 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500813 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500814 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500815
816 // Force a flush so we can time that, too
817 startTime = SkTime::GetMSecs();
818 slideCanvas->flush();
819 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500820
821 // If we rendered offscreen, snap an image and push the results to the window's canvas
822 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500823 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500824
825 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400826 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500827 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400828 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500829 SkPaint paint;
830 paint.setBlendMode(SkBlendMode::kSrc);
831 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700832 }
liyuqian6f163d22016-06-13 12:26:45 -0700833}
834
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700835void Viewer::onBackendCreated() {
836 this->updateTitle();
837 this->updateUIState();
838 this->setupCurrentSlide(-1);
839 fWindow->show();
840 fWindow->inval();
841}
Jim Van Verth6f449692017-02-14 15:16:46 -0500842
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700843void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500844 // Update ImGui input
845 ImGuiIO& io = ImGui::GetIO();
846 io.DeltaTime = 1.0f / 60.0f;
847 io.DisplaySize.x = static_cast<float>(fWindow->width());
848 io.DisplaySize.y = static_cast<float>(fWindow->height());
849
850 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
851 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
852 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
853
854 ImGui::NewFrame();
855
Brian Osmanf750fbc2017-02-08 10:47:28 -0500856 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700857
Brian Osman1df161a2017-02-09 12:10:20 -0500858 // Advance our timing bookkeeping
859 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
860 SkASSERT(fCurrentMeasurement < kMeasurementCount);
861
862 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700863 if (fDisplayStats) {
864 drawStats(canvas);
865 }
brianosman622c8d52016-05-10 06:50:49 -0700866 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700867
Brian Osman79086b92017-02-10 13:36:16 -0500868 drawImGui(canvas);
869
Brian Osman1df161a2017-02-09 12:10:20 -0500870 // Update the FPS
871 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700872}
873
jvanverth814e38d2016-06-06 08:48:47 -0700874bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400875 if (GestureDevice::kMouse == fGestureDevice) {
876 return false;
877 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700878 void* castedOwner = reinterpret_cast<void*>(owner);
879 switch (state) {
880 case Window::kUp_InputState: {
881 fGesture.touchEnd(castedOwner);
882 break;
883 }
884 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400885 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700886 break;
887 }
888 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400889 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700890 break;
891 }
892 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400893 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700894 fWindow->inval();
895 return true;
896}
897
Jim Van Verthe7705782017-05-04 14:00:59 -0400898bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400899 if (GestureDevice::kTouch == fGestureDevice) {
900 return false;
901 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400902 switch (state) {
903 case Window::kUp_InputState: {
904 fGesture.touchEnd(nullptr);
905 break;
906 }
907 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400908 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400909 break;
910 }
911 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400912 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400913 break;
914 }
915 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400916 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400917 fWindow->inval();
918 return true;
919}
920
jvanverth34524262016-05-04 13:49:13 -0700921void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700922 static const float kPixelPerMS = 2.0f;
923 static const int kDisplayWidth = 130;
924 static const int kDisplayHeight = 100;
925 static const int kDisplayPadding = 10;
926 static const int kGraphPadding = 3;
927 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
928
Mike Reed3661bc92017-02-22 13:21:42 -0500929 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700930 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
931 SkIntToScalar(kDisplayPadding),
932 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
933 SkPaint paint;
934 canvas->save();
935
936 canvas->clipRect(rect);
937 paint.setColor(SK_ColorBLACK);
938 canvas->drawRect(rect, paint);
939 // draw the 16ms line
940 paint.setColor(SK_ColorLTGRAY);
941 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
942 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
943 paint.setColor(SK_ColorRED);
944 paint.setStyle(SkPaint::kStroke_Style);
945 canvas->drawRect(rect, paint);
946
947 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
948 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700949 int i = fCurrentMeasurement;
950 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500951 // Round to nearest values
952 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
953 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
954 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
955 int startY = SkScalarTruncToInt(rect.fBottom);
956 int endY = startY - flushHeight;
957 paint.setColor(SK_ColorRED);
958 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
959 SkIntToScalar(x), SkIntToScalar(endY), paint);
960 startY = endY;
961 endY = startY - paintHeight;
962 paint.setColor(SK_ColorGREEN);
963 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
964 SkIntToScalar(x), SkIntToScalar(endY), paint);
965 startY = endY;
966 endY = startY - animateHeight;
967 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700968 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
969 SkIntToScalar(x), SkIntToScalar(endY), paint);
970 i++;
971 i &= (kMeasurementCount - 1); // fast mod
972 x += xStep;
973 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700974
975 canvas->restore();
976}
977
Brian Osmana109e392017-02-24 09:49:14 -0500978static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
979 const ImVec2& pos, const ImVec2& size) {
980 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
981 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
982
983 // Invisible 10x10 button
984 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
985 ImGui::InvisibleButton(label, ImVec2(10, 10));
986
987 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
988 ImGuiIO& io = ImGui::GetIO();
989 // Normalized mouse position, relative to our gamut box
990 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
991 // Clamp to edge of box, convert back to primary scale
992 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
993 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
994 }
995
996 if (ImGui::IsItemHovered()) {
997 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
998 }
999
1000 // Return screen coordinates for the caller. We could just return center here, but we'd have
1001 // one frame of lag during drag.
1002 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1003}
1004
1005static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1006 ImDrawList* drawList = ImGui::GetWindowDrawList();
1007
1008 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1009 // width, and scale the height to maintain aspect ratio.
1010 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1011 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1012 ImVec2 pos = ImGui::GetCursorScreenPos();
1013
1014 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1015 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1016 // Magic numbers are pixel locations of the origin and upper-right corner.
1017 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1018 ImVec2(242, 61), ImVec2(1897, 1922));
1019 ImVec2 endPos = ImGui::GetCursorPos();
1020
1021 // Primary markers
1022 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1023 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1024 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1025 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1026
1027 // Gamut triangle
1028 drawList->AddCircle(r, 5.0f, 0xFF000040);
1029 drawList->AddCircle(g, 5.0f, 0xFF004000);
1030 drawList->AddCircle(b, 5.0f, 0xFF400000);
1031 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1032 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1033
1034 // Re-position cursor immediate after the diagram for subsequent controls
1035 ImGui::SetCursorPos(endPos);
1036}
1037
Brian Osman79086b92017-02-10 13:36:16 -05001038void Viewer::drawImGui(SkCanvas* canvas) {
1039 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1040 if (fShowImGuiTestWindow) {
1041 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1042 }
1043
1044 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001045 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1046 // always visible, we can end up in a layout feedback loop.
1047 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001048 DisplayParams params = fWindow->getRequestedDisplayParams();
1049 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001050 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1051 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001052 if (ImGui::CollapsingHeader("Backend")) {
1053 int newBackend = static_cast<int>(fBackendType);
1054 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1055 ImGui::SameLine();
1056 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001057#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1058 ImGui::SameLine();
1059 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1060#endif
Brian Osman621491e2017-02-28 15:45:01 -05001061#if defined(SK_VULKAN)
1062 ImGui::SameLine();
1063 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1064#endif
1065 if (newBackend != fBackendType) {
1066 fDeferredActions.push_back([=]() {
1067 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1068 });
1069 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001070
Brian Salomon99a33902017-03-07 15:16:34 -05001071 const GrContext* ctx = fWindow->getGrContext();
1072 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1073 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1074 paramsChanged = true;
1075 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001076 bool* wire = &params.fGrContextOptions.fWireframeMode;
1077 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1078 paramsChanged = true;
1079 }
Brian Salomon99a33902017-03-07 15:16:34 -05001080
Brian Osman28b12522017-03-08 17:10:24 -05001081 if (ctx) {
1082 int sampleCount = fWindow->sampleCount();
1083 ImGui::Text("MSAA: "); ImGui::SameLine();
1084 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1085 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1086 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1087 ImGui::RadioButton("16", &sampleCount, 16);
1088
1089 if (sampleCount != params.fMSAASampleCount) {
1090 params.fMSAASampleCount = sampleCount;
1091 paramsChanged = true;
1092 }
1093 }
1094
Brian Osman8a9de3d2017-03-01 14:59:05 -05001095 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001096 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001097 auto prButton = [&](GpuPathRenderers x) {
1098 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001099 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1100 params.fGrContextOptions.fGpuPathRenderers = x;
1101 paramsChanged = true;
1102 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001103 }
1104 };
1105
1106 if (!ctx) {
1107 ImGui::RadioButton("Software", true);
1108 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001109 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001110 prButton(GpuPathRenderers::kAll);
1111 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1112 prButton(GpuPathRenderers::kStencilAndCover);
1113 }
1114 if (ctx->caps()->sampleShadingSupport()) {
1115 prButton(GpuPathRenderers::kMSAA);
1116 }
1117 prButton(GpuPathRenderers::kTessellating);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001118 prButton(GpuPathRenderers::kNone);
1119 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001120 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001121 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001122 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1123 prButton(GpuPathRenderers::kCoverageCounting);
1124 }
Jim Van Verth83010462017-03-16 08:45:39 -04001125 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001126 prButton(GpuPathRenderers::kTessellating);
1127 prButton(GpuPathRenderers::kNone);
1128 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001129 ImGui::TreePop();
1130 }
Brian Osman621491e2017-02-28 15:45:01 -05001131 }
1132
Brian Osman79086b92017-02-10 13:36:16 -05001133 if (ImGui::CollapsingHeader("Slide")) {
1134 static ImGuiTextFilter filter;
1135 filter.Draw();
1136 int previousSlide = fCurrentSlide;
1137 fCurrentSlide = 0;
1138 for (auto slide : fSlides) {
1139 if (filter.PassFilter(slide->getName().c_str())) {
1140 ImGui::BulletText("%s", slide->getName().c_str());
1141 if (ImGui::IsItemClicked()) {
1142 setupCurrentSlide(previousSlide);
1143 break;
1144 }
1145 }
1146 ++fCurrentSlide;
1147 }
1148 if (fCurrentSlide >= fSlides.count()) {
1149 fCurrentSlide = previousSlide;
1150 }
1151 }
Brian Osmana109e392017-02-24 09:49:14 -05001152
1153 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001154 ColorMode newMode = fColorMode;
1155 auto cmButton = [&](ColorMode mode, const char* label) {
1156 if (ImGui::RadioButton(label, mode == fColorMode)) {
1157 newMode = mode;
1158 }
1159 };
1160
1161 cmButton(ColorMode::kLegacy, "Legacy 8888");
1162 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1163 "Color Managed 8888 (Nonlinear blending)");
1164 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1165 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1166
1167 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001168 // It isn't safe to switch color mode now (in the middle of painting). We might
1169 // tear down the back-end, etc... Defer this change until the next onIdle.
1170 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001171 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001172 });
Brian Osmana109e392017-02-24 09:49:14 -05001173 }
1174
1175 // Pick from common gamuts:
1176 int primariesIdx = 4; // Default: Custom
1177 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1178 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1179 primariesIdx = i;
1180 break;
1181 }
1182 }
1183
1184 if (ImGui::Combo("Primaries", &primariesIdx,
1185 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1186 if (primariesIdx >= 0 && primariesIdx <= 3) {
1187 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1188 }
1189 }
1190
1191 // Allow direct editing of gamut
1192 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1193 }
Brian Osman79086b92017-02-10 13:36:16 -05001194 }
Brian Salomon99a33902017-03-07 15:16:34 -05001195 if (paramsChanged) {
1196 fDeferredActions.push_back([=]() {
1197 fWindow->setRequestedDisplayParams(params);
1198 fWindow->inval();
1199 this->updateTitle();
1200 });
1201 }
Brian Osman79086b92017-02-10 13:36:16 -05001202 ImGui::End();
1203 }
1204
Brian Osmanf6877092017-02-13 09:39:57 -05001205 SkPaint zoomImagePaint;
1206 if (fShowZoomWindow && fLastImage) {
1207 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1208 static int zoomFactor = 4;
1209 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1210
Mike Reed0acd7952017-04-28 11:12:19 -04001211 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001212 zoomImagePaint.setColor(SK_ColorWHITE);
1213
1214 // Zoom by shrinking the corner UVs towards the mouse cursor
1215 ImVec2 mousePos = ImGui::GetMousePos();
1216 ImVec2 avail = ImGui::GetContentRegionAvail();
1217
1218 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1219 (avail.y * 0.5f) / zoomFactor);
1220 ImGui::Image(&zoomImagePaint, avail,
1221 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1222 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1223 }
1224
1225 ImGui::End();
1226 }
1227
Brian Osman79086b92017-02-10 13:36:16 -05001228 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1229 // (widgets, etc...) that have been issued
1230 ImGui::Render();
1231
1232 // Then we fetch the most recent data, and convert it so we can render with Skia
1233 const ImDrawData* drawData = ImGui::GetDrawData();
1234 SkTDArray<SkPoint> pos;
1235 SkTDArray<SkPoint> uv;
1236 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001237
1238 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1239 const ImDrawList* drawList = drawData->CmdLists[i];
1240
1241 // De-interleave all vertex data (sigh), convert to Skia types
1242 pos.rewind(); uv.rewind(); color.rewind();
1243 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1244 const ImDrawVert& vert = drawList->VtxBuffer[i];
1245 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1246 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1247 color.push(vert.col);
1248 }
1249 // ImGui colors are RGBA
1250 SkSwapRB(color.begin(), color.begin(), color.count());
1251
1252 int indexOffset = 0;
1253
1254 // Draw everything with canvas.drawVertices...
1255 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1256 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1257
1258 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1259 if (drawCmd->UserCallback) {
1260 drawCmd->UserCallback(drawList, drawCmd);
1261 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001262 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1263 SkASSERT(paint);
1264
Brian Osman79086b92017-02-10 13:36:16 -05001265 canvas->save();
1266 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1267 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001268 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1269 drawList->VtxBuffer.size(), pos.begin(),
1270 uv.begin(), color.begin(),
1271 drawCmd->ElemCount,
1272 drawList->IdxBuffer.begin() + indexOffset),
1273 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001274 indexOffset += drawCmd->ElemCount;
1275 canvas->restore();
1276 }
1277 }
1278 }
1279}
1280
liyuqian2edb0f42016-07-06 14:11:32 -07001281void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001282 for (int i = 0; i < fDeferredActions.count(); ++i) {
1283 fDeferredActions[i]();
1284 }
1285 fDeferredActions.reset();
1286
Brian Osman1df161a2017-02-09 12:10:20 -05001287 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001288 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001289 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1290 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1291
Brian Osman79086b92017-02-10 13:36:16 -05001292 ImGuiIO& io = ImGui::GetIO();
1293 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001294 fWindow->inval();
1295 }
jvanverth9f372462016-04-06 06:08:59 -07001296}
liyuqiane5a6cd92016-05-27 08:52:52 -07001297
1298void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001299 if (!fWindow) {
1300 return;
1301 }
1302 if (fWindow->sampleCount() < 0) {
1303 return; // Surface hasn't been created yet.
1304 }
1305
liyuqianb73c24b2016-06-03 08:47:23 -07001306 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001307 Json::Value slideState(Json::objectValue);
1308 slideState[kName] = kSlideStateName;
1309 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001310 if (fAllSlideNames.size() == 0) {
1311 for(auto slide : fSlides) {
1312 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1313 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001314 }
liyuqian1f508fd2016-06-07 06:57:40 -07001315 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001316
liyuqianb73c24b2016-06-03 08:47:23 -07001317 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001318 Json::Value backendState(Json::objectValue);
1319 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001320 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001321 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001322 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001323 backendState[kOptions].append(Json::Value(str));
1324 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001325
csmartdalton578f0642017-02-24 16:04:47 -07001326 // MSAA state
1327 Json::Value msaaState(Json::objectValue);
1328 msaaState[kName] = kMSAAStateName;
1329 msaaState[kValue] = fWindow->sampleCount();
1330 msaaState[kOptions] = Json::Value(Json::arrayValue);
1331 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1332 msaaState[kOptions].append(Json::Value(0));
1333 } else {
1334 for (int msaa : {0, 4, 8, 16}) {
1335 msaaState[kOptions].append(Json::Value(msaa));
1336 }
1337 }
1338
csmartdalton61cd31a2017-02-27 17:00:53 -07001339 // Path renderer state
1340 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1341 Json::Value prState(Json::objectValue);
1342 prState[kName] = kPathRendererStateName;
1343 prState[kValue] = gPathRendererNames[pr];
1344 prState[kOptions] = Json::Value(Json::arrayValue);
1345 const GrContext* ctx = fWindow->getGrContext();
1346 if (!ctx) {
1347 prState[kOptions].append("Software");
1348 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001349 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001350 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1351 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1352 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1353 }
1354 if (ctx->caps()->sampleShadingSupport()) {
1355 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1356 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001357 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001358 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1359 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001360 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001361 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001362 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1363 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1364 }
Jim Van Verth83010462017-03-16 08:45:39 -04001365 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001366 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001367 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1368 }
1369
Brian Salomon99a33902017-03-07 15:16:34 -05001370 // Instanced rendering state
1371 Json::Value instState(Json::objectValue);
1372 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001373 instState[kValue] = kOFF;
1374 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001375 if (ctx) {
1376 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1377 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001378 }
Brian Salomon99a33902017-03-07 15:16:34 -05001379 instState[kOptions].append(kOFF);
1380 instState[kOptions].append(kON);
1381 }
1382
liyuqianb73c24b2016-06-03 08:47:23 -07001383 // Softkey state
1384 Json::Value softkeyState(Json::objectValue);
1385 softkeyState[kName] = kSoftkeyStateName;
1386 softkeyState[kValue] = kSoftkeyHint;
1387 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1388 softkeyState[kOptions].append(kSoftkeyHint);
1389 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1390 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1391 }
1392
liyuqian1f508fd2016-06-07 06:57:40 -07001393 // FPS state
1394 Json::Value fpsState(Json::objectValue);
1395 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001396 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1397 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1398 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1399 fAnimateTimes[idx],
1400 fPaintTimes[idx],
1401 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001402 fpsState[kOptions] = Json::Value(Json::arrayValue);
1403
liyuqiane5a6cd92016-05-27 08:52:52 -07001404 Json::Value state(Json::arrayValue);
1405 state.append(slideState);
1406 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001407 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001408 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001409 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001410 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001411 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001412
1413 fWindow->setUIState(state);
1414}
1415
1416void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001417 // For those who will add more features to handle the state change in this function:
1418 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1419 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1420 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001421 if (stateName.equals(kSlideStateName)) {
1422 int previousSlide = fCurrentSlide;
1423 fCurrentSlide = 0;
1424 for(auto slide : fSlides) {
1425 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001426 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001427 break;
1428 }
1429 fCurrentSlide++;
1430 }
1431 if (fCurrentSlide >= fSlides.count()) {
1432 fCurrentSlide = previousSlide;
1433 SkDebugf("Slide not found: %s", stateValue.c_str());
1434 }
liyuqian6cb70252016-06-02 12:16:25 -07001435 } else if (stateName.equals(kBackendStateName)) {
1436 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1437 if (stateValue.equals(kBackendTypeStrings[i])) {
1438 if (fBackendType != i) {
1439 fBackendType = (sk_app::Window::BackendType)i;
1440 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001441 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001442 }
1443 break;
1444 }
1445 }
csmartdalton578f0642017-02-24 16:04:47 -07001446 } else if (stateName.equals(kMSAAStateName)) {
1447 DisplayParams params = fWindow->getRequestedDisplayParams();
1448 int sampleCount = atoi(stateValue.c_str());
1449 if (sampleCount != params.fMSAASampleCount) {
1450 params.fMSAASampleCount = sampleCount;
1451 fWindow->setRequestedDisplayParams(params);
1452 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001453 this->updateTitle();
1454 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001455 }
1456 } else if (stateName.equals(kPathRendererStateName)) {
1457 DisplayParams params = fWindow->getRequestedDisplayParams();
1458 for (const auto& pair : gPathRendererNames) {
1459 if (pair.second == stateValue.c_str()) {
1460 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1461 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1462 fWindow->setRequestedDisplayParams(params);
1463 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001464 this->updateTitle();
1465 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001466 }
1467 break;
1468 }
csmartdalton578f0642017-02-24 16:04:47 -07001469 }
Brian Salomon99a33902017-03-07 15:16:34 -05001470 } else if (stateName.equals(kInstancedRenderingStateName)) {
1471 DisplayParams params = fWindow->getRequestedDisplayParams();
1472 bool value = !strcmp(stateValue.c_str(), kON);
1473 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1474 params.fGrContextOptions.fEnableInstancedRendering = value;
1475 fWindow->setRequestedDisplayParams(params);
1476 fWindow->inval();
1477 this->updateTitle();
1478 this->updateUIState();
1479 }
liyuqianb73c24b2016-06-03 08:47:23 -07001480 } else if (stateName.equals(kSoftkeyStateName)) {
1481 if (!stateValue.equals(kSoftkeyHint)) {
1482 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001483 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001484 }
liyuqian2edb0f42016-07-06 14:11:32 -07001485 } else if (stateName.equals(kRefreshStateName)) {
1486 // This state is actually NOT in the UI state.
1487 // We use this to allow Android to quickly set bool fRefresh.
1488 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001489 } else {
1490 SkDebugf("Unknown stateName: %s", stateName.c_str());
1491 }
1492}
Brian Osman79086b92017-02-10 13:36:16 -05001493
1494bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1495 return fCommands.onKey(key, state, modifiers);
1496}
1497
1498bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001499 if (fSlides[fCurrentSlide]->onChar(c)) {
1500 fWindow->inval();
1501 return true;
1502 }
1503
Brian Osman79086b92017-02-10 13:36:16 -05001504 return fCommands.onChar(c, modifiers);
1505}