blob: 12bb282a74c115fc34a7c7786555da76a7f8c09a [file] [log] [blame]
csmartdaltoned4984b2017-02-13 14:57:28 -07001/*
2 * Copyright 2017 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
8#include "SampleCode.h"
9#include "SkAnimTimer.h"
10#include "SkCanvas.h"
11#include "SkGlyphCache.h"
12#include "SkPaint.h"
13#include "SkPath.h"
14#include "SkRandom.h"
15#include "SkTaskGroup.h"
Chris Dalton7c02cc72017-11-06 14:10:54 -070016#include "sk_tool_utils.h"
csmartdaltoned4984b2017-02-13 14:57:28 -070017
18////////////////////////////////////////////////////////////////////////////////////////////////////
19// Static text from paths.
20class PathText : public SampleView {
21public:
22 constexpr static int kNumPaths = 1500;
23 virtual const char* getName() const { return "PathText"; }
24
Chris Dalton7c02cc72017-11-06 14:10:54 -070025 PathText() {
csmartdaltoned4984b2017-02-13 14:57:28 -070026 SkPaint defaultPaint;
27 SkAutoGlyphCache agc(defaultPaint, nullptr, &SkMatrix::I());
28 SkGlyphCache* cache = agc.getCache();
29 SkPath glyphPaths[52];
30 for (int i = 0; i < 52; ++i) {
31 // I and l are rects on OS X ...
32 char c = "aQCDEFGH7JKLMNOPBRZTUVWXYSAbcdefghijk1mnopqrstuvwxyz"[i];
33 SkGlyphID id = cache->unicharToGlyph(c);
34 cache->getScalerContext()->getPath(SkPackedGlyphID(id), &glyphPaths[i]);
35 }
36
37 for (int i = 0; i < kNumPaths; ++i) {
38 const SkPath& p = glyphPaths[i % 52];
39 fGlyphs[i].init(fRand, p);
40 }
41 }
42
43 virtual void reset() {
44 for (Glyph& glyph : fGlyphs) {
45 glyph.reset(fRand, this->width(), this->height());
46 }
47 }
48
49 void onOnceBeforeDraw() final { this->INHERITED::onOnceBeforeDraw(); this->reset(); }
50 void onSizeChange() final { this->INHERITED::onSizeChange(); this->reset(); }
51
52 bool onQuery(SkEvent* evt) final {
53 if (SampleCode::TitleQ(*evt)) {
54 SampleCode::TitleR(evt, this->getName());
55 return true;
56 }
Chris Dalton7c02cc72017-11-06 14:10:54 -070057 SkUnichar unichar;
58 if (SampleCode::CharQ(*evt, &unichar)) {
59 if (unichar == 'X') {
60 fDoClip = !fDoClip;
61 this->inval(nullptr);
62 return true;
63 }
64 }
csmartdaltoned4984b2017-02-13 14:57:28 -070065 return this->INHERITED::onQuery(evt);
66 }
67
68 void onDrawContent(SkCanvas* canvas) override {
Chris Dalton7c02cc72017-11-06 14:10:54 -070069 if (fDoClip) {
70 SkMatrix oldMatrix = canvas->getTotalMatrix();
71 canvas->setMatrix(SkMatrix::MakeScale(this->width(), this->height()));
72 canvas->save();
73 canvas->clipPath(fClipPath, SkClipOp::kDifference, true);
74 canvas->clear(SK_ColorBLACK);
75 canvas->restore();
76 canvas->clipPath(fClipPath, SkClipOp::kIntersect, true);
77 canvas->setMatrix(oldMatrix);
78 }
79 this->drawGlyphs(canvas);
80 }
81
82 virtual void drawGlyphs(SkCanvas* canvas) {
csmartdaltoned4984b2017-02-13 14:57:28 -070083 for (Glyph& glyph : fGlyphs) {
84 SkAutoCanvasRestore acr(canvas, true);
85 canvas->translate(glyph.fPosition.x(), glyph.fPosition.y());
86 canvas->scale(glyph.fZoom, glyph.fZoom);
87 canvas->rotate(glyph.fSpin);
88 canvas->translate(-glyph.fMidpt.x(), -glyph.fMidpt.y());
89 canvas->drawPath(glyph.fPath, glyph.fPaint);
90 }
91 }
92
93protected:
94 struct Glyph {
95 void init(SkRandom& rand, const SkPath& path);
96 void reset(SkRandom& rand, int w, int h);
97
98 SkPath fPath;
99 SkPaint fPaint;
100 SkPoint fPosition;
101 SkScalar fZoom;
102 SkScalar fSpin;
103 SkPoint fMidpt;
104 };
105
106 Glyph fGlyphs[kNumPaths];
Chris Dalton7c02cc72017-11-06 14:10:54 -0700107 SkRandom fRand{25};
108 SkPath fClipPath = sk_tool_utils::make_star(SkRect{0,0,1,1}, 11, 3);
109 bool fDoClip = false;
csmartdaltoned4984b2017-02-13 14:57:28 -0700110
111 typedef SampleView INHERITED;
112};
113
114void PathText::Glyph::init(SkRandom& rand, const SkPath& path) {
115 fPath = path;
116 fPaint.setAntiAlias(true);
117 fPaint.setColor(rand.nextU() | 0x80808080);
118}
119
120void PathText::Glyph::reset(SkRandom& rand, int w, int h) {
121 int screensize = SkTMax(w, h);
122 const SkRect& bounds = fPath.getBounds();
123 SkScalar t;
124
125 fPosition = {rand.nextF() * w, rand.nextF() * h};
126 t = pow(rand.nextF(), 100);
127 fZoom = ((1 - t) * screensize / 50 + t * screensize / 3) /
128 SkTMax(bounds.width(), bounds.height());
129 fSpin = rand.nextF() * 360;
130 fMidpt = {bounds.centerX(), bounds.centerY()};
131}
132
133////////////////////////////////////////////////////////////////////////////////////////////////////
134// Text from paths with animated transformation matrices.
135class MovingPathText : public PathText {
136public:
137 const char* getName() const override { return "MovingPathText"; }
138
139 MovingPathText()
140 : fFrontMatrices(kNumPaths)
141 , fBackMatrices(kNumPaths) {
142 }
143
Brian Salomond3b65972017-03-22 12:05:03 -0400144 ~MovingPathText() override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700145 fBackgroundAnimationTask.wait();
146 }
147
148 void reset() override {
149 const SkScalar screensize = static_cast<SkScalar>(SkTMax(this->width(), this->height()));
150 this->INHERITED::reset();
151
152 for (auto& v : fVelocities) {
153 for (SkScalar* d : {&v.fDx, &v.fDy}) {
154 SkScalar t = pow(fRand.nextF(), 3);
155 *d = ((1 - t) / 60 + t / 10) * (fRand.nextBool() ? screensize : -screensize);
156 }
157
158 SkScalar t = pow(fRand.nextF(), 25);
159 v.fDSpin = ((1 - t) * 360 / 7.5 + t * 360 / 1.5) * (fRand.nextBool() ? 1 : -1);
160 }
161
162 // Get valid front data.
163 fBackgroundAnimationTask.wait();
164 this->runAnimationTask(0, 0, this->width(), this->height());
165 memcpy(fFrontMatrices, fBackMatrices, kNumPaths * sizeof(SkMatrix));
166 fLastTick = 0;
167 }
168
169 bool onAnimate(const SkAnimTimer& timer) final {
170 fBackgroundAnimationTask.wait();
171 this->swapAnimationBuffers();
172
173 const double tsec = timer.secs();
174 const double dt = fLastTick ? (timer.secs() - fLastTick) : 0;
175 fBackgroundAnimationTask.add(std::bind(&MovingPathText::runAnimationTask, this, tsec,
176 dt, this->width(), this->height()));
177 fLastTick = timer.secs();
178 return true;
179 }
180
181 /**
182 * Called on a background thread. Here we can only modify fBackMatrices.
183 */
184 virtual void runAnimationTask(double t, double dt, int w, int h) {
185 for (int idx = 0; idx < kNumPaths; ++idx) {
186 Velocity* v = &fVelocities[idx];
187 Glyph* glyph = &fGlyphs[idx];
188 SkMatrix* backMatrix = &fBackMatrices[idx];
189
190 glyph->fPosition.fX += v->fDx * dt;
191 if (glyph->fPosition.x() < 0) {
192 glyph->fPosition.fX -= 2 * glyph->fPosition.x();
193 v->fDx = -v->fDx;
194 } else if (glyph->fPosition.x() > w) {
195 glyph->fPosition.fX -= 2 * (glyph->fPosition.x() - w);
196 v->fDx = -v->fDx;
197 }
198
199 glyph->fPosition.fY += v->fDy * dt;
200 if (glyph->fPosition.y() < 0) {
201 glyph->fPosition.fY -= 2 * glyph->fPosition.y();
202 v->fDy = -v->fDy;
203 } else if (glyph->fPosition.y() > h) {
204 glyph->fPosition.fY -= 2 * (glyph->fPosition.y() - h);
205 v->fDy = -v->fDy;
206 }
207
208 glyph->fSpin += v->fDSpin * dt;
209
210 backMatrix->setTranslate(glyph->fPosition.x(), glyph->fPosition.y());
211 backMatrix->preScale(glyph->fZoom, glyph->fZoom);
212 backMatrix->preRotate(glyph->fSpin);
213 backMatrix->preTranslate(-glyph->fMidpt.x(), -glyph->fMidpt.y());
214 }
215 }
216
217 virtual void swapAnimationBuffers() {
218 std::swap(fFrontMatrices, fBackMatrices);
219 }
220
Chris Dalton7c02cc72017-11-06 14:10:54 -0700221 void drawGlyphs(SkCanvas* canvas) override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700222 for (int i = 0; i < kNumPaths; ++i) {
223 SkAutoCanvasRestore acr(canvas, true);
224 canvas->concat(fFrontMatrices[i]);
225 canvas->drawPath(fGlyphs[i].fPath, fGlyphs[i].fPaint);
226 }
227 }
228
229protected:
230 struct Velocity {
231 SkScalar fDx, fDy;
232 SkScalar fDSpin;
233 };
234
235 Velocity fVelocities[kNumPaths];
236 SkAutoTMalloc<SkMatrix> fFrontMatrices;
237 SkAutoTMalloc<SkMatrix> fBackMatrices;
238 SkTaskGroup fBackgroundAnimationTask;
239 double fLastTick;
240
241 typedef PathText INHERITED;
242};
243
244
245////////////////////////////////////////////////////////////////////////////////////////////////////
246// Text from paths with animated control points.
247class WavyPathText : public MovingPathText {
248public:
249 const char* getName() const override { return "WavyPathText"; }
250
251 WavyPathText()
252 : fFrontPaths(kNumPaths)
253 , fBackPaths(kNumPaths) {}
254
Brian Salomond3b65972017-03-22 12:05:03 -0400255 ~WavyPathText() override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700256 fBackgroundAnimationTask.wait();
257 }
258
259 void reset() override {
260 fWaves.reset(fRand, this->width(), this->height());
261 this->INHERITED::reset();
262 std::copy(fBackPaths.get(), fBackPaths.get() + kNumPaths, fFrontPaths.get());
263 }
264
265 /**
266 * Called on a background thread. Here we can only modify fBackPaths.
267 */
268 void runAnimationTask(double t, double dt, int w, int h) override {
269 const float tsec = static_cast<float>(t);
270 this->INHERITED::runAnimationTask(t, 0.5 * dt, w, h);
271
272 for (int i = 0; i < kNumPaths; ++i) {
273 const Glyph& glyph = fGlyphs[i];
274 const SkMatrix& backMatrix = fBackMatrices[i];
275
276 const Sk2f matrix[3] = {
277 Sk2f(backMatrix.getScaleX(), backMatrix.getSkewY()),
278 Sk2f(backMatrix.getSkewX(), backMatrix.getScaleY()),
279 Sk2f(backMatrix.getTranslateX(), backMatrix.getTranslateY())
280 };
281
282 SkPath* backpath = &fBackPaths[i];
283 backpath->reset();
284 backpath->setFillType(SkPath::kEvenOdd_FillType);
285
286 SkPath::RawIter iter(glyph.fPath);
287 SkPath::Verb verb;
288 SkPoint pts[4];
289
290 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
291 switch (verb) {
292 case SkPath::kMove_Verb: {
293 SkPoint pt = fWaves.apply(tsec, matrix, pts[0]);
294 backpath->moveTo(pt.x(), pt.y());
295 break;
296 }
297 case SkPath::kLine_Verb: {
298 SkPoint endpt = fWaves.apply(tsec, matrix, pts[1]);
299 backpath->lineTo(endpt.x(), endpt.y());
300 break;
301 }
302 case SkPath::kQuad_Verb: {
303 SkPoint controlPt = fWaves.apply(tsec, matrix, pts[1]);
304 SkPoint endpt = fWaves.apply(tsec, matrix, pts[2]);
305 backpath->quadTo(controlPt.x(), controlPt.y(), endpt.x(), endpt.y());
306 break;
307 }
308 case SkPath::kClose_Verb: {
309 backpath->close();
310 break;
311 }
312 case SkPath::kCubic_Verb:
313 case SkPath::kConic_Verb:
314 case SkPath::kDone_Verb:
Ben Wagnerb4aab9a2017-08-16 10:53:04 -0400315 SK_ABORT("Unexpected path verb");
csmartdaltoned4984b2017-02-13 14:57:28 -0700316 break;
317 }
318 }
319 }
320 }
321
322 void swapAnimationBuffers() override {
323 this->INHERITED::swapAnimationBuffers();
324 fFrontPaths.swap(fBackPaths);
325 }
326
Chris Dalton7c02cc72017-11-06 14:10:54 -0700327 void drawGlyphs(SkCanvas* canvas) override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700328 for (int i = 0; i < kNumPaths; ++i) {
329 canvas->drawPath(fFrontPaths[i], fGlyphs[i].fPaint);
330 }
331 }
332
333private:
334 /**
335 * Describes 4 stacked sine waves that can offset a point as a function of wall time.
336 */
337 class Waves {
338 public:
339 void reset(SkRandom& rand, int w, int h);
340 SkPoint apply(float tsec, const Sk2f matrix[3], const SkPoint& pt) const;
341
342 private:
343 constexpr static double kAverageAngle = SK_ScalarPI / 8.0;
344 constexpr static double kMaxOffsetAngle = SK_ScalarPI / 3.0;
345
346 float fAmplitudes[4];
347 float fFrequencies[4];
348 float fDirsX[4];
349 float fDirsY[4];
350 float fSpeeds[4];
351 float fOffsets[4];
352 };
353
354 SkAutoTArray<SkPath> fFrontPaths;
355 SkAutoTArray<SkPath> fBackPaths;
356 Waves fWaves;
357
358 typedef MovingPathText INHERITED;
359};
360
361void WavyPathText::Waves::reset(SkRandom& rand, int w, int h) {
362 const double pixelsPerMeter = 0.06 * SkTMax(w, h);
363 const double medianWavelength = 8 * pixelsPerMeter;
364 const double medianWaveAmplitude = 0.05 * 4 * pixelsPerMeter;
365 const double gravity = 9.8 * pixelsPerMeter;
366
367 for (int i = 0; i < 4; ++i) {
368 const double offsetAngle = (rand.nextF() * 2 - 1) * kMaxOffsetAngle;
369 const double intensity = pow(2, rand.nextF() * 2 - 1);
370 const double wavelength = intensity * medianWavelength;
371
372 fAmplitudes[i] = intensity * medianWaveAmplitude;
373 fFrequencies[i] = 2 * SK_ScalarPI / wavelength;
374 fDirsX[i] = cosf(kAverageAngle + offsetAngle);
375 fDirsY[i] = sinf(kAverageAngle + offsetAngle);
376 fSpeeds[i] = -sqrt(gravity * 2 * SK_ScalarPI / wavelength);
377 fOffsets[i] = rand.nextF() * 2 * SK_ScalarPI;
378 }
379}
380
381SkPoint WavyPathText::Waves::apply(float tsec, const Sk2f matrix[3], const SkPoint& pt) const {
Chris Dalton95cf1662017-06-20 16:32:59 -0700382 constexpr static int kTablePeriod = 1 << 12;
383 static float sin2table[kTablePeriod + 1];
csmartdaltoned4984b2017-02-13 14:57:28 -0700384 static SkOnce initTable;
385 initTable([]() {
Chris Dalton95cf1662017-06-20 16:32:59 -0700386 for (int i = 0; i <= kTablePeriod; ++i) {
387 const double sintheta = sin(i * (SK_ScalarPI / kTablePeriod));
csmartdaltoned4984b2017-02-13 14:57:28 -0700388 sin2table[i] = static_cast<float>(sintheta * sintheta - 0.5);
389 }
390 });
391
392 const Sk4f amplitudes = Sk4f::Load(fAmplitudes);
393 const Sk4f frequencies = Sk4f::Load(fFrequencies);
394 const Sk4f dirsX = Sk4f::Load(fDirsX);
395 const Sk4f dirsY = Sk4f::Load(fDirsY);
396 const Sk4f speeds = Sk4f::Load(fSpeeds);
397 const Sk4f offsets = Sk4f::Load(fOffsets);
398
399 float devicePt[2];
400 (matrix[0] * pt.x() + matrix[1] * pt.y() + matrix[2]).store(devicePt);
401
402 const Sk4f t = (frequencies * (dirsX * devicePt[0] + dirsY * devicePt[1]) +
403 speeds * tsec +
Chris Dalton95cf1662017-06-20 16:32:59 -0700404 offsets).abs() * (float(kTablePeriod) / float(SK_ScalarPI));
csmartdaltoned4984b2017-02-13 14:57:28 -0700405
406 const Sk4i ipart = SkNx_cast<int>(t);
407 const Sk4f fpart = t - SkNx_cast<float>(ipart);
408
409 int32_t indices[4];
Chris Dalton95cf1662017-06-20 16:32:59 -0700410 (ipart & (kTablePeriod-1)).store(indices);
csmartdaltoned4984b2017-02-13 14:57:28 -0700411
412 const Sk4f left(sin2table[indices[0]], sin2table[indices[1]],
413 sin2table[indices[2]], sin2table[indices[3]]);
414 const Sk4f right(sin2table[indices[0] + 1], sin2table[indices[1] + 1],
415 sin2table[indices[2] + 1], sin2table[indices[3] + 1]);
416 const Sk4f height = amplitudes * (left * (1.f - fpart) + right * fpart);
417
418 Sk4f dy = height * dirsY;
419 Sk4f dx = height * dirsX;
420
421 float offsetY[4], offsetX[4];
422 (dy + SkNx_shuffle<2,3,0,1>(dy)).store(offsetY); // accumulate.
423 (dx + SkNx_shuffle<2,3,0,1>(dx)).store(offsetX);;
424
425 return {devicePt[0] + offsetY[0] + offsetY[1], devicePt[1] - offsetX[0] - offsetX[1]};
426}
427
428////////////////////////////////////////////////////////////////////////////////////////////////////
429
430DEF_SAMPLE( return new WavyPathText; )
431DEF_SAMPLE( return new MovingPathText; )
432DEF_SAMPLE( return new PathText; )