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