Debian Codegraph @

tools/viewer/SkSLSlide.cpp

raw
1 /*
2 * Copyright 2019 Google LLC
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
8 #include "tools/viewer/SkSLSlide.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkClipOp.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkFont.h"
15 #include "include/core/SkFontTypes.h"
16 #include "include/core/SkImage.h"
17 #include "include/core/SkPaint.h"
18 #include "include/core/SkPoint.h"
19 #include "include/core/SkRect.h"
20 #include "include/core/SkSamplingOptions.h"
21 #include "include/core/SkStream.h"
22 #include "include/core/SkTileMode.h"
23 #include "include/effects/SkGradient.h"
24 #include "include/private/base/SkAssert.h"
25 #include "include/private/base/SkSpan_impl.h"
26 #include "include/sksl/SkSLDebugTrace.h"
27 #include "src/sksl/tracing/SkSLDebugTracePriv.h"
28 #include "tools/DecodeUtils.h"
29 #include "tools/Resources.h"
30 #include "tools/fonts/FontToolUtils.h"
31 #include "tools/sk_app/Application.h"
32 #include "tools/sksltrace/SkSLTraceUtils.h"
33 #include "tools/viewer/Viewer.h"
34
35 #include <algorithm>
36 #include <cmath>
37 #include <cstdio>
38 #include <cstring>
39 #include <string>
40 #include <string_view>
41
42 #include "imgui.h"
43
44 using namespace sk_app;
45
46 ///////////////////////////////////////////////////////////////////////////////
47
48 static int InputTextCallback(ImGuiInputTextCallbackData* data) {
49 if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
50 SkString* s = (SkString*)data->UserData;
51 SkASSERT(data->Buf == s->data());
52 SkString tmp(data->Buf, data->BufTextLen);
53 s->swap(tmp);
54 data->Buf = s->data();
55 }
56 return 0;
57 }
58
59 SkSLSlide::SkSLSlide() {
60 // Register types for serialization
61 fName = "SkSL";
62
63 fSkSL =
64
65 "uniform shader child;\n"
66 "\n"
67 "half4 main(float2 p) {\n"
68 " return child.eval(p);\n"
69 "}\n";
70
71 fCodeIsDirty = true;
72 }
73
74 void SkSLSlide::load(SkScalar winWidth, SkScalar winHeight) {
75 const SkPoint points[] = { { 0, 0 }, { 256, 0 } };
76 const SkColor4f colors[] = { SkColors::kRed, SkColors::kGreen };
77 const SkGradient grad = {{colors, {}, SkTileMode::kClamp}, {}};
78
79 sk_sp<SkShader> shader;
80
81 fShaders.push_back(std::make_pair("Null", nullptr));
82
83 shader = SkShaders::LinearGradient(points, grad);
84 fShaders.push_back(std::make_pair("Linear Gradient", shader));
85
86 shader = SkShaders::RadialGradient({ 256, 256 }, 256, grad);
87 fShaders.push_back(std::make_pair("Radial Gradient", shader));
88
89 shader = SkShaders::SweepGradient({256, 256}, grad);
90 fShaders.push_back(std::make_pair("Sweep Gradient", shader));
91
92 shader = ToolUtils::GetResourceAsImage("images/mandrill_256.png")
93 ->makeShader(SkSamplingOptions());
94 fShaders.push_back(std::make_pair("Mandrill", shader));
95
96 fResolution = { winWidth, winHeight, 1.0f };
97 }
98
99 void SkSLSlide::unload() {
100 fEffect.reset();
101 fInputs.reset();
102 fChildren.clear();
103 fShaders.clear();
104 }
105
106 bool SkSLSlide::rebuild() {
107 // Some of the standard shadertoy inputs:
108 SkString sksl;
109 // TODO(skbug.com/40042585): This interferes with user-authored #version directives
110 if (fShadertoyUniforms) {
111 sksl = "uniform float3 iResolution;\n"
112 "uniform float iTime;\n"
113 "uniform float4 iMouse;\n";
114 }
115 sksl.append(fSkSL);
116
117 // It shouldn't happen, but it's possible to assert in the compiler, especially mid-edit.
118 // To guard against losing your work, write out the shader to a backup file, then remove it
119 // when we compile successfully.
120 constexpr char kBackupFile[] = "sksl.bak";
121 FILE* backup = fopen(kBackupFile, "w");
122 if (backup) {
123 fwrite(fSkSL.c_str(), 1, fSkSL.size(), backup);
124 fclose(backup);
125 }
126 auto [effect, errorText] = SkRuntimeEffect::MakeForShader(sksl);
127 if (backup) {
128 std::remove(kBackupFile);
129 }
130
131 if (!effect) {
132 #if defined(SK_GANESH)
133 Viewer::ShaderErrorHandler()->compileError(sksl.c_str(), errorText.c_str());
134 #endif
135 return false;
136 }
137
138 size_t oldSize = fEffect ? fEffect->uniformSize() : 0;
139 fInputs.realloc(effect->uniformSize());
140 if (effect->uniformSize() > oldSize) {
141 memset(fInputs.get() + oldSize, 0, effect->uniformSize() - oldSize);
142 }
143 fChildren.resize_back(effect->children().size());
144
145 fEffect = effect;
146 fCodeIsDirty = false;
147 return true;
148 }
149
150 void SkSLSlide::draw(SkCanvas* canvas) {
151 canvas->clear(SK_ColorWHITE);
152
153 ImGui::Begin("SkSL", nullptr, ImGuiWindowFlags_AlwaysVerticalScrollbar);
154
155 // Edit box for shader code
156 ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackResize;
157 ImVec2 boxSize(-1.0f, ImGui::GetTextLineHeight() * 30);
158 if (ImGui::InputTextMultiline("Code", fSkSL.data(), fSkSL.size() + 1, boxSize, flags,
159 InputTextCallback, &fSkSL)) {
160 fCodeIsDirty = true;
161 }
162
163 if (ImGui::Checkbox("ShaderToy Uniforms (iResolution/iTime/iMouse)", &fShadertoyUniforms)) {
164 fCodeIsDirty = true;
165 }
166
167 if (fCodeIsDirty || !fEffect) {
168 this->rebuild();
169 }
170
171 if (!fEffect) {
172 ImGui::End();
173 return;
174 }
175
176 bool writeTrace = false;
177 bool writeDump = false;
178 if (!canvas->recordingContext()) {
179 ImGui::InputInt2("Trace Coordinate (X/Y)", fTraceCoord);
180 writeTrace = ImGui::Button("Write Debug Trace (JSON)");
181 writeDump = ImGui::Button("Write Debug Dump (Human-Readable)");
182 }
183
184 // Update fMousePos
185 ImVec2 mousePos = ImGui::GetMousePos();
186 if (ImGui::IsMouseDown(0)) {
187 fMousePos.x = mousePos.x;
188 fMousePos.y = mousePos.y;
189 }
190 if (ImGui::IsMouseClicked(0)) {
191 fMousePos.z = mousePos.x;
192 fMousePos.w = mousePos.y;
193 }
194 fMousePos.z = std::abs(fMousePos.z) * (ImGui::IsMouseDown(0) ? 1 : -1);
195 fMousePos.w = std::abs(fMousePos.w) * (ImGui::IsMouseClicked(0) ? 1 : -1);
196
197 for (const SkRuntimeEffect::Uniform& v : fEffect->uniforms()) {
198 char* data = fInputs.get() + v.offset;
199 if (v.name == "iResolution") {
200 memcpy(data, &fResolution, sizeof(fResolution));
201 continue;
202 }
203 if (v.name == "iTime") {
204 memcpy(data, &fSeconds, sizeof(fSeconds));
205 continue;
206 }
207 if (v.name == "iMouse") {
208 memcpy(data, &fMousePos, sizeof(fMousePos));
209 continue;
210 }
211 switch (v.type) {
212 case SkRuntimeEffect::Uniform::Type::kFloat:
213 case SkRuntimeEffect::Uniform::Type::kFloat2:
214 case SkRuntimeEffect::Uniform::Type::kFloat3:
215 case SkRuntimeEffect::Uniform::Type::kFloat4: {
216 int rows = ((int)v.type - (int)SkRuntimeEffect::Uniform::Type::kFloat) + 1;
217 float* f = reinterpret_cast<float*>(data);
218 for (int c = 0; c < v.count; ++c, f += rows) {
219 SkString name = v.isArray()
220 ? SkStringPrintf("%.*s[%d]", (int)v.name.size(), v.name.data(), c)
221 : SkString(v.name);
222 ImGui::PushID(c);
223 ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
224 ImGui::PopID();
225 }
226 break;
227 }
228 case SkRuntimeEffect::Uniform::Type::kFloat2x2:
229 case SkRuntimeEffect::Uniform::Type::kFloat3x3:
230 case SkRuntimeEffect::Uniform::Type::kFloat4x4: {
231 int rows = ((int)v.type - (int)SkRuntimeEffect::Uniform::Type::kFloat2x2) + 2;
232 int cols = rows;
233 float* f = reinterpret_cast<float*>(data);
234 for (int e = 0; e < v.count; ++e) {
235 for (int c = 0; c < cols; ++c, f += rows) {
236 SkString name = v.isArray()
237 ? SkStringPrintf("%.*s[%d][%d]", (int)v.name.size(), v.name.data(), e, c)
238 : SkStringPrintf("%.*s[%d]", (int)v.name.size(), v.name.data(), c);
239 ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
240 }
241 }
242 break;
243 }
244 case SkRuntimeEffect::Uniform::Type::kInt:
245 case SkRuntimeEffect::Uniform::Type::kInt2:
246 case SkRuntimeEffect::Uniform::Type::kInt3:
247 case SkRuntimeEffect::Uniform::Type::kInt4: {
248 int rows = ((int)v.type - (int)SkRuntimeEffect::Uniform::Type::kInt) + 1;
249 int* i = reinterpret_cast<int*>(data);
250 for (int c = 0; c < v.count; ++c, i += rows) {
251 SkString name = v.isArray()
252 ? SkStringPrintf("%.*s[%d]", (int)v.name.size(), v.name.data(), c)
253 : SkString(v.name);
254 ImGui::PushID(c);
255 ImGui::DragScalarN(name.c_str(), ImGuiDataType_S32, i, rows, 1.0f);
256 ImGui::PopID();
257 }
258 break;
259 }
260 }
261 }
262
263 for (const SkRuntimeEffect::Child& c : fEffect->children()) {
264 auto curShader = std::find_if(
265 fShaders.begin(),
266 fShaders.end(),
267 [tgt = fChildren[c.index]](const std::pair<const char*, sk_sp<SkShader>>& p) {
268 return p.second == tgt;
269 });
270 SkASSERT(curShader != fShaders.end());
271
272 if (ImGui::BeginCombo(std::string(c.name).c_str(), curShader->first)) {
273 for (const auto& namedShader : fShaders) {
274 if (ImGui::Selectable(namedShader.first, curShader->second == namedShader.second)) {
275 fChildren[c.index] = namedShader.second;
276 }
277 }
278 ImGui::EndCombo();
279 }
280 }
281
282 static SkColor4f gPaintColor { 1.0f, 1.0f, 1.0f , 1.0f };
283 ImGui::ColorEdit4("Paint Color", gPaintColor.vec());
284
285 ImGui::RadioButton("Fill", &fGeometry, kFill); ImGui::SameLine();
286 ImGui::RadioButton("Circle", &fGeometry, kCircle); ImGui::SameLine();
287 ImGui::RadioButton("RoundRect", &fGeometry, kRoundRect); ImGui::SameLine();
288 ImGui::RadioButton("Capsule", &fGeometry, kCapsule); ImGui::SameLine();
289 ImGui::RadioButton("Text", &fGeometry, kText);
290
291 ImGui::End();
292
293 auto inputs = SkData::MakeWithoutCopy(fInputs.get(), fEffect->uniformSize());
294
295 canvas->save();
296
297 sk_sp<SkSL::DebugTrace> debugTrace;
298 auto shader = fEffect->makeShader(std::move(inputs), fChildren.data(), fChildren.size());
299 if (writeTrace || writeDump) {
300 SkIPoint traceCoord = {fTraceCoord[0], fTraceCoord[1]};
301 SkRuntimeEffect::TracedShader traced = SkRuntimeEffect::MakeTraced(std::move(shader),
302 traceCoord);
303 shader = std::move(traced.shader);
304 debugTrace = std::move(traced.debugTrace);
305
306 // Reduce debug trace delay by clipping to a 4x4 rectangle for this paint, centered on the
307 // pixel to trace. A minor complication is that the canvas might have a transform applied to
308 // it, but we want to clip in device space. This can be worked around by resetting the
309 // canvas matrix temporarily.
310 SkM44 canvasMatrix = canvas->getLocalToDevice();
311 canvas->resetMatrix();
312 auto r = SkRect::MakeXYWH(fTraceCoord[0] - 1, fTraceCoord[1] - 1, 4, 4);
313 canvas->clipRect(r, SkClipOp::kIntersect);
314 canvas->setMatrix(canvasMatrix);
315 }
316 SkPaint p;
317 p.setColor4f(gPaintColor);
318 p.setShader(std::move(shader));
319
320 switch (fGeometry) {
321 case kFill:
322 canvas->drawPaint(p);
323 break;
324 case kCircle:
325 canvas->drawCircle({ 256, 256 }, 256, p);
326 break;
327 case kRoundRect:
328 canvas->drawRoundRect({ 0, 0, 512, 512 }, 64, 64, p);
329 break;
330 case kCapsule:
331 canvas->drawRoundRect({ 0, 224, 512, 288 }, 32, 32, p);
332 break;
333 case kText: {
334 SkFont font = ToolUtils::DefaultFont();
335 font.setSize(SkIntToScalar(96));
336 canvas->drawSimpleText("Hello World", strlen("Hello World"), SkTextEncoding::kUTF8, 0,
337 256, font, p);
338 } break;
339 default: break;
340 }
341
342 canvas->restore();
343
344 if (debugTrace && writeTrace) {
345 SkFILEWStream traceFile("SkSLDebugTrace.json");
346 SkSLTraceUtils::WriteTrace(static_cast<const SkSL::DebugTracePriv&>(*debugTrace), &traceFile);
347 }
348 if (debugTrace && writeDump) {
349 SkFILEWStream dumpFile("SkSLDebugTrace.dump.txt");
350 debugTrace->dump(&dumpFile);
351 }
352 }
353
354 bool SkSLSlide::animate(double nanos) {
355 fSeconds = static_cast<float>(nanos * 1E-9);
356 return true;
357 }