blob: 3503e6481f359b1fe6c0c8d243f4c04aec2e5d23 [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"
Greg Daniel285db442016-10-14 09:12:53 -040024#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050025#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070026#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070027#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070028#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050029#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070030#include "SkRandom.h"
31#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070032#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050033#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050034#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070035#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040036#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070037
Brian Osman79086b92017-02-10 13:36:16 -050038#include "imgui.h"
39
csmartdalton578f0642017-02-24 16:04:47 -070040#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070041#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070042
jvanverth34524262016-05-04 13:49:13 -070043using namespace sk_app;
44
csmartdalton61cd31a2017-02-27 17:00:53 -070045using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
46static std::map<GpuPathRenderers, std::string> gPathRendererNames;
47
jvanverth9f372462016-04-06 06:08:59 -070048Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070049 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070050}
51
Christopher Dalton443ec1b2017-02-24 13:22:53 -070052static void on_backend_created_func(void* userData) {
53 Viewer* vv = reinterpret_cast<Viewer*>(userData);
54
55 return vv->onBackendCreated();
56}
57
jvanverth9f372462016-04-06 06:08:59 -070058static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070059 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070060
61 return vv->onPaint(canvas);
62}
63
jvanverth814e38d2016-06-06 08:48:47 -070064static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070065{
66 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
67
68 return viewer->onTouch(owner, state, x, y);
69}
70
liyuqiane5a6cd92016-05-27 08:52:52 -070071static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
72 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
73
74 return viewer->onUIStateChanged(stateName, stateValue);
75}
76
Brian Osman79086b92017-02-10 13:36:16 -050077static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
78 void* userData) {
79 ImGuiIO& io = ImGui::GetIO();
80 io.MousePos.x = static_cast<float>(x);
81 io.MousePos.y = static_cast<float>(y);
82 if (Window::kDown_InputState == state) {
83 io.MouseDown[0] = true;
84 } else if (Window::kUp_InputState == state) {
85 io.MouseDown[0] = false;
86 }
Jim Van Verthe7705782017-05-04 14:00:59 -040087 if (io.WantCaptureMouse) {
88 return true;
89 } else {
90 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
91 return viewer->onMouse(x, y, state, modifiers);
92 }
Brian Osman79086b92017-02-10 13:36:16 -050093}
94
95static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
96 ImGuiIO& io = ImGui::GetIO();
97 io.MouseWheel += delta;
98 return true;
99}
100
101static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
102 void* userData) {
103 ImGuiIO& io = ImGui::GetIO();
104 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
105
106 if (io.WantCaptureKeyboard) {
107 return true;
108 } else {
109 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
110 return viewer->onKey(key, state, modifiers);
111 }
112}
113
114static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
115 ImGuiIO& io = ImGui::GetIO();
116 if (io.WantTextInput) {
117 if (c > 0 && c < 0x10000) {
118 io.AddInputCharacter(c);
119 }
120 return true;
121 } else {
122 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
123 return viewer->onChar(c, modifiers);
124 }
125}
126
Brian Osman2dd96932016-10-18 15:33:53 -0400127static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400128
Brian Osman2dd96932016-10-18 15:33:53 -0400129static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700130 "[~][^]substring[$] [...] of bench name to run.\n"
131 "Multiple matches may be separated by spaces.\n"
132 "~ causes a matching bench to always be skipped\n"
133 "^ requires the start of the bench to match\n"
134 "$ requires the end of the bench to match\n"
135 "^ and $ requires an exact match\n"
136 "If a bench does not match any list entry,\n"
137 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700138
Jim Van Verth6f449692017-02-14 15:16:46 -0500139DEFINE_string(slide, "", "Start on this sample.");
140DEFINE_bool(list, false, "List samples?");
141
bsalomon6c471f72016-07-26 12:56:32 -0700142#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700143# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700144#else
145# define BACKENDS_STR "\"sw\" and \"gl\""
146#endif
147
liyuqian71491dc2016-06-09 12:02:34 -0700148#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400149static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
150static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700151#else
Brian Osman2dd96932016-10-18 15:33:53 -0400152static DEFINE_string(skps, "skps", "Directory to read skps from.");
153static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700154#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700155
Brian Osman2dd96932016-10-18 15:33:53 -0400156static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700157
Brian Osman2dd96932016-10-18 15:33:53 -0400158static DEFINE_bool(atrace, false, "Enable support for using ATrace. ATrace is only supported on Android.");
Greg Daniel285db442016-10-14 09:12:53 -0400159
csmartdalton578f0642017-02-24 16:04:47 -0700160DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700161DEFINE_pathrenderer_flag;
162
Brian Salomon41eac792017-03-08 14:03:56 -0500163DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
164
jvanverthaf236b52016-05-20 06:01:06 -0700165const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700166 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700167#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700168 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700169#endif
csmartdalton578f0642017-02-24 16:04:47 -0700170 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700171};
172
bsalomon6c471f72016-07-26 12:56:32 -0700173static sk_app::Window::BackendType get_backend_type(const char* str) {
174#ifdef SK_VULKAN
175 if (0 == strcmp(str, "vk")) {
176 return sk_app::Window::kVulkan_BackendType;
177 } else
178#endif
179 if (0 == strcmp(str, "gl")) {
180 return sk_app::Window::kNativeGL_BackendType;
181 } else if (0 == strcmp(str, "sw")) {
182 return sk_app::Window::kRaster_BackendType;
183 } else {
184 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
185 return sk_app::Window::kRaster_BackendType;
186 }
187}
188
Brian Osmana109e392017-02-24 09:49:14 -0500189static SkColorSpacePrimaries gSrgbPrimaries = {
190 0.64f, 0.33f,
191 0.30f, 0.60f,
192 0.15f, 0.06f,
193 0.3127f, 0.3290f };
194
195static SkColorSpacePrimaries gAdobePrimaries = {
196 0.64f, 0.33f,
197 0.21f, 0.71f,
198 0.15f, 0.06f,
199 0.3127f, 0.3290f };
200
201static SkColorSpacePrimaries gP3Primaries = {
202 0.680f, 0.320f,
203 0.265f, 0.690f,
204 0.150f, 0.060f,
205 0.3127f, 0.3290f };
206
207static SkColorSpacePrimaries gRec2020Primaries = {
208 0.708f, 0.292f,
209 0.170f, 0.797f,
210 0.131f, 0.046f,
211 0.3127f, 0.3290f };
212
213struct NamedPrimaries {
214 const char* fName;
215 SkColorSpacePrimaries* fPrimaries;
216} gNamedPrimaries[] = {
217 { "sRGB", &gSrgbPrimaries },
218 { "AdobeRGB", &gAdobePrimaries },
219 { "P3", &gP3Primaries },
220 { "Rec. 2020", &gRec2020Primaries },
221};
222
223static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
224 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
225}
226
liyuqiane5a6cd92016-05-27 08:52:52 -0700227const char* kName = "name";
228const char* kValue = "value";
229const char* kOptions = "options";
230const char* kSlideStateName = "Slide";
231const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700232const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700233const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500234const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700235const char* kSoftkeyStateName = "Softkey";
236const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700237const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700238const char* kON = "ON";
239const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700240const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700241
jvanverth34524262016-05-04 13:49:13 -0700242Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700243 : fCurrentMeasurement(0)
244 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700245 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500246 , fShowImGuiDebugWindow(false)
247 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500248 , fShowZoomWindow(false)
249 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700250 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500251 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500252 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700253 , fZoomLevel(0.0f)
jvanverthc265a922016-04-08 12:51:45 -0700254{
csmartdalton29d87152017-02-10 17:05:14 -0500255 static SkTaskGroup::Enabler kTaskGroupEnabler;
Greg Daniel285db442016-10-14 09:12:53 -0400256 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700257
258 static SkOnce initPathRendererNames;
259 initPathRendererNames([]() {
260 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
261 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
262 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400263 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500264 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700265 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
266 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
267 });
268
Brian Osman1df161a2017-02-09 12:10:20 -0500269 memset(fPaintTimes, 0, sizeof(fPaintTimes));
270 memset(fFlushTimes, 0, sizeof(fFlushTimes));
271 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700272
jvanverth2bb3b6d2016-04-08 07:24:09 -0700273 SkDebugf("Command line arguments: ");
274 for (int i = 1; i < argc; ++i) {
275 SkDebugf("%s ", argv[i]);
276 }
277 SkDebugf("\n");
278
279 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500280#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400281 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500282#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700283
Greg Daniel285db442016-10-14 09:12:53 -0400284 if (FLAGS_atrace) {
Brian Salomon175f5882017-05-12 12:02:50 -0400285 SkAssertResult(SkEventTracer::SetInstance(new SkATrace()));
Greg Daniel285db442016-10-14 09:12:53 -0400286 }
287
bsalomon6c471f72016-07-26 12:56:32 -0700288 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700289 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700290
csmartdalton578f0642017-02-24 16:04:47 -0700291 DisplayParams displayParams;
292 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500293 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700294 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700295 fWindow->setRequestedDisplayParams(displayParams);
296
jvanverth9f372462016-04-06 06:08:59 -0700297 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700298 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700299 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700300 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700301 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700302 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500303 fWindow->registerMouseFunc(on_mouse_handler, this);
304 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
305 fWindow->registerKeyFunc(on_key_handler, this);
306 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700307
brianosman622c8d52016-05-10 06:50:49 -0700308 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500309 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
310 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
311 fWindow->inval();
312 });
313 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
314 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
315 fWindow->inval();
316 });
Brian Osmanf6877092017-02-13 09:39:57 -0500317 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
318 this->fShowZoomWindow = !this->fShowZoomWindow;
319 fWindow->inval();
320 });
brianosman622c8d52016-05-10 06:50:49 -0700321 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
322 this->fDisplayStats = !this->fDisplayStats;
323 fWindow->inval();
324 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500325 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500326 switch (fColorMode) {
327 case ColorMode::kLegacy:
328 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
329 break;
330 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
331 this->setColorMode(ColorMode::kColorManagedSRGB8888);
332 break;
333 case ColorMode::kColorManagedSRGB8888:
334 this->setColorMode(ColorMode::kColorManagedLinearF16);
335 break;
336 case ColorMode::kColorManagedLinearF16:
337 this->setColorMode(ColorMode::kLegacy);
338 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500339 }
brianosman622c8d52016-05-10 06:50:49 -0700340 });
341 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
342 int previousSlide = fCurrentSlide;
343 fCurrentSlide++;
344 if (fCurrentSlide >= fSlides.count()) {
345 fCurrentSlide = 0;
346 }
347 this->setupCurrentSlide(previousSlide);
348 });
349 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
350 int previousSlide = fCurrentSlide;
351 fCurrentSlide--;
352 if (fCurrentSlide < 0) {
353 fCurrentSlide = fSlides.count() - 1;
354 }
355 this->setupCurrentSlide(previousSlide);
356 });
357 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
358 this->changeZoomLevel(1.f / 32.f);
359 fWindow->inval();
360 });
361 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
362 this->changeZoomLevel(-1.f / 32.f);
363 fWindow->inval();
364 });
jvanverthaf236b52016-05-20 06:01:06 -0700365 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Osman621491e2017-02-28 15:45:01 -0500366 sk_app::Window::BackendType newBackend = fBackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500367#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
jvanverthb8794cc2016-07-27 14:29:18 -0700368 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500369 newBackend = sk_app::Window::kNativeGL_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700370#ifdef SK_VULKAN
371 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500372 newBackend = sk_app::Window::kVulkan_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700373#endif
374 } else {
Brian Osman621491e2017-02-28 15:45:01 -0500375 newBackend = sk_app::Window::kRaster_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700376 }
Jim Van Verthd63c1022017-01-05 13:50:49 -0500377#elif defined(SK_BUILD_FOR_UNIX)
378 // Switching to and from Vulkan is problematic on Linux so disabled for now
379 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500380 newBackend = sk_app::Window::kNativeGL_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500381 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500382 newBackend = sk_app::Window::kRaster_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500383 }
384#endif
jvanverthaf236b52016-05-20 06:01:06 -0700385
Brian Osman621491e2017-02-28 15:45:01 -0500386 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700387 });
brianosman622c8d52016-05-10 06:50:49 -0700388
jvanverth2bb3b6d2016-04-08 07:24:09 -0700389 // set up slides
390 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500391 this->setStartupSlide();
392 if (FLAGS_list) {
393 this->listNames();
394 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700395
djsollen12d62a72016-04-21 07:59:44 -0700396 fAnimTimer.run();
397
Brian Osman79086b92017-02-10 13:36:16 -0500398 // ImGui initialization:
399 ImGuiIO& io = ImGui::GetIO();
400 io.DisplaySize.x = static_cast<float>(fWindow->width());
401 io.DisplaySize.y = static_cast<float>(fWindow->height());
402
403 // Keymap...
404 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
405 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
406 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
407 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
408 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
409 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
410 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
411 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
412 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
413 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
414 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
415 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
416 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
417 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
418 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
419 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
420 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
421 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
422 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
423
424 int w, h;
425 unsigned char* pixels;
426 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
427 SkImageInfo info = SkImageInfo::MakeA8(w, h);
428 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500429 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
430 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400431 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500432 fImGuiFontPaint.setShader(fontShader);
433 fImGuiFontPaint.setColor(SK_ColorWHITE);
434 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
435 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500436
Brian Osmana109e392017-02-24 09:49:14 -0500437 auto gamutImage = GetResourceAsImage("gamut.png");
438 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400439 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500440 }
441 fImGuiGamutPaint.setColor(SK_ColorWHITE);
442 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
443
csmartdalton578f0642017-02-24 16:04:47 -0700444 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700445}
446
jvanverth34524262016-05-04 13:49:13 -0700447void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700448 fAllSlideNames = Json::Value(Json::arrayValue);
449
jvanverth2bb3b6d2016-04-08 07:24:09 -0700450 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
451 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400452 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700453
454 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
455 sk_sp<Slide> slide(new GMSlide(gm.release()));
456 fSlides.push_back(slide);
457 }
458
459 gms = gms->next();
460 }
461
462 // reverse array
463 for (int i = 0; i < fSlides.count()/2; ++i) {
464 sk_sp<Slide> temp = fSlides[i];
465 fSlides[i] = fSlides[fSlides.count() - i - 1];
466 fSlides[fSlides.count() - i - 1] = temp;
467 }
468
jvanverthc7027ab2016-06-16 09:52:35 -0700469 // samples
470 const SkViewRegister* reg = SkViewRegister::Head();
471 while (reg) {
472 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700473 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
474 fSlides.push_back(slide);
475 }
jvanverthc7027ab2016-06-16 09:52:35 -0700476 reg = reg->next();
477 }
478
jvanverth2bb3b6d2016-04-08 07:24:09 -0700479 // SKPs
480 for (int i = 0; i < FLAGS_skps.count(); i++) {
481 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700482 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
483 continue;
484 }
485
jvanverth2bb3b6d2016-04-08 07:24:09 -0700486 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700487 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700488 if (slide) {
489 fSlides.push_back(slide);
490 }
491 } else {
492 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700493 SkString skpName;
494 while (it.next(&skpName)) {
495 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
496 continue;
497 }
498
499 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
500 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700501 if (slide) {
502 fSlides.push_back(slide);
503 }
504 }
505 }
506 }
liyuqian6f163d22016-06-13 12:26:45 -0700507
508 // JPGs
509 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
510 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
511 SkString jpgName;
512 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700513 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
514 continue;
515 }
516
liyuqian6f163d22016-06-13 12:26:45 -0700517 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
518 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
519 if (slide) {
520 fSlides.push_back(slide);
521 }
522 }
523 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700524}
525
526
jvanverth34524262016-05-04 13:49:13 -0700527Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700528 fWindow->detach();
529 delete fWindow;
530}
531
brianosman05de2162016-05-06 13:28:57 -0700532void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700533 if (!fWindow) {
534 return;
535 }
536 if (fWindow->sampleCount() < 0) {
537 return; // Surface hasn't been created yet.
538 }
539
jvanverth34524262016-05-04 13:49:13 -0700540 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700541 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700542
Brian Osman92004802017-03-06 11:47:26 -0500543 switch (fColorMode) {
544 case ColorMode::kLegacy:
545 title.append(" Legacy 8888");
546 break;
547 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
548 title.append(" ColorManaged 8888 (Nonlinear blending)");
549 break;
550 case ColorMode::kColorManagedSRGB8888:
551 title.append(" ColorManaged 8888");
552 break;
553 case ColorMode::kColorManagedLinearF16:
554 title.append(" ColorManaged F16");
555 break;
556 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500557
Brian Osman92004802017-03-06 11:47:26 -0500558 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500559 int curPrimaries = -1;
560 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
561 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
562 curPrimaries = i;
563 break;
564 }
565 }
566 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700567 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500568
csmartdalton578f0642017-02-24 16:04:47 -0700569 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700570 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700571 if (int msaa = fWindow->sampleCount()) {
572 title.appendf(" MSAA: %i", msaa);
573 }
574 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700575
576 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
577 if (GpuPathRenderers::kAll != pr) {
578 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
579 }
580
brianosman05de2162016-05-06 13:28:57 -0700581 fWindow->setTitle(title.c_str());
582}
583
Jim Van Verth6f449692017-02-14 15:16:46 -0500584void Viewer::setStartupSlide() {
585
586 if (!FLAGS_slide.isEmpty()) {
587 int count = fSlides.count();
588 for (int i = 0; i < count; i++) {
589 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
590 fCurrentSlide = i;
591 return;
592 }
593 }
594
595 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
596 this->listNames();
597 }
598
599 fCurrentSlide = 0;
600}
601
602void Viewer::listNames() {
603 int count = fSlides.count();
604 SkDebugf("All Slides:\n");
605 for (int i = 0; i < count; i++) {
606 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
607 }
608}
609
brianosman05de2162016-05-06 13:28:57 -0700610void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700611 if (fCurrentSlide == previousSlide) {
612 return; // no change; do nothing
613 }
liyuqian6f163d22016-06-13 12:26:45 -0700614 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700615 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700616
liyuqiane46e4f02016-05-20 07:32:19 -0700617 fGesture.reset();
618 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700619
Brian Osman42bb6ac2017-06-05 08:46:04 -0400620 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
621 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
622 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
623
624 // Start with a matrix that scales the slide to the available screen space
625 if (fWindow->scaleContentToFit()) {
626 if (windowRect.width() > 0 && windowRect.height() > 0) {
627 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700628 }
629 }
630
Brian Osman42bb6ac2017-06-05 08:46:04 -0400631 // Prevent the user from dragging content so far outside the window they can't find it again
632 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700633
brianosman05de2162016-05-06 13:28:57 -0700634 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700635 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700636 if (previousSlide >= 0) {
637 fSlides[previousSlide]->unload();
638 }
jvanverthc265a922016-04-08 12:51:45 -0700639 fWindow->inval();
640}
641
642#define MAX_ZOOM_LEVEL 8
643#define MIN_ZOOM_LEVEL -8
644
jvanverth34524262016-05-04 13:49:13 -0700645void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700646 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400647 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700648}
649
liyuqiand3cdbca2016-05-17 12:44:20 -0700650SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700651 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700652
Brian Osman42bb6ac2017-06-05 08:46:04 -0400653 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
654 : SK_Scalar1 + fZoomLevel;
655 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700656 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400657 m.preConcat(fDefaultMatrix);
658 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700659
liyuqiand3cdbca2016-05-17 12:44:20 -0700660 return m;
jvanverthc265a922016-04-08 12:51:45 -0700661}
662
Brian Osman621491e2017-02-28 15:45:01 -0500663void Viewer::setBackend(sk_app::Window::BackendType backendType) {
664 fBackendType = backendType;
665
666 fWindow->detach();
667
668#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
669 // Switching from OpenGL to Vulkan in the same window is problematic at this point on
670 // Windows, so we just delete the window and recreate it.
671 if (sk_app::Window::kVulkan_BackendType == fBackendType) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400672 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500673 delete fWindow;
674 fWindow = Window::CreateNativeWindow(nullptr);
675
676 // re-register callbacks
677 fCommands.attach(fWindow);
678 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
679 fWindow->registerPaintFunc(on_paint_handler, this);
680 fWindow->registerTouchFunc(on_touch_handler, this);
681 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
682 fWindow->registerMouseFunc(on_mouse_handler, this);
683 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
684 fWindow->registerKeyFunc(on_key_handler, this);
685 fWindow->registerCharFunc(on_char_handler, this);
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400686 fWindow->setRequestedDisplayParams(params);
Brian Osman621491e2017-02-28 15:45:01 -0500687 }
688#endif
689
690 fWindow->attach(fBackendType);
691}
692
Brian Osman92004802017-03-06 11:47:26 -0500693void Viewer::setColorMode(ColorMode colorMode) {
694 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700695
Brian Osmanf750fbc2017-02-08 10:47:28 -0500696 // 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 -0400697 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700698 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500699 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400700 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
701 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500702 if (wasInLegacy != wantLegacy) {
703 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700704 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500705 }
706
707 this->updateTitle();
708 fWindow->inval();
709}
710
711void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500712 SkAutoCanvasRestore autorestore(canvas, false);
713
Brian Osmanf750fbc2017-02-08 10:47:28 -0500714 // By default, we render directly into the window's surface/canvas
715 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500716 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700717
Brian Osmane0d4fba2017-03-15 10:24:55 -0400718 // If we're in any of the color managed modes, construct the color space we're going to use
719 sk_sp<SkColorSpace> cs = nullptr;
720 if (ColorMode::kLegacy != fColorMode) {
721 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
722 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
723 SkMatrix44 toXYZ;
724 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
725 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
726 }
727
728 // 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 -0500729 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500730 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500731 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500732 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400733 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
734 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
735
Brian Osman92004802017-03-06 11:47:26 -0500736 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
737 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400738 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
739 // with a special canvas (below) that has the color space attached
740 sk_sp<SkColorSpace> offscreenColorSpace =
741 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500742 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400743 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500744 offscreenSurface = canvas->makeSurface(info);
745 slideCanvas = offscreenSurface->getCanvas();
746 }
747
Brian Osmane0d4fba2017-03-15 10:24:55 -0400748 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
749 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
750 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
751 slideCanvas = xformCanvas.get();
752 }
753
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500754 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500755 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500756 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500757 // Time the painting logic of the slide
758 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500759 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500760 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500761 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500762
763 // Force a flush so we can time that, too
764 startTime = SkTime::GetMSecs();
765 slideCanvas->flush();
766 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500767
768 // If we rendered offscreen, snap an image and push the results to the window's canvas
769 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500770 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500771
772 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400773 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500774 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400775 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500776 SkPaint paint;
777 paint.setBlendMode(SkBlendMode::kSrc);
778 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700779 }
liyuqian6f163d22016-06-13 12:26:45 -0700780}
781
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700782void Viewer::onBackendCreated() {
783 this->updateTitle();
784 this->updateUIState();
785 this->setupCurrentSlide(-1);
786 fWindow->show();
787 fWindow->inval();
788}
Jim Van Verth6f449692017-02-14 15:16:46 -0500789
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700790void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500791 // Update ImGui input
792 ImGuiIO& io = ImGui::GetIO();
793 io.DeltaTime = 1.0f / 60.0f;
794 io.DisplaySize.x = static_cast<float>(fWindow->width());
795 io.DisplaySize.y = static_cast<float>(fWindow->height());
796
797 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
798 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
799 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
800
801 ImGui::NewFrame();
802
Brian Osmanf750fbc2017-02-08 10:47:28 -0500803 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700804
Brian Osman1df161a2017-02-09 12:10:20 -0500805 // Advance our timing bookkeeping
806 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
807 SkASSERT(fCurrentMeasurement < kMeasurementCount);
808
809 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700810 if (fDisplayStats) {
811 drawStats(canvas);
812 }
brianosman622c8d52016-05-10 06:50:49 -0700813 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700814
Brian Osman79086b92017-02-10 13:36:16 -0500815 drawImGui(canvas);
816
Brian Osman1df161a2017-02-09 12:10:20 -0500817 // Update the FPS
818 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700819}
820
jvanverth814e38d2016-06-06 08:48:47 -0700821bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
liyuqiand3cdbca2016-05-17 12:44:20 -0700822 void* castedOwner = reinterpret_cast<void*>(owner);
823 switch (state) {
824 case Window::kUp_InputState: {
825 fGesture.touchEnd(castedOwner);
826 break;
827 }
828 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400829 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700830 break;
831 }
832 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400833 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700834 break;
835 }
836 }
837 fWindow->inval();
838 return true;
839}
840
Jim Van Verthe7705782017-05-04 14:00:59 -0400841bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Jim Van Verthe7705782017-05-04 14:00:59 -0400842 switch (state) {
843 case Window::kUp_InputState: {
844 fGesture.touchEnd(nullptr);
845 break;
846 }
847 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400848 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400849 break;
850 }
851 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400852 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400853 break;
854 }
855 }
856 fWindow->inval();
857 return true;
858}
859
jvanverth34524262016-05-04 13:49:13 -0700860void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700861 static const float kPixelPerMS = 2.0f;
862 static const int kDisplayWidth = 130;
863 static const int kDisplayHeight = 100;
864 static const int kDisplayPadding = 10;
865 static const int kGraphPadding = 3;
866 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
867
Mike Reed3661bc92017-02-22 13:21:42 -0500868 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700869 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
870 SkIntToScalar(kDisplayPadding),
871 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
872 SkPaint paint;
873 canvas->save();
874
875 canvas->clipRect(rect);
876 paint.setColor(SK_ColorBLACK);
877 canvas->drawRect(rect, paint);
878 // draw the 16ms line
879 paint.setColor(SK_ColorLTGRAY);
880 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
881 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
882 paint.setColor(SK_ColorRED);
883 paint.setStyle(SkPaint::kStroke_Style);
884 canvas->drawRect(rect, paint);
885
886 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
887 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700888 int i = fCurrentMeasurement;
889 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500890 // Round to nearest values
891 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
892 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
893 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
894 int startY = SkScalarTruncToInt(rect.fBottom);
895 int endY = startY - flushHeight;
896 paint.setColor(SK_ColorRED);
897 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
898 SkIntToScalar(x), SkIntToScalar(endY), paint);
899 startY = endY;
900 endY = startY - paintHeight;
901 paint.setColor(SK_ColorGREEN);
902 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
903 SkIntToScalar(x), SkIntToScalar(endY), paint);
904 startY = endY;
905 endY = startY - animateHeight;
906 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700907 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
908 SkIntToScalar(x), SkIntToScalar(endY), paint);
909 i++;
910 i &= (kMeasurementCount - 1); // fast mod
911 x += xStep;
912 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700913
914 canvas->restore();
915}
916
Brian Osmana109e392017-02-24 09:49:14 -0500917static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
918 const ImVec2& pos, const ImVec2& size) {
919 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
920 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
921
922 // Invisible 10x10 button
923 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
924 ImGui::InvisibleButton(label, ImVec2(10, 10));
925
926 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
927 ImGuiIO& io = ImGui::GetIO();
928 // Normalized mouse position, relative to our gamut box
929 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
930 // Clamp to edge of box, convert back to primary scale
931 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
932 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
933 }
934
935 if (ImGui::IsItemHovered()) {
936 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
937 }
938
939 // Return screen coordinates for the caller. We could just return center here, but we'd have
940 // one frame of lag during drag.
941 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
942}
943
944static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
945 ImDrawList* drawList = ImGui::GetWindowDrawList();
946
947 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
948 // width, and scale the height to maintain aspect ratio.
949 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
950 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
951 ImVec2 pos = ImGui::GetCursorScreenPos();
952
953 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
954 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
955 // Magic numbers are pixel locations of the origin and upper-right corner.
956 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
957 ImVec2(242, 61), ImVec2(1897, 1922));
958 ImVec2 endPos = ImGui::GetCursorPos();
959
960 // Primary markers
961 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
962 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
963 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
964 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
965
966 // Gamut triangle
967 drawList->AddCircle(r, 5.0f, 0xFF000040);
968 drawList->AddCircle(g, 5.0f, 0xFF004000);
969 drawList->AddCircle(b, 5.0f, 0xFF400000);
970 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
971 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
972
973 // Re-position cursor immediate after the diagram for subsequent controls
974 ImGui::SetCursorPos(endPos);
975}
976
Brian Osman79086b92017-02-10 13:36:16 -0500977void Viewer::drawImGui(SkCanvas* canvas) {
978 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
979 if (fShowImGuiTestWindow) {
980 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
981 }
982
983 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -0500984 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
985 // always visible, we can end up in a layout feedback loop.
986 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -0500987 DisplayParams params = fWindow->getRequestedDisplayParams();
988 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -0500989 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
990 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -0500991 if (ImGui::CollapsingHeader("Backend")) {
992 int newBackend = static_cast<int>(fBackendType);
993 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
994 ImGui::SameLine();
995 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
996#if defined(SK_VULKAN)
997 ImGui::SameLine();
998 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
999#endif
1000 if (newBackend != fBackendType) {
1001 fDeferredActions.push_back([=]() {
1002 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1003 });
1004 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001005
Brian Salomon99a33902017-03-07 15:16:34 -05001006 const GrContext* ctx = fWindow->getGrContext();
1007 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1008 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1009 paramsChanged = true;
1010 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001011 bool* wire = &params.fGrContextOptions.fWireframeMode;
1012 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1013 paramsChanged = true;
1014 }
Brian Salomon99a33902017-03-07 15:16:34 -05001015
Brian Osman28b12522017-03-08 17:10:24 -05001016 if (ctx) {
1017 int sampleCount = fWindow->sampleCount();
1018 ImGui::Text("MSAA: "); ImGui::SameLine();
1019 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1020 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1021 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1022 ImGui::RadioButton("16", &sampleCount, 16);
1023
1024 if (sampleCount != params.fMSAASampleCount) {
1025 params.fMSAASampleCount = sampleCount;
1026 paramsChanged = true;
1027 }
1028 }
1029
Brian Osman8a9de3d2017-03-01 14:59:05 -05001030 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001031 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001032 auto prButton = [&](GpuPathRenderers x) {
1033 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001034 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1035 params.fGrContextOptions.fGpuPathRenderers = x;
1036 paramsChanged = true;
1037 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001038 }
1039 };
1040
1041 if (!ctx) {
1042 ImGui::RadioButton("Software", true);
1043 } else if (fWindow->sampleCount()) {
1044 prButton(GpuPathRenderers::kAll);
1045 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1046 prButton(GpuPathRenderers::kStencilAndCover);
1047 }
1048 if (ctx->caps()->sampleShadingSupport()) {
1049 prButton(GpuPathRenderers::kMSAA);
1050 }
1051 prButton(GpuPathRenderers::kTessellating);
1052 prButton(GpuPathRenderers::kDefault);
1053 prButton(GpuPathRenderers::kNone);
1054 } else {
1055 prButton(GpuPathRenderers::kAll);
Jim Van Verth83010462017-03-16 08:45:39 -04001056 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001057 prButton(GpuPathRenderers::kTessellating);
1058 prButton(GpuPathRenderers::kNone);
1059 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001060 ImGui::TreePop();
1061 }
Brian Osman621491e2017-02-28 15:45:01 -05001062 }
1063
Brian Osman79086b92017-02-10 13:36:16 -05001064 if (ImGui::CollapsingHeader("Slide")) {
1065 static ImGuiTextFilter filter;
1066 filter.Draw();
1067 int previousSlide = fCurrentSlide;
1068 fCurrentSlide = 0;
1069 for (auto slide : fSlides) {
1070 if (filter.PassFilter(slide->getName().c_str())) {
1071 ImGui::BulletText("%s", slide->getName().c_str());
1072 if (ImGui::IsItemClicked()) {
1073 setupCurrentSlide(previousSlide);
1074 break;
1075 }
1076 }
1077 ++fCurrentSlide;
1078 }
1079 if (fCurrentSlide >= fSlides.count()) {
1080 fCurrentSlide = previousSlide;
1081 }
1082 }
Brian Osmana109e392017-02-24 09:49:14 -05001083
1084 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001085 ColorMode newMode = fColorMode;
1086 auto cmButton = [&](ColorMode mode, const char* label) {
1087 if (ImGui::RadioButton(label, mode == fColorMode)) {
1088 newMode = mode;
1089 }
1090 };
1091
1092 cmButton(ColorMode::kLegacy, "Legacy 8888");
1093 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1094 "Color Managed 8888 (Nonlinear blending)");
1095 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1096 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1097
1098 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001099 // It isn't safe to switch color mode now (in the middle of painting). We might
1100 // tear down the back-end, etc... Defer this change until the next onIdle.
1101 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001102 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001103 });
Brian Osmana109e392017-02-24 09:49:14 -05001104 }
1105
1106 // Pick from common gamuts:
1107 int primariesIdx = 4; // Default: Custom
1108 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1109 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1110 primariesIdx = i;
1111 break;
1112 }
1113 }
1114
1115 if (ImGui::Combo("Primaries", &primariesIdx,
1116 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1117 if (primariesIdx >= 0 && primariesIdx <= 3) {
1118 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1119 }
1120 }
1121
1122 // Allow direct editing of gamut
1123 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1124 }
Brian Osman79086b92017-02-10 13:36:16 -05001125 }
Brian Salomon99a33902017-03-07 15:16:34 -05001126 if (paramsChanged) {
1127 fDeferredActions.push_back([=]() {
1128 fWindow->setRequestedDisplayParams(params);
1129 fWindow->inval();
1130 this->updateTitle();
1131 });
1132 }
Brian Osman79086b92017-02-10 13:36:16 -05001133 ImGui::End();
1134 }
1135
Brian Osmanf6877092017-02-13 09:39:57 -05001136 SkPaint zoomImagePaint;
1137 if (fShowZoomWindow && fLastImage) {
1138 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1139 static int zoomFactor = 4;
1140 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1141
Mike Reed0acd7952017-04-28 11:12:19 -04001142 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001143 zoomImagePaint.setColor(SK_ColorWHITE);
1144
1145 // Zoom by shrinking the corner UVs towards the mouse cursor
1146 ImVec2 mousePos = ImGui::GetMousePos();
1147 ImVec2 avail = ImGui::GetContentRegionAvail();
1148
1149 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1150 (avail.y * 0.5f) / zoomFactor);
1151 ImGui::Image(&zoomImagePaint, avail,
1152 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1153 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1154 }
1155
1156 ImGui::End();
1157 }
1158
Brian Osman79086b92017-02-10 13:36:16 -05001159 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1160 // (widgets, etc...) that have been issued
1161 ImGui::Render();
1162
1163 // Then we fetch the most recent data, and convert it so we can render with Skia
1164 const ImDrawData* drawData = ImGui::GetDrawData();
1165 SkTDArray<SkPoint> pos;
1166 SkTDArray<SkPoint> uv;
1167 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001168
1169 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1170 const ImDrawList* drawList = drawData->CmdLists[i];
1171
1172 // De-interleave all vertex data (sigh), convert to Skia types
1173 pos.rewind(); uv.rewind(); color.rewind();
1174 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1175 const ImDrawVert& vert = drawList->VtxBuffer[i];
1176 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1177 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1178 color.push(vert.col);
1179 }
1180 // ImGui colors are RGBA
1181 SkSwapRB(color.begin(), color.begin(), color.count());
1182
1183 int indexOffset = 0;
1184
1185 // Draw everything with canvas.drawVertices...
1186 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1187 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1188
1189 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1190 if (drawCmd->UserCallback) {
1191 drawCmd->UserCallback(drawList, drawCmd);
1192 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001193 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1194 SkASSERT(paint);
1195
Brian Osman79086b92017-02-10 13:36:16 -05001196 canvas->save();
1197 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1198 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001199 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1200 drawList->VtxBuffer.size(), pos.begin(),
1201 uv.begin(), color.begin(),
1202 drawCmd->ElemCount,
1203 drawList->IdxBuffer.begin() + indexOffset),
1204 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001205 indexOffset += drawCmd->ElemCount;
1206 canvas->restore();
1207 }
1208 }
1209 }
1210}
1211
liyuqian2edb0f42016-07-06 14:11:32 -07001212void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001213 for (int i = 0; i < fDeferredActions.count(); ++i) {
1214 fDeferredActions[i]();
1215 }
1216 fDeferredActions.reset();
1217
Brian Osman1df161a2017-02-09 12:10:20 -05001218 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001219 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001220 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1221 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1222
Brian Osman79086b92017-02-10 13:36:16 -05001223 ImGuiIO& io = ImGui::GetIO();
1224 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001225 fWindow->inval();
1226 }
jvanverth9f372462016-04-06 06:08:59 -07001227}
liyuqiane5a6cd92016-05-27 08:52:52 -07001228
1229void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001230 if (!fWindow) {
1231 return;
1232 }
1233 if (fWindow->sampleCount() < 0) {
1234 return; // Surface hasn't been created yet.
1235 }
1236
liyuqianb73c24b2016-06-03 08:47:23 -07001237 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001238 Json::Value slideState(Json::objectValue);
1239 slideState[kName] = kSlideStateName;
1240 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001241 if (fAllSlideNames.size() == 0) {
1242 for(auto slide : fSlides) {
1243 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1244 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001245 }
liyuqian1f508fd2016-06-07 06:57:40 -07001246 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001247
liyuqianb73c24b2016-06-03 08:47:23 -07001248 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001249 Json::Value backendState(Json::objectValue);
1250 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001251 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001252 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001253 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001254 backendState[kOptions].append(Json::Value(str));
1255 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001256
csmartdalton578f0642017-02-24 16:04:47 -07001257 // MSAA state
1258 Json::Value msaaState(Json::objectValue);
1259 msaaState[kName] = kMSAAStateName;
1260 msaaState[kValue] = fWindow->sampleCount();
1261 msaaState[kOptions] = Json::Value(Json::arrayValue);
1262 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1263 msaaState[kOptions].append(Json::Value(0));
1264 } else {
1265 for (int msaa : {0, 4, 8, 16}) {
1266 msaaState[kOptions].append(Json::Value(msaa));
1267 }
1268 }
1269
csmartdalton61cd31a2017-02-27 17:00:53 -07001270 // Path renderer state
1271 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1272 Json::Value prState(Json::objectValue);
1273 prState[kName] = kPathRendererStateName;
1274 prState[kValue] = gPathRendererNames[pr];
1275 prState[kOptions] = Json::Value(Json::arrayValue);
1276 const GrContext* ctx = fWindow->getGrContext();
1277 if (!ctx) {
1278 prState[kOptions].append("Software");
1279 } else if (fWindow->sampleCount()) {
1280 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1281 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1282 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1283 }
1284 if (ctx->caps()->sampleShadingSupport()) {
1285 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1286 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001287 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001288 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1289 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1290 } else {
1291 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Jim Van Verth83010462017-03-16 08:45:39 -04001292 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001293 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001294 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1295 }
1296
Brian Salomon99a33902017-03-07 15:16:34 -05001297 // Instanced rendering state
1298 Json::Value instState(Json::objectValue);
1299 instState[kName] = kInstancedRenderingStateName;
1300 if (ctx) {
1301 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1302 instState[kValue] = kON;
1303 } else {
1304 instState[kValue] = kOFF;
1305 }
1306 instState[kOptions] = Json::Value(Json::arrayValue);
1307 instState[kOptions].append(kOFF);
1308 instState[kOptions].append(kON);
1309 }
1310
liyuqianb73c24b2016-06-03 08:47:23 -07001311 // Softkey state
1312 Json::Value softkeyState(Json::objectValue);
1313 softkeyState[kName] = kSoftkeyStateName;
1314 softkeyState[kValue] = kSoftkeyHint;
1315 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1316 softkeyState[kOptions].append(kSoftkeyHint);
1317 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1318 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1319 }
1320
liyuqian1f508fd2016-06-07 06:57:40 -07001321 // FPS state
1322 Json::Value fpsState(Json::objectValue);
1323 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001324 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1325 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1326 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1327 fAnimateTimes[idx],
1328 fPaintTimes[idx],
1329 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001330 fpsState[kOptions] = Json::Value(Json::arrayValue);
1331
liyuqiane5a6cd92016-05-27 08:52:52 -07001332 Json::Value state(Json::arrayValue);
1333 state.append(slideState);
1334 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001335 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001336 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001337 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001338 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001339 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001340
1341 fWindow->setUIState(state);
1342}
1343
1344void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001345 // For those who will add more features to handle the state change in this function:
1346 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1347 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1348 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001349 if (stateName.equals(kSlideStateName)) {
1350 int previousSlide = fCurrentSlide;
1351 fCurrentSlide = 0;
1352 for(auto slide : fSlides) {
1353 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001354 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001355 break;
1356 }
1357 fCurrentSlide++;
1358 }
1359 if (fCurrentSlide >= fSlides.count()) {
1360 fCurrentSlide = previousSlide;
1361 SkDebugf("Slide not found: %s", stateValue.c_str());
1362 }
liyuqian6cb70252016-06-02 12:16:25 -07001363 } else if (stateName.equals(kBackendStateName)) {
1364 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1365 if (stateValue.equals(kBackendTypeStrings[i])) {
1366 if (fBackendType != i) {
1367 fBackendType = (sk_app::Window::BackendType)i;
1368 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001369 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001370 }
1371 break;
1372 }
1373 }
csmartdalton578f0642017-02-24 16:04:47 -07001374 } else if (stateName.equals(kMSAAStateName)) {
1375 DisplayParams params = fWindow->getRequestedDisplayParams();
1376 int sampleCount = atoi(stateValue.c_str());
1377 if (sampleCount != params.fMSAASampleCount) {
1378 params.fMSAASampleCount = sampleCount;
1379 fWindow->setRequestedDisplayParams(params);
1380 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001381 this->updateTitle();
1382 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001383 }
1384 } else if (stateName.equals(kPathRendererStateName)) {
1385 DisplayParams params = fWindow->getRequestedDisplayParams();
1386 for (const auto& pair : gPathRendererNames) {
1387 if (pair.second == stateValue.c_str()) {
1388 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1389 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1390 fWindow->setRequestedDisplayParams(params);
1391 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001392 this->updateTitle();
1393 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001394 }
1395 break;
1396 }
csmartdalton578f0642017-02-24 16:04:47 -07001397 }
Brian Salomon99a33902017-03-07 15:16:34 -05001398 } else if (stateName.equals(kInstancedRenderingStateName)) {
1399 DisplayParams params = fWindow->getRequestedDisplayParams();
1400 bool value = !strcmp(stateValue.c_str(), kON);
1401 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1402 params.fGrContextOptions.fEnableInstancedRendering = value;
1403 fWindow->setRequestedDisplayParams(params);
1404 fWindow->inval();
1405 this->updateTitle();
1406 this->updateUIState();
1407 }
liyuqianb73c24b2016-06-03 08:47:23 -07001408 } else if (stateName.equals(kSoftkeyStateName)) {
1409 if (!stateValue.equals(kSoftkeyHint)) {
1410 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001411 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001412 }
liyuqian2edb0f42016-07-06 14:11:32 -07001413 } else if (stateName.equals(kRefreshStateName)) {
1414 // This state is actually NOT in the UI state.
1415 // We use this to allow Android to quickly set bool fRefresh.
1416 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001417 } else {
1418 SkDebugf("Unknown stateName: %s", stateName.c_str());
1419 }
1420}
Brian Osman79086b92017-02-10 13:36:16 -05001421
1422bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1423 return fCommands.onKey(key, state, modifiers);
1424}
1425
1426bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001427 if (fSlides[fCurrentSlide]->onChar(c)) {
1428 fWindow->inval();
1429 return true;
1430 }
1431
Brian Osman79086b92017-02-10 13:36:16 -05001432 return fCommands.onChar(c, modifiers);
1433}