blob: de4c6e0cbfaf06d23e3491fa9195ba738daffc2b [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 }
87 return true;
88}
89
90static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
91 ImGuiIO& io = ImGui::GetIO();
92 io.MouseWheel += delta;
93 return true;
94}
95
96static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
97 void* userData) {
98 ImGuiIO& io = ImGui::GetIO();
99 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
100
101 if (io.WantCaptureKeyboard) {
102 return true;
103 } else {
104 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
105 return viewer->onKey(key, state, modifiers);
106 }
107}
108
109static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
110 ImGuiIO& io = ImGui::GetIO();
111 if (io.WantTextInput) {
112 if (c > 0 && c < 0x10000) {
113 io.AddInputCharacter(c);
114 }
115 return true;
116 } else {
117 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
118 return viewer->onChar(c, modifiers);
119 }
120}
121
Brian Osman2dd96932016-10-18 15:33:53 -0400122static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400123
Brian Osman2dd96932016-10-18 15:33:53 -0400124static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700125 "[~][^]substring[$] [...] of bench name to run.\n"
126 "Multiple matches may be separated by spaces.\n"
127 "~ causes a matching bench to always be skipped\n"
128 "^ requires the start of the bench to match\n"
129 "$ requires the end of the bench to match\n"
130 "^ and $ requires an exact match\n"
131 "If a bench does not match any list entry,\n"
132 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700133
Jim Van Verth6f449692017-02-14 15:16:46 -0500134DEFINE_string(slide, "", "Start on this sample.");
135DEFINE_bool(list, false, "List samples?");
136
bsalomon6c471f72016-07-26 12:56:32 -0700137#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700138# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700139#else
140# define BACKENDS_STR "\"sw\" and \"gl\""
141#endif
142
liyuqian71491dc2016-06-09 12:02:34 -0700143#ifdef SK_BUILD_FOR_ANDROID
Brian Osman2dd96932016-10-18 15:33:53 -0400144static DEFINE_string(skps, "/data/local/tmp/skia", "Directory to read skps from.");
145static DEFINE_string(jpgs, "/data/local/tmp/skia", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700146#else
Brian Osman2dd96932016-10-18 15:33:53 -0400147static DEFINE_string(skps, "skps", "Directory to read skps from.");
148static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700149#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700150
Brian Osman2dd96932016-10-18 15:33:53 -0400151static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700152
Brian Osman2dd96932016-10-18 15:33:53 -0400153static DEFINE_bool(atrace, false, "Enable support for using ATrace. ATrace is only supported on Android.");
Greg Daniel285db442016-10-14 09:12:53 -0400154
csmartdalton578f0642017-02-24 16:04:47 -0700155DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700156DEFINE_pathrenderer_flag;
157
Brian Salomon41eac792017-03-08 14:03:56 -0500158DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
159
jvanverthaf236b52016-05-20 06:01:06 -0700160const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700161 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700162#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700163 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700164#endif
csmartdalton578f0642017-02-24 16:04:47 -0700165 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700166};
167
bsalomon6c471f72016-07-26 12:56:32 -0700168static sk_app::Window::BackendType get_backend_type(const char* str) {
169#ifdef SK_VULKAN
170 if (0 == strcmp(str, "vk")) {
171 return sk_app::Window::kVulkan_BackendType;
172 } else
173#endif
174 if (0 == strcmp(str, "gl")) {
175 return sk_app::Window::kNativeGL_BackendType;
176 } else if (0 == strcmp(str, "sw")) {
177 return sk_app::Window::kRaster_BackendType;
178 } else {
179 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
180 return sk_app::Window::kRaster_BackendType;
181 }
182}
183
Brian Osmana109e392017-02-24 09:49:14 -0500184static SkColorSpacePrimaries gSrgbPrimaries = {
185 0.64f, 0.33f,
186 0.30f, 0.60f,
187 0.15f, 0.06f,
188 0.3127f, 0.3290f };
189
190static SkColorSpacePrimaries gAdobePrimaries = {
191 0.64f, 0.33f,
192 0.21f, 0.71f,
193 0.15f, 0.06f,
194 0.3127f, 0.3290f };
195
196static SkColorSpacePrimaries gP3Primaries = {
197 0.680f, 0.320f,
198 0.265f, 0.690f,
199 0.150f, 0.060f,
200 0.3127f, 0.3290f };
201
202static SkColorSpacePrimaries gRec2020Primaries = {
203 0.708f, 0.292f,
204 0.170f, 0.797f,
205 0.131f, 0.046f,
206 0.3127f, 0.3290f };
207
208struct NamedPrimaries {
209 const char* fName;
210 SkColorSpacePrimaries* fPrimaries;
211} gNamedPrimaries[] = {
212 { "sRGB", &gSrgbPrimaries },
213 { "AdobeRGB", &gAdobePrimaries },
214 { "P3", &gP3Primaries },
215 { "Rec. 2020", &gRec2020Primaries },
216};
217
218static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
219 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
220}
221
liyuqiane5a6cd92016-05-27 08:52:52 -0700222const char* kName = "name";
223const char* kValue = "value";
224const char* kOptions = "options";
225const char* kSlideStateName = "Slide";
226const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700227const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700228const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500229const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700230const char* kSoftkeyStateName = "Softkey";
231const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700232const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700233const char* kON = "ON";
234const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700235const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700236
jvanverth34524262016-05-04 13:49:13 -0700237Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700238 : fCurrentMeasurement(0)
239 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700240 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500241 , fShowImGuiDebugWindow(false)
242 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500243 , fShowZoomWindow(false)
244 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700245 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500246 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500247 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700248 , fZoomCenterX(0.0f)
249 , fZoomCenterY(0.0f)
250 , fZoomLevel(0.0f)
251 , fZoomScale(SK_Scalar1)
jvanverthc265a922016-04-08 12:51:45 -0700252{
csmartdalton29d87152017-02-10 17:05:14 -0500253 static SkTaskGroup::Enabler kTaskGroupEnabler;
Greg Daniel285db442016-10-14 09:12:53 -0400254 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700255
256 static SkOnce initPathRendererNames;
257 initPathRendererNames([]() {
258 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
259 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
260 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400261 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500262 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700263 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
264 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
265 });
266
Brian Osman1df161a2017-02-09 12:10:20 -0500267 memset(fPaintTimes, 0, sizeof(fPaintTimes));
268 memset(fFlushTimes, 0, sizeof(fFlushTimes));
269 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700270
jvanverth2bb3b6d2016-04-08 07:24:09 -0700271 SkDebugf("Command line arguments: ");
272 for (int i = 1; i < argc; ++i) {
273 SkDebugf("%s ", argv[i]);
274 }
275 SkDebugf("\n");
276
277 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500278#ifdef SK_BUILD_FOR_ANDROID
279 SetResourcePath("/data/local/tmp/skia");
280#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700281
Greg Daniel285db442016-10-14 09:12:53 -0400282 if (FLAGS_atrace) {
283 SkEventTracer::SetInstance(new SkATrace());
284 }
285
bsalomon6c471f72016-07-26 12:56:32 -0700286 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700287 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700288
csmartdalton578f0642017-02-24 16:04:47 -0700289 DisplayParams displayParams;
290 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500291 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700292 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700293 fWindow->setRequestedDisplayParams(displayParams);
294
jvanverth9f372462016-04-06 06:08:59 -0700295 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700296 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700297 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700298 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700299 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700300 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500301 fWindow->registerMouseFunc(on_mouse_handler, this);
302 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
303 fWindow->registerKeyFunc(on_key_handler, this);
304 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700305
brianosman622c8d52016-05-10 06:50:49 -0700306 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500307 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
308 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
309 fWindow->inval();
310 });
311 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
312 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
313 fWindow->inval();
314 });
Brian Osmanf6877092017-02-13 09:39:57 -0500315 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
316 this->fShowZoomWindow = !this->fShowZoomWindow;
317 fWindow->inval();
318 });
brianosman622c8d52016-05-10 06:50:49 -0700319 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
320 this->fDisplayStats = !this->fDisplayStats;
321 fWindow->inval();
322 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500323 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500324 switch (fColorMode) {
325 case ColorMode::kLegacy:
326 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
327 break;
328 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
329 this->setColorMode(ColorMode::kColorManagedSRGB8888);
330 break;
331 case ColorMode::kColorManagedSRGB8888:
332 this->setColorMode(ColorMode::kColorManagedLinearF16);
333 break;
334 case ColorMode::kColorManagedLinearF16:
335 this->setColorMode(ColorMode::kLegacy);
336 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500337 }
brianosman622c8d52016-05-10 06:50:49 -0700338 });
339 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
340 int previousSlide = fCurrentSlide;
341 fCurrentSlide++;
342 if (fCurrentSlide >= fSlides.count()) {
343 fCurrentSlide = 0;
344 }
345 this->setupCurrentSlide(previousSlide);
346 });
347 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
348 int previousSlide = fCurrentSlide;
349 fCurrentSlide--;
350 if (fCurrentSlide < 0) {
351 fCurrentSlide = fSlides.count() - 1;
352 }
353 this->setupCurrentSlide(previousSlide);
354 });
355 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
356 this->changeZoomLevel(1.f / 32.f);
357 fWindow->inval();
358 });
359 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
360 this->changeZoomLevel(-1.f / 32.f);
361 fWindow->inval();
362 });
jvanverthaf236b52016-05-20 06:01:06 -0700363 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Osman621491e2017-02-28 15:45:01 -0500364 sk_app::Window::BackendType newBackend = fBackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500365#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
jvanverthb8794cc2016-07-27 14:29:18 -0700366 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500367 newBackend = sk_app::Window::kNativeGL_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700368#ifdef SK_VULKAN
369 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500370 newBackend = sk_app::Window::kVulkan_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700371#endif
372 } else {
Brian Osman621491e2017-02-28 15:45:01 -0500373 newBackend = sk_app::Window::kRaster_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700374 }
Jim Van Verthd63c1022017-01-05 13:50:49 -0500375#elif defined(SK_BUILD_FOR_UNIX)
376 // Switching to and from Vulkan is problematic on Linux so disabled for now
377 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500378 newBackend = sk_app::Window::kNativeGL_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500379 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500380 newBackend = sk_app::Window::kRaster_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500381 }
382#endif
jvanverthaf236b52016-05-20 06:01:06 -0700383
Brian Osman621491e2017-02-28 15:45:01 -0500384 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700385 });
brianosman622c8d52016-05-10 06:50:49 -0700386
jvanverth2bb3b6d2016-04-08 07:24:09 -0700387 // set up slides
388 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500389 this->setStartupSlide();
390 if (FLAGS_list) {
391 this->listNames();
392 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700393
djsollen12d62a72016-04-21 07:59:44 -0700394 fAnimTimer.run();
395
Brian Osman79086b92017-02-10 13:36:16 -0500396 // ImGui initialization:
397 ImGuiIO& io = ImGui::GetIO();
398 io.DisplaySize.x = static_cast<float>(fWindow->width());
399 io.DisplaySize.y = static_cast<float>(fWindow->height());
400
401 // Keymap...
402 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
403 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
404 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
405 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
406 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
407 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
408 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
409 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
410 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
411 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
412 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
413 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
414 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
415 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
416 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
417 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
418 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
419 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
420 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
421
422 int w, h;
423 unsigned char* pixels;
424 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
425 SkImageInfo info = SkImageInfo::MakeA8(w, h);
426 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500427 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
428 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
429 auto fontShader = fontImage->makeShader(SkShader::kClamp_TileMode, SkShader::kClamp_TileMode,
430 &localMatrix);
431 fImGuiFontPaint.setShader(fontShader);
432 fImGuiFontPaint.setColor(SK_ColorWHITE);
433 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
434 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500435
Brian Osmana109e392017-02-24 09:49:14 -0500436 auto gamutImage = GetResourceAsImage("gamut.png");
437 if (gamutImage) {
438 auto gamutShader = gamutImage->makeShader(SkShader::kClamp_TileMode,
439 SkShader::kClamp_TileMode);
440 fImGuiGamutPaint.setShader(gamutShader);
441 }
442 fImGuiGamutPaint.setColor(SK_ColorWHITE);
443 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
444
csmartdalton578f0642017-02-24 16:04:47 -0700445 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700446}
447
jvanverth34524262016-05-04 13:49:13 -0700448void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700449 fAllSlideNames = Json::Value(Json::arrayValue);
450
jvanverth2bb3b6d2016-04-08 07:24:09 -0700451 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
452 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400453 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700454
455 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
456 sk_sp<Slide> slide(new GMSlide(gm.release()));
457 fSlides.push_back(slide);
458 }
459
460 gms = gms->next();
461 }
462
463 // reverse array
464 for (int i = 0; i < fSlides.count()/2; ++i) {
465 sk_sp<Slide> temp = fSlides[i];
466 fSlides[i] = fSlides[fSlides.count() - i - 1];
467 fSlides[fSlides.count() - i - 1] = temp;
468 }
469
jvanverthc7027ab2016-06-16 09:52:35 -0700470 // samples
471 const SkViewRegister* reg = SkViewRegister::Head();
472 while (reg) {
473 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700474 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
475 fSlides.push_back(slide);
476 }
jvanverthc7027ab2016-06-16 09:52:35 -0700477 reg = reg->next();
478 }
479
jvanverth2bb3b6d2016-04-08 07:24:09 -0700480 // SKPs
481 for (int i = 0; i < FLAGS_skps.count(); i++) {
482 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700483 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
484 continue;
485 }
486
jvanverth2bb3b6d2016-04-08 07:24:09 -0700487 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700488 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700489 if (slide) {
490 fSlides.push_back(slide);
491 }
492 } else {
493 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700494 SkString skpName;
495 while (it.next(&skpName)) {
496 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
497 continue;
498 }
499
500 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
501 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700502 if (slide) {
503 fSlides.push_back(slide);
504 }
505 }
506 }
507 }
liyuqian6f163d22016-06-13 12:26:45 -0700508
509 // JPGs
510 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
511 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
512 SkString jpgName;
513 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700514 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
515 continue;
516 }
517
liyuqian6f163d22016-06-13 12:26:45 -0700518 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
519 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
520 if (slide) {
521 fSlides.push_back(slide);
522 }
523 }
524 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700525}
526
527
jvanverth34524262016-05-04 13:49:13 -0700528Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700529 fWindow->detach();
530 delete fWindow;
531}
532
brianosman05de2162016-05-06 13:28:57 -0700533void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700534 if (!fWindow) {
535 return;
536 }
537 if (fWindow->sampleCount() < 0) {
538 return; // Surface hasn't been created yet.
539 }
540
jvanverth34524262016-05-04 13:49:13 -0700541 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700542 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700543
Brian Osman92004802017-03-06 11:47:26 -0500544 switch (fColorMode) {
545 case ColorMode::kLegacy:
546 title.append(" Legacy 8888");
547 break;
548 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
549 title.append(" ColorManaged 8888 (Nonlinear blending)");
550 break;
551 case ColorMode::kColorManagedSRGB8888:
552 title.append(" ColorManaged 8888");
553 break;
554 case ColorMode::kColorManagedLinearF16:
555 title.append(" ColorManaged F16");
556 break;
557 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500558
Brian Osman92004802017-03-06 11:47:26 -0500559 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500560 int curPrimaries = -1;
561 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
562 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
563 curPrimaries = i;
564 break;
565 }
566 }
567 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700568 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500569
csmartdalton578f0642017-02-24 16:04:47 -0700570 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700571 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700572 if (int msaa = fWindow->sampleCount()) {
573 title.appendf(" MSAA: %i", msaa);
574 }
575 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700576
577 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
578 if (GpuPathRenderers::kAll != pr) {
579 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
580 }
581
brianosman05de2162016-05-06 13:28:57 -0700582 fWindow->setTitle(title.c_str());
583}
584
Jim Van Verth6f449692017-02-14 15:16:46 -0500585void Viewer::setStartupSlide() {
586
587 if (!FLAGS_slide.isEmpty()) {
588 int count = fSlides.count();
589 for (int i = 0; i < count; i++) {
590 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
591 fCurrentSlide = i;
592 return;
593 }
594 }
595
596 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
597 this->listNames();
598 }
599
600 fCurrentSlide = 0;
601}
602
603void Viewer::listNames() {
604 int count = fSlides.count();
605 SkDebugf("All Slides:\n");
606 for (int i = 0; i < count; i++) {
607 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
608 }
609}
610
brianosman05de2162016-05-06 13:28:57 -0700611void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700612 if (fCurrentSlide == previousSlide) {
613 return; // no change; do nothing
614 }
liyuqian6f163d22016-06-13 12:26:45 -0700615 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700616 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700617
liyuqiane46e4f02016-05-20 07:32:19 -0700618 fGesture.reset();
619 fDefaultMatrix.reset();
620 fDefaultMatrixInv.reset();
621
622 if (fWindow->supportsContentRect() && fWindow->scaleContentToFit()) {
623 const SkRect contentRect = fWindow->getContentRect();
624 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
625 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
626 if (contentRect.width() > 0 && contentRect.height() > 0) {
627 fDefaultMatrix.setRectToRect(slideBounds, contentRect, SkMatrix::kStart_ScaleToFit);
liyuqianbeb1c672016-05-20 11:41:01 -0700628 SkAssertResult(fDefaultMatrix.invert(&fDefaultMatrixInv));
liyuqiane46e4f02016-05-20 07:32:19 -0700629 }
630 }
631
632 if (fWindow->supportsContentRect()) {
633 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
634 SkRect windowRect = fWindow->getContentRect();
635 fDefaultMatrixInv.mapRect(&windowRect);
jvanverth1e305ba2016-06-01 09:39:15 -0700636 fGesture.setTransLimit(SkRect::MakeWH(SkIntToScalar(slideSize.width()),
637 SkIntToScalar(slideSize.height())),
638 windowRect);
liyuqiane46e4f02016-05-20 07:32:19 -0700639 }
640
brianosman05de2162016-05-06 13:28:57 -0700641 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700642 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700643 if (previousSlide >= 0) {
644 fSlides[previousSlide]->unload();
645 }
jvanverthc265a922016-04-08 12:51:45 -0700646 fWindow->inval();
647}
648
649#define MAX_ZOOM_LEVEL 8
650#define MIN_ZOOM_LEVEL -8
651
jvanverth34524262016-05-04 13:49:13 -0700652void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700653 fZoomLevel += delta;
654 if (fZoomLevel > 0) {
655 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
656 fZoomScale = fZoomLevel + SK_Scalar1;
657 } else if (fZoomLevel < 0) {
658 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
659 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
660 } else {
661 fZoomScale = SK_Scalar1;
662 }
jvanverthc265a922016-04-08 12:51:45 -0700663}
664
liyuqiand3cdbca2016-05-17 12:44:20 -0700665SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700666 SkMatrix m;
667 m.reset();
668
669 if (fZoomLevel) {
670 SkPoint center;
671 //m = this->getLocalMatrix();//.invert(&m);
672 m.mapXY(fZoomCenterX, fZoomCenterY, &center);
673 SkScalar cx = center.fX;
674 SkScalar cy = center.fY;
675
676 m.setTranslate(-cx, -cy);
677 m.postScale(fZoomScale, fZoomScale);
678 m.postTranslate(cx, cy);
679 }
680
liyuqiand3cdbca2016-05-17 12:44:20 -0700681 m.preConcat(fGesture.localM());
682 m.preConcat(fGesture.globalM());
jvanverthc265a922016-04-08 12:51:45 -0700683
liyuqiand3cdbca2016-05-17 12:44:20 -0700684 return m;
jvanverthc265a922016-04-08 12:51:45 -0700685}
686
Brian Osman621491e2017-02-28 15:45:01 -0500687void Viewer::setBackend(sk_app::Window::BackendType backendType) {
688 fBackendType = backendType;
689
690 fWindow->detach();
691
692#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
693 // Switching from OpenGL to Vulkan in the same window is problematic at this point on
694 // Windows, so we just delete the window and recreate it.
695 if (sk_app::Window::kVulkan_BackendType == fBackendType) {
696 delete fWindow;
697 fWindow = Window::CreateNativeWindow(nullptr);
698
699 // re-register callbacks
700 fCommands.attach(fWindow);
701 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
702 fWindow->registerPaintFunc(on_paint_handler, this);
703 fWindow->registerTouchFunc(on_touch_handler, this);
704 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
705 fWindow->registerMouseFunc(on_mouse_handler, this);
706 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
707 fWindow->registerKeyFunc(on_key_handler, this);
708 fWindow->registerCharFunc(on_char_handler, this);
709 }
710#endif
711
712 fWindow->attach(fBackendType);
713}
714
Brian Osman92004802017-03-06 11:47:26 -0500715void Viewer::setColorMode(ColorMode colorMode) {
716 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700717
Brian Osmanf750fbc2017-02-08 10:47:28 -0500718 // 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 -0400719 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700720 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500721 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400722 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
723 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500724 if (wasInLegacy != wantLegacy) {
725 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700726 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500727 }
728
729 this->updateTitle();
730 fWindow->inval();
731}
732
733void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500734 SkAutoCanvasRestore autorestore(canvas, false);
735
djsollen12d62a72016-04-21 07:59:44 -0700736 if (fWindow->supportsContentRect()) {
737 SkRect contentRect = fWindow->getContentRect();
738 canvas->clipRect(contentRect);
739 canvas->translate(contentRect.fLeft, contentRect.fTop);
740 }
741
Brian Osmanf750fbc2017-02-08 10:47:28 -0500742 // By default, we render directly into the window's surface/canvas
743 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500744 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700745
Brian Osmane0d4fba2017-03-15 10:24:55 -0400746 // If we're in any of the color managed modes, construct the color space we're going to use
747 sk_sp<SkColorSpace> cs = nullptr;
748 if (ColorMode::kLegacy != fColorMode) {
749 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
750 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
751 SkMatrix44 toXYZ;
752 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
753 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
754 }
755
756 // 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 -0500757 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500758 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500759 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500760 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400761 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
762 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
763
Brian Osman92004802017-03-06 11:47:26 -0500764 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
765 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400766 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
767 // with a special canvas (below) that has the color space attached
768 sk_sp<SkColorSpace> offscreenColorSpace =
769 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500770 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400771 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500772 offscreenSurface = canvas->makeSurface(info);
773 slideCanvas = offscreenSurface->getCanvas();
774 }
775
Brian Osmane0d4fba2017-03-15 10:24:55 -0400776 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
777 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
778 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
779 slideCanvas = xformCanvas.get();
780 }
781
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500782 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500783 slideCanvas->clear(SK_ColorWHITE);
784 slideCanvas->concat(fDefaultMatrix);
785 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500786 // Time the painting logic of the slide
787 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500788 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500789 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500790 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500791
792 // Force a flush so we can time that, too
793 startTime = SkTime::GetMSecs();
794 slideCanvas->flush();
795 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500796
797 // If we rendered offscreen, snap an image and push the results to the window's canvas
798 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500799 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500800
801 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400802 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500803 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400804 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500805 SkPaint paint;
806 paint.setBlendMode(SkBlendMode::kSrc);
807 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700808 }
liyuqian6f163d22016-06-13 12:26:45 -0700809}
810
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700811void Viewer::onBackendCreated() {
812 this->updateTitle();
813 this->updateUIState();
814 this->setupCurrentSlide(-1);
815 fWindow->show();
816 fWindow->inval();
817}
Jim Van Verth6f449692017-02-14 15:16:46 -0500818
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700819void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500820 // Update ImGui input
821 ImGuiIO& io = ImGui::GetIO();
822 io.DeltaTime = 1.0f / 60.0f;
823 io.DisplaySize.x = static_cast<float>(fWindow->width());
824 io.DisplaySize.y = static_cast<float>(fWindow->height());
825
826 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
827 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
828 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
829
830 ImGui::NewFrame();
831
Brian Osmanf750fbc2017-02-08 10:47:28 -0500832 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700833
Brian Osman1df161a2017-02-09 12:10:20 -0500834 // Advance our timing bookkeeping
835 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
836 SkASSERT(fCurrentMeasurement < kMeasurementCount);
837
838 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700839 if (fDisplayStats) {
840 drawStats(canvas);
841 }
brianosman622c8d52016-05-10 06:50:49 -0700842 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700843
Brian Osman79086b92017-02-10 13:36:16 -0500844 drawImGui(canvas);
845
Brian Osman1df161a2017-02-09 12:10:20 -0500846 // Update the FPS
847 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700848}
849
jvanverth814e38d2016-06-06 08:48:47 -0700850bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
liyuqiand3cdbca2016-05-17 12:44:20 -0700851 void* castedOwner = reinterpret_cast<void*>(owner);
liyuqiane46e4f02016-05-20 07:32:19 -0700852 SkPoint touchPoint = fDefaultMatrixInv.mapXY(x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700853 switch (state) {
854 case Window::kUp_InputState: {
855 fGesture.touchEnd(castedOwner);
856 break;
857 }
858 case Window::kDown_InputState: {
liyuqiane46e4f02016-05-20 07:32:19 -0700859 fGesture.touchBegin(castedOwner, touchPoint.fX, touchPoint.fY);
liyuqiand3cdbca2016-05-17 12:44:20 -0700860 break;
861 }
862 case Window::kMove_InputState: {
liyuqiane46e4f02016-05-20 07:32:19 -0700863 fGesture.touchMoved(castedOwner, touchPoint.fX, touchPoint.fY);
liyuqiand3cdbca2016-05-17 12:44:20 -0700864 break;
865 }
866 }
867 fWindow->inval();
868 return true;
869}
870
jvanverth34524262016-05-04 13:49:13 -0700871void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700872 static const float kPixelPerMS = 2.0f;
873 static const int kDisplayWidth = 130;
874 static const int kDisplayHeight = 100;
875 static const int kDisplayPadding = 10;
876 static const int kGraphPadding = 3;
877 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
878
Mike Reed3661bc92017-02-22 13:21:42 -0500879 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700880 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
881 SkIntToScalar(kDisplayPadding),
882 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
883 SkPaint paint;
884 canvas->save();
885
djsollen12d62a72016-04-21 07:59:44 -0700886 if (fWindow->supportsContentRect()) {
887 SkRect contentRect = fWindow->getContentRect();
888 canvas->clipRect(contentRect);
889 canvas->translate(contentRect.fLeft, contentRect.fTop);
890 }
891
jvanverth3d6ed3a2016-04-07 11:09:51 -0700892 canvas->clipRect(rect);
893 paint.setColor(SK_ColorBLACK);
894 canvas->drawRect(rect, paint);
895 // draw the 16ms line
896 paint.setColor(SK_ColorLTGRAY);
897 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
898 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
899 paint.setColor(SK_ColorRED);
900 paint.setStyle(SkPaint::kStroke_Style);
901 canvas->drawRect(rect, paint);
902
903 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
904 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700905 int i = fCurrentMeasurement;
906 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500907 // Round to nearest values
908 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
909 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
910 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
911 int startY = SkScalarTruncToInt(rect.fBottom);
912 int endY = startY - flushHeight;
913 paint.setColor(SK_ColorRED);
914 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
915 SkIntToScalar(x), SkIntToScalar(endY), paint);
916 startY = endY;
917 endY = startY - paintHeight;
918 paint.setColor(SK_ColorGREEN);
919 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
920 SkIntToScalar(x), SkIntToScalar(endY), paint);
921 startY = endY;
922 endY = startY - animateHeight;
923 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700924 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
925 SkIntToScalar(x), SkIntToScalar(endY), paint);
926 i++;
927 i &= (kMeasurementCount - 1); // fast mod
928 x += xStep;
929 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700930
931 canvas->restore();
932}
933
Brian Osmana109e392017-02-24 09:49:14 -0500934static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
935 const ImVec2& pos, const ImVec2& size) {
936 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
937 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
938
939 // Invisible 10x10 button
940 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
941 ImGui::InvisibleButton(label, ImVec2(10, 10));
942
943 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
944 ImGuiIO& io = ImGui::GetIO();
945 // Normalized mouse position, relative to our gamut box
946 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
947 // Clamp to edge of box, convert back to primary scale
948 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
949 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
950 }
951
952 if (ImGui::IsItemHovered()) {
953 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
954 }
955
956 // Return screen coordinates for the caller. We could just return center here, but we'd have
957 // one frame of lag during drag.
958 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
959}
960
961static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
962 ImDrawList* drawList = ImGui::GetWindowDrawList();
963
964 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
965 // width, and scale the height to maintain aspect ratio.
966 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
967 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
968 ImVec2 pos = ImGui::GetCursorScreenPos();
969
970 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
971 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
972 // Magic numbers are pixel locations of the origin and upper-right corner.
973 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
974 ImVec2(242, 61), ImVec2(1897, 1922));
975 ImVec2 endPos = ImGui::GetCursorPos();
976
977 // Primary markers
978 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
979 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
980 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
981 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
982
983 // Gamut triangle
984 drawList->AddCircle(r, 5.0f, 0xFF000040);
985 drawList->AddCircle(g, 5.0f, 0xFF004000);
986 drawList->AddCircle(b, 5.0f, 0xFF400000);
987 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
988 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
989
990 // Re-position cursor immediate after the diagram for subsequent controls
991 ImGui::SetCursorPos(endPos);
992}
993
Brian Osman79086b92017-02-10 13:36:16 -0500994void Viewer::drawImGui(SkCanvas* canvas) {
995 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
996 if (fShowImGuiTestWindow) {
997 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
998 }
999
1000 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001001 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1002 // always visible, we can end up in a layout feedback loop.
1003 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001004 DisplayParams params = fWindow->getRequestedDisplayParams();
1005 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001006 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1007 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001008 if (ImGui::CollapsingHeader("Backend")) {
1009 int newBackend = static_cast<int>(fBackendType);
1010 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1011 ImGui::SameLine();
1012 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1013#if defined(SK_VULKAN)
1014 ImGui::SameLine();
1015 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1016#endif
1017 if (newBackend != fBackendType) {
1018 fDeferredActions.push_back([=]() {
1019 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1020 });
1021 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001022
Brian Salomon99a33902017-03-07 15:16:34 -05001023 const GrContext* ctx = fWindow->getGrContext();
1024 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1025 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1026 paramsChanged = true;
1027 }
1028
Brian Osman28b12522017-03-08 17:10:24 -05001029 if (ctx) {
1030 int sampleCount = fWindow->sampleCount();
1031 ImGui::Text("MSAA: "); ImGui::SameLine();
1032 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1033 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1034 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1035 ImGui::RadioButton("16", &sampleCount, 16);
1036
1037 if (sampleCount != params.fMSAASampleCount) {
1038 params.fMSAASampleCount = sampleCount;
1039 paramsChanged = true;
1040 }
1041 }
1042
Brian Osman8a9de3d2017-03-01 14:59:05 -05001043 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001044 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001045 auto prButton = [&](GpuPathRenderers x) {
1046 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001047 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1048 params.fGrContextOptions.fGpuPathRenderers = x;
1049 paramsChanged = true;
1050 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001051 }
1052 };
1053
1054 if (!ctx) {
1055 ImGui::RadioButton("Software", true);
1056 } else if (fWindow->sampleCount()) {
1057 prButton(GpuPathRenderers::kAll);
1058 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1059 prButton(GpuPathRenderers::kStencilAndCover);
1060 }
1061 if (ctx->caps()->sampleShadingSupport()) {
1062 prButton(GpuPathRenderers::kMSAA);
1063 }
1064 prButton(GpuPathRenderers::kTessellating);
1065 prButton(GpuPathRenderers::kDefault);
1066 prButton(GpuPathRenderers::kNone);
1067 } else {
1068 prButton(GpuPathRenderers::kAll);
Jim Van Verth83010462017-03-16 08:45:39 -04001069 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001070 prButton(GpuPathRenderers::kTessellating);
1071 prButton(GpuPathRenderers::kNone);
1072 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001073 ImGui::TreePop();
1074 }
Brian Osman621491e2017-02-28 15:45:01 -05001075 }
1076
Brian Osman79086b92017-02-10 13:36:16 -05001077 if (ImGui::CollapsingHeader("Slide")) {
1078 static ImGuiTextFilter filter;
1079 filter.Draw();
1080 int previousSlide = fCurrentSlide;
1081 fCurrentSlide = 0;
1082 for (auto slide : fSlides) {
1083 if (filter.PassFilter(slide->getName().c_str())) {
1084 ImGui::BulletText("%s", slide->getName().c_str());
1085 if (ImGui::IsItemClicked()) {
1086 setupCurrentSlide(previousSlide);
1087 break;
1088 }
1089 }
1090 ++fCurrentSlide;
1091 }
1092 if (fCurrentSlide >= fSlides.count()) {
1093 fCurrentSlide = previousSlide;
1094 }
1095 }
Brian Osmana109e392017-02-24 09:49:14 -05001096
1097 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001098 ColorMode newMode = fColorMode;
1099 auto cmButton = [&](ColorMode mode, const char* label) {
1100 if (ImGui::RadioButton(label, mode == fColorMode)) {
1101 newMode = mode;
1102 }
1103 };
1104
1105 cmButton(ColorMode::kLegacy, "Legacy 8888");
1106 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1107 "Color Managed 8888 (Nonlinear blending)");
1108 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1109 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1110
1111 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001112 // It isn't safe to switch color mode now (in the middle of painting). We might
1113 // tear down the back-end, etc... Defer this change until the next onIdle.
1114 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001115 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001116 });
Brian Osmana109e392017-02-24 09:49:14 -05001117 }
1118
1119 // Pick from common gamuts:
1120 int primariesIdx = 4; // Default: Custom
1121 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1122 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1123 primariesIdx = i;
1124 break;
1125 }
1126 }
1127
1128 if (ImGui::Combo("Primaries", &primariesIdx,
1129 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1130 if (primariesIdx >= 0 && primariesIdx <= 3) {
1131 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1132 }
1133 }
1134
1135 // Allow direct editing of gamut
1136 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1137 }
Brian Osman79086b92017-02-10 13:36:16 -05001138 }
Brian Salomon99a33902017-03-07 15:16:34 -05001139 if (paramsChanged) {
1140 fDeferredActions.push_back([=]() {
1141 fWindow->setRequestedDisplayParams(params);
1142 fWindow->inval();
1143 this->updateTitle();
1144 });
1145 }
Brian Osman79086b92017-02-10 13:36:16 -05001146 ImGui::End();
1147 }
1148
Brian Osmanf6877092017-02-13 09:39:57 -05001149 SkPaint zoomImagePaint;
1150 if (fShowZoomWindow && fLastImage) {
1151 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1152 static int zoomFactor = 4;
1153 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1154
1155 zoomImagePaint.setShader(fLastImage->makeShader(SkShader::kClamp_TileMode,
1156 SkShader::kClamp_TileMode));
1157 zoomImagePaint.setColor(SK_ColorWHITE);
1158
1159 // Zoom by shrinking the corner UVs towards the mouse cursor
1160 ImVec2 mousePos = ImGui::GetMousePos();
1161 ImVec2 avail = ImGui::GetContentRegionAvail();
1162
1163 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1164 (avail.y * 0.5f) / zoomFactor);
1165 ImGui::Image(&zoomImagePaint, avail,
1166 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1167 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1168 }
1169
1170 ImGui::End();
1171 }
1172
Brian Osman79086b92017-02-10 13:36:16 -05001173 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1174 // (widgets, etc...) that have been issued
1175 ImGui::Render();
1176
1177 // Then we fetch the most recent data, and convert it so we can render with Skia
1178 const ImDrawData* drawData = ImGui::GetDrawData();
1179 SkTDArray<SkPoint> pos;
1180 SkTDArray<SkPoint> uv;
1181 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001182
1183 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1184 const ImDrawList* drawList = drawData->CmdLists[i];
1185
1186 // De-interleave all vertex data (sigh), convert to Skia types
1187 pos.rewind(); uv.rewind(); color.rewind();
1188 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1189 const ImDrawVert& vert = drawList->VtxBuffer[i];
1190 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1191 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1192 color.push(vert.col);
1193 }
1194 // ImGui colors are RGBA
1195 SkSwapRB(color.begin(), color.begin(), color.count());
1196
1197 int indexOffset = 0;
1198
1199 // Draw everything with canvas.drawVertices...
1200 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1201 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1202
1203 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1204 if (drawCmd->UserCallback) {
1205 drawCmd->UserCallback(drawList, drawCmd);
1206 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001207 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1208 SkASSERT(paint);
1209
Brian Osman79086b92017-02-10 13:36:16 -05001210 canvas->save();
1211 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1212 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001213 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1214 drawList->VtxBuffer.size(), pos.begin(),
1215 uv.begin(), color.begin(),
1216 drawCmd->ElemCount,
1217 drawList->IdxBuffer.begin() + indexOffset),
1218 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001219 indexOffset += drawCmd->ElemCount;
1220 canvas->restore();
1221 }
1222 }
1223 }
1224}
1225
liyuqian2edb0f42016-07-06 14:11:32 -07001226void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001227 for (int i = 0; i < fDeferredActions.count(); ++i) {
1228 fDeferredActions[i]();
1229 }
1230 fDeferredActions.reset();
1231
Brian Osman1df161a2017-02-09 12:10:20 -05001232 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001233 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001234 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1235 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1236
Brian Osman79086b92017-02-10 13:36:16 -05001237 ImGuiIO& io = ImGui::GetIO();
1238 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001239 fWindow->inval();
1240 }
jvanverth9f372462016-04-06 06:08:59 -07001241}
liyuqiane5a6cd92016-05-27 08:52:52 -07001242
1243void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001244 if (!fWindow) {
1245 return;
1246 }
1247 if (fWindow->sampleCount() < 0) {
1248 return; // Surface hasn't been created yet.
1249 }
1250
liyuqianb73c24b2016-06-03 08:47:23 -07001251 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001252 Json::Value slideState(Json::objectValue);
1253 slideState[kName] = kSlideStateName;
1254 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001255 if (fAllSlideNames.size() == 0) {
1256 for(auto slide : fSlides) {
1257 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1258 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001259 }
liyuqian1f508fd2016-06-07 06:57:40 -07001260 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001261
liyuqianb73c24b2016-06-03 08:47:23 -07001262 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001263 Json::Value backendState(Json::objectValue);
1264 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001265 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001266 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001267 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001268 backendState[kOptions].append(Json::Value(str));
1269 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001270
csmartdalton578f0642017-02-24 16:04:47 -07001271 // MSAA state
1272 Json::Value msaaState(Json::objectValue);
1273 msaaState[kName] = kMSAAStateName;
1274 msaaState[kValue] = fWindow->sampleCount();
1275 msaaState[kOptions] = Json::Value(Json::arrayValue);
1276 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1277 msaaState[kOptions].append(Json::Value(0));
1278 } else {
1279 for (int msaa : {0, 4, 8, 16}) {
1280 msaaState[kOptions].append(Json::Value(msaa));
1281 }
1282 }
1283
csmartdalton61cd31a2017-02-27 17:00:53 -07001284 // Path renderer state
1285 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1286 Json::Value prState(Json::objectValue);
1287 prState[kName] = kPathRendererStateName;
1288 prState[kValue] = gPathRendererNames[pr];
1289 prState[kOptions] = Json::Value(Json::arrayValue);
1290 const GrContext* ctx = fWindow->getGrContext();
1291 if (!ctx) {
1292 prState[kOptions].append("Software");
1293 } else if (fWindow->sampleCount()) {
1294 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1295 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1296 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1297 }
1298 if (ctx->caps()->sampleShadingSupport()) {
1299 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1300 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001301 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001302 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1303 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1304 } else {
1305 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Jim Van Verth83010462017-03-16 08:45:39 -04001306 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001307 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001308 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1309 }
1310
Brian Salomon99a33902017-03-07 15:16:34 -05001311 // Instanced rendering state
1312 Json::Value instState(Json::objectValue);
1313 instState[kName] = kInstancedRenderingStateName;
1314 if (ctx) {
1315 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1316 instState[kValue] = kON;
1317 } else {
1318 instState[kValue] = kOFF;
1319 }
1320 instState[kOptions] = Json::Value(Json::arrayValue);
1321 instState[kOptions].append(kOFF);
1322 instState[kOptions].append(kON);
1323 }
1324
liyuqianb73c24b2016-06-03 08:47:23 -07001325 // Softkey state
1326 Json::Value softkeyState(Json::objectValue);
1327 softkeyState[kName] = kSoftkeyStateName;
1328 softkeyState[kValue] = kSoftkeyHint;
1329 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1330 softkeyState[kOptions].append(kSoftkeyHint);
1331 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1332 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1333 }
1334
liyuqian1f508fd2016-06-07 06:57:40 -07001335 // FPS state
1336 Json::Value fpsState(Json::objectValue);
1337 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001338 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1339 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1340 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1341 fAnimateTimes[idx],
1342 fPaintTimes[idx],
1343 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001344 fpsState[kOptions] = Json::Value(Json::arrayValue);
1345
liyuqiane5a6cd92016-05-27 08:52:52 -07001346 Json::Value state(Json::arrayValue);
1347 state.append(slideState);
1348 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001349 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001350 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001351 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001352 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001353 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001354
1355 fWindow->setUIState(state);
1356}
1357
1358void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001359 // For those who will add more features to handle the state change in this function:
1360 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1361 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1362 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001363 if (stateName.equals(kSlideStateName)) {
1364 int previousSlide = fCurrentSlide;
1365 fCurrentSlide = 0;
1366 for(auto slide : fSlides) {
1367 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001368 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001369 break;
1370 }
1371 fCurrentSlide++;
1372 }
1373 if (fCurrentSlide >= fSlides.count()) {
1374 fCurrentSlide = previousSlide;
1375 SkDebugf("Slide not found: %s", stateValue.c_str());
1376 }
liyuqian6cb70252016-06-02 12:16:25 -07001377 } else if (stateName.equals(kBackendStateName)) {
1378 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1379 if (stateValue.equals(kBackendTypeStrings[i])) {
1380 if (fBackendType != i) {
1381 fBackendType = (sk_app::Window::BackendType)i;
1382 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001383 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001384 }
1385 break;
1386 }
1387 }
csmartdalton578f0642017-02-24 16:04:47 -07001388 } else if (stateName.equals(kMSAAStateName)) {
1389 DisplayParams params = fWindow->getRequestedDisplayParams();
1390 int sampleCount = atoi(stateValue.c_str());
1391 if (sampleCount != params.fMSAASampleCount) {
1392 params.fMSAASampleCount = sampleCount;
1393 fWindow->setRequestedDisplayParams(params);
1394 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001395 this->updateTitle();
1396 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001397 }
1398 } else if (stateName.equals(kPathRendererStateName)) {
1399 DisplayParams params = fWindow->getRequestedDisplayParams();
1400 for (const auto& pair : gPathRendererNames) {
1401 if (pair.second == stateValue.c_str()) {
1402 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1403 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1404 fWindow->setRequestedDisplayParams(params);
1405 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001406 this->updateTitle();
1407 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001408 }
1409 break;
1410 }
csmartdalton578f0642017-02-24 16:04:47 -07001411 }
Brian Salomon99a33902017-03-07 15:16:34 -05001412 } else if (stateName.equals(kInstancedRenderingStateName)) {
1413 DisplayParams params = fWindow->getRequestedDisplayParams();
1414 bool value = !strcmp(stateValue.c_str(), kON);
1415 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1416 params.fGrContextOptions.fEnableInstancedRendering = value;
1417 fWindow->setRequestedDisplayParams(params);
1418 fWindow->inval();
1419 this->updateTitle();
1420 this->updateUIState();
1421 }
liyuqianb73c24b2016-06-03 08:47:23 -07001422 } else if (stateName.equals(kSoftkeyStateName)) {
1423 if (!stateValue.equals(kSoftkeyHint)) {
1424 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001425 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001426 }
liyuqian2edb0f42016-07-06 14:11:32 -07001427 } else if (stateName.equals(kRefreshStateName)) {
1428 // This state is actually NOT in the UI state.
1429 // We use this to allow Android to quickly set bool fRefresh.
1430 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001431 } else {
1432 SkDebugf("Unknown stateName: %s", stateName.c_str());
1433 }
1434}
Brian Osman79086b92017-02-10 13:36:16 -05001435
1436bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1437 return fCommands.onKey(key, state, modifiers);
1438}
1439
1440bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001441 if (fSlides[fCurrentSlide]->onChar(c)) {
1442 fWindow->inval();
1443 return true;
1444 }
1445
Brian Osman79086b92017-02-10 13:36:16 -05001446 return fCommands.onChar(c, modifiers);
1447}