1/*
2 * Copyright 2014 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 "SkPatchUtils.h"
9
10#include "SkColorData.h"
11#include "SkGeometry.h"
12#include "SkPM4f.h"
13
14namespace {
15    enum CubicCtrlPts {
16        kTopP0_CubicCtrlPts = 0,
17        kTopP1_CubicCtrlPts = 1,
18        kTopP2_CubicCtrlPts = 2,
19        kTopP3_CubicCtrlPts = 3,
20
21        kRightP0_CubicCtrlPts = 3,
22        kRightP1_CubicCtrlPts = 4,
23        kRightP2_CubicCtrlPts = 5,
24        kRightP3_CubicCtrlPts = 6,
25
26        kBottomP0_CubicCtrlPts = 9,
27        kBottomP1_CubicCtrlPts = 8,
28        kBottomP2_CubicCtrlPts = 7,
29        kBottomP3_CubicCtrlPts = 6,
30
31        kLeftP0_CubicCtrlPts = 0,
32        kLeftP1_CubicCtrlPts = 11,
33        kLeftP2_CubicCtrlPts = 10,
34        kLeftP3_CubicCtrlPts = 9,
35    };
36
37    // Enum for corner also clockwise.
38    enum Corner {
39        kTopLeft_Corner = 0,
40        kTopRight_Corner,
41        kBottomRight_Corner,
42        kBottomLeft_Corner
43    };
44}
45
46/**
47 * Evaluator to sample the values of a cubic bezier using forward differences.
48 * Forward differences is a method for evaluating a nth degree polynomial at a uniform step by only
49 * adding precalculated values.
50 * For a linear example we have the function f(t) = m*t+b, then the value of that function at t+h
51 * would be f(t+h) = m*(t+h)+b. If we want to know the uniform step that we must add to the first
52 * evaluation f(t) then we need to substract f(t+h) - f(t) = m*t + m*h + b - m*t + b = mh. After
53 * obtaining this value (mh) we could just add this constant step to our first sampled point
54 * to compute the next one.
55 *
56 * For the cubic case the first difference gives as a result a quadratic polynomial to which we can
57 * apply again forward differences and get linear function to which we can apply again forward
58 * differences to get a constant difference. This is why we keep an array of size 4, the 0th
59 * position keeps the sampled value while the next ones keep the quadratic, linear and constant
60 * difference values.
61 */
62
63class FwDCubicEvaluator {
64
65public:
66
67    /**
68     * Receives the 4 control points of the cubic bezier.
69     */
70
71    explicit FwDCubicEvaluator(const SkPoint points[4])
72            : fCoefs(points) {
73        memcpy(fPoints, points, 4 * sizeof(SkPoint));
74
75        this->restart(1);
76    }
77
78    /**
79     * Restarts the forward differences evaluator to the first value of t = 0.
80     */
81    void restart(int divisions)  {
82        fDivisions = divisions;
83        fCurrent    = 0;
84        fMax        = fDivisions + 1;
85        Sk2s h  = Sk2s(1.f / fDivisions);
86        Sk2s h2 = h * h;
87        Sk2s h3 = h2 * h;
88        Sk2s fwDiff3 = Sk2s(6) * fCoefs.fA * h3;
89        fFwDiff[3] = to_point(fwDiff3);
90        fFwDiff[2] = to_point(fwDiff3 + times_2(fCoefs.fB) * h2);
91        fFwDiff[1] = to_point(fCoefs.fA * h3 + fCoefs.fB * h2 + fCoefs.fC * h);
92        fFwDiff[0] = to_point(fCoefs.fD);
93    }
94
95    /**
96     * Check if the evaluator is still within the range of 0<=t<=1
97     */
98    bool done() const {
99        return fCurrent > fMax;
100    }
101
102    /**
103     * Call next to obtain the SkPoint sampled and move to the next one.
104     */
105    SkPoint next() {
106        SkPoint point = fFwDiff[0];
107        fFwDiff[0]    += fFwDiff[1];
108        fFwDiff[1]    += fFwDiff[2];
109        fFwDiff[2]    += fFwDiff[3];
110        fCurrent++;
111        return point;
112    }
113
114    const SkPoint* getCtrlPoints() const {
115        return fPoints;
116    }
117
118private:
119    SkCubicCoeff fCoefs;
120    int fMax, fCurrent, fDivisions;
121    SkPoint fFwDiff[4], fPoints[4];
122};
123
124////////////////////////////////////////////////////////////////////////////////
125
126// size in pixels of each partition per axis, adjust this knob
127static const int kPartitionSize = 10;
128
129/**
130 * Calculate the approximate arc length given a bezier curve's control points.
131 */
132static SkScalar approx_arc_length(SkPoint* points, int count) {
133    if (count < 2) {
134        return 0;
135    }
136    SkScalar arcLength = 0;
137    for (int i = 0; i < count - 1; i++) {
138        arcLength += SkPoint::Distance(points[i], points[i + 1]);
139    }
140    return arcLength;
141}
142
143static SkScalar bilerp(SkScalar tx, SkScalar ty, SkScalar c00, SkScalar c10, SkScalar c01,
144                       SkScalar c11) {
145    SkScalar a = c00 * (1.f - tx) + c10 * tx;
146    SkScalar b = c01 * (1.f - tx) + c11 * tx;
147    return a * (1.f - ty) + b * ty;
148}
149
150static Sk4f bilerp(SkScalar tx, SkScalar ty,
151                   const Sk4f& c00, const Sk4f& c10, const Sk4f& c01, const Sk4f& c11) {
152    Sk4f a = c00 * (1.f - tx) + c10 * tx;
153    Sk4f b = c01 * (1.f - tx) + c11 * tx;
154    return a * (1.f - ty) + b * ty;
155}
156
157SkISize SkPatchUtils::GetLevelOfDetail(const SkPoint cubics[12], const SkMatrix* matrix) {
158
159    // Approximate length of each cubic.
160    SkPoint pts[kNumPtsCubic];
161    SkPatchUtils::GetTopCubic(cubics, pts);
162    matrix->mapPoints(pts, kNumPtsCubic);
163    SkScalar topLength = approx_arc_length(pts, kNumPtsCubic);
164
165    SkPatchUtils::GetBottomCubic(cubics, pts);
166    matrix->mapPoints(pts, kNumPtsCubic);
167    SkScalar bottomLength = approx_arc_length(pts, kNumPtsCubic);
168
169    SkPatchUtils::GetLeftCubic(cubics, pts);
170    matrix->mapPoints(pts, kNumPtsCubic);
171    SkScalar leftLength = approx_arc_length(pts, kNumPtsCubic);
172
173    SkPatchUtils::GetRightCubic(cubics, pts);
174    matrix->mapPoints(pts, kNumPtsCubic);
175    SkScalar rightLength = approx_arc_length(pts, kNumPtsCubic);
176
177    // Level of detail per axis, based on the larger side between top and bottom or left and right
178    int lodX = static_cast<int>(SkMaxScalar(topLength, bottomLength) / kPartitionSize);
179    int lodY = static_cast<int>(SkMaxScalar(leftLength, rightLength) / kPartitionSize);
180
181    return SkISize::Make(SkMax32(8, lodX), SkMax32(8, lodY));
182}
183
184void SkPatchUtils::GetTopCubic(const SkPoint cubics[12], SkPoint points[4]) {
185    points[0] = cubics[kTopP0_CubicCtrlPts];
186    points[1] = cubics[kTopP1_CubicCtrlPts];
187    points[2] = cubics[kTopP2_CubicCtrlPts];
188    points[3] = cubics[kTopP3_CubicCtrlPts];
189}
190
191void SkPatchUtils::GetBottomCubic(const SkPoint cubics[12], SkPoint points[4]) {
192    points[0] = cubics[kBottomP0_CubicCtrlPts];
193    points[1] = cubics[kBottomP1_CubicCtrlPts];
194    points[2] = cubics[kBottomP2_CubicCtrlPts];
195    points[3] = cubics[kBottomP3_CubicCtrlPts];
196}
197
198void SkPatchUtils::GetLeftCubic(const SkPoint cubics[12], SkPoint points[4]) {
199    points[0] = cubics[kLeftP0_CubicCtrlPts];
200    points[1] = cubics[kLeftP1_CubicCtrlPts];
201    points[2] = cubics[kLeftP2_CubicCtrlPts];
202    points[3] = cubics[kLeftP3_CubicCtrlPts];
203}
204
205void SkPatchUtils::GetRightCubic(const SkPoint cubics[12], SkPoint points[4]) {
206    points[0] = cubics[kRightP0_CubicCtrlPts];
207    points[1] = cubics[kRightP1_CubicCtrlPts];
208    points[2] = cubics[kRightP2_CubicCtrlPts];
209    points[3] = cubics[kRightP3_CubicCtrlPts];
210}
211
212#include "SkPM4fPriv.h"
213#include "SkColorSpaceXform.h"
214
215struct SkRGBAf {
216    float fVec[4];
217
218    static SkRGBAf From4f(const Sk4f& x) {
219        SkRGBAf c;
220        x.store(c.fVec);
221        return c;
222    }
223
224    static SkRGBAf FromBGRA32(SkColor c) {
225        return From4f(swizzle_rb(SkNx_cast<float>(Sk4b::Load(&c)) * (1/255.0f)));
226    }
227
228    Sk4f to4f() const {
229        return Sk4f::Load(fVec);
230    }
231
232    SkColor toBGRA32() const {
233        SkColor color;
234        SkNx_cast<uint8_t>(swizzle_rb(this->to4f()) * Sk4f(255) + Sk4f(0.5f)).store(&color);
235        return color;
236    }
237
238    SkRGBAf premul() const {
239        float a = fVec[3];
240        return From4f(this->to4f() * Sk4f(a, a, a, 1));
241    }
242
243    SkRGBAf unpremul() const {
244        float a = fVec[3];
245        float inv = a ? 1/a : 0;
246        return From4f(this->to4f() * Sk4f(inv, inv, inv, 1));
247    }
248};
249
250static void skcolor_to_linear(SkRGBAf dst[], const SkColor src[], int count, SkColorSpace* cs,
251                              bool doPremul) {
252    if (cs) {
253        auto srcCS = SkColorSpace::MakeSRGB();
254        auto dstCS = cs->makeLinearGamma();
255        auto op = doPremul ? SkColorSpaceXform::kPremul_AlphaOp
256                           : SkColorSpaceXform::kPreserve_AlphaOp;
257        SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat,  dst,
258                                 srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src,
259                                 count, op);
260    } else {
261        for (int i = 0; i < count; ++i) {
262            dst[i] = SkRGBAf::FromBGRA32(src[i]);
263            if (doPremul) {
264                dst[i] = dst[i].premul();
265            }
266        }
267    }
268}
269
270static void linear_to_skcolor(SkColor dst[], const SkRGBAf src[], int count, SkColorSpace* cs) {
271    if (cs) {
272        auto srcCS = cs->makeLinearGamma();
273        auto dstCS = SkColorSpace::MakeSRGB();
274        SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, dst,
275                                 srcCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat,  src,
276                                 count, SkColorSpaceXform::kPreserve_AlphaOp);
277    } else {
278        for (int i = 0; i < count; ++i) {
279            dst[i] = src[i].toBGRA32();
280        }
281    }
282}
283
284static void unpremul(SkRGBAf array[], int count) {
285    for (int i = 0; i < count; ++i) {
286        array[i] = array[i].unpremul();
287    }
288}
289
290sk_sp<SkVertices> SkPatchUtils::MakeVertices(const SkPoint cubics[12], const SkColor srcColors[4],
291                                             const SkPoint srcTexCoords[4], int lodX, int lodY,
292                                             bool interpColorsLinearly) {
293    if (lodX < 1 || lodY < 1 || nullptr == cubics) {
294        return nullptr;
295    }
296
297    // check for overflow in multiplication
298    const int64_t lodX64 = (lodX + 1),
299    lodY64 = (lodY + 1),
300    mult64 = lodX64 * lodY64;
301    if (mult64 > SK_MaxS32) {
302        return nullptr;
303    }
304
305    int vertexCount = SkToS32(mult64);
306    // it is recommended to generate draw calls of no more than 65536 indices, so we never generate
307    // more than 60000 indices. To accomplish that we resize the LOD and vertex count
308    if (vertexCount > 10000 || lodX > 200 || lodY > 200) {
309        float weightX = static_cast<float>(lodX) / (lodX + lodY);
310        float weightY = static_cast<float>(lodY) / (lodX + lodY);
311
312        // 200 comes from the 100 * 2 which is the max value of vertices because of the limit of
313        // 60000 indices ( sqrt(60000 / 6) that comes from data->fIndexCount = lodX * lodY * 6)
314        lodX = static_cast<int>(weightX * 200);
315        lodY = static_cast<int>(weightY * 200);
316        vertexCount = (lodX + 1) * (lodY + 1);
317    }
318    const int indexCount = lodX * lodY * 6;
319    uint32_t flags = 0;
320    if (srcTexCoords) {
321        flags |= SkVertices::kHasTexCoords_BuilderFlag;
322    }
323    if (srcColors) {
324        flags |= SkVertices::kHasColors_BuilderFlag;
325    }
326
327    SkSTArenaAlloc<2048> alloc;
328    SkRGBAf* cornerColors = srcColors ? alloc.makeArray<SkRGBAf>(4) : nullptr;
329    SkRGBAf* tmpColors = srcColors ? alloc.makeArray<SkRGBAf>(vertexCount) : nullptr;
330    auto convertCS = interpColorsLinearly ? SkColorSpace::MakeSRGB() : nullptr;
331
332    SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, indexCount, flags);
333    SkPoint* pos = builder.positions();
334    SkPoint* texs = builder.texCoords();
335    uint16_t* indices = builder.indices();
336    bool is_opaque = false;
337
338    /*
339     *  1. Should we offer this as a runtime choice, as we do in gradients?
340     *  2. Since drawing the vertices wants premul, shoudl we extend SkVertices to store
341     *     premul colors (as floats, w/ a colorspace)?
342     */
343    bool doPremul = true;
344    if (cornerColors) {
345        SkColor c = ~0;
346        for (int i = 0; i < kNumCorners; i++) {
347            c &= srcColors[i];
348        }
349        is_opaque = (SkColorGetA(c) == 0xFF);
350        if (is_opaque) {
351            doPremul = false;   // no need
352        }
353
354        skcolor_to_linear(cornerColors, srcColors, kNumCorners, convertCS.get(), doPremul);
355    }
356
357    SkPoint pts[kNumPtsCubic];
358    SkPatchUtils::GetBottomCubic(cubics, pts);
359    FwDCubicEvaluator fBottom(pts);
360    SkPatchUtils::GetTopCubic(cubics, pts);
361    FwDCubicEvaluator fTop(pts);
362    SkPatchUtils::GetLeftCubic(cubics, pts);
363    FwDCubicEvaluator fLeft(pts);
364    SkPatchUtils::GetRightCubic(cubics, pts);
365    FwDCubicEvaluator fRight(pts);
366
367    fBottom.restart(lodX);
368    fTop.restart(lodX);
369
370    SkScalar u = 0.0f;
371    int stride = lodY + 1;
372    for (int x = 0; x <= lodX; x++) {
373        SkPoint bottom = fBottom.next(), top = fTop.next();
374        fLeft.restart(lodY);
375        fRight.restart(lodY);
376        SkScalar v = 0.f;
377        for (int y = 0; y <= lodY; y++) {
378            int dataIndex = x * (lodY + 1) + y;
379
380            SkPoint left = fLeft.next(), right = fRight.next();
381
382            SkPoint s0 = SkPoint::Make((1.0f - v) * top.x() + v * bottom.x(),
383                                       (1.0f - v) * top.y() + v * bottom.y());
384            SkPoint s1 = SkPoint::Make((1.0f - u) * left.x() + u * right.x(),
385                                       (1.0f - u) * left.y() + u * right.y());
386            SkPoint s2 = SkPoint::Make(
387                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].x()
388                                                     + u * fTop.getCtrlPoints()[3].x())
389                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].x()
390                                              + u * fBottom.getCtrlPoints()[3].x()),
391                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].y()
392                                                     + u * fTop.getCtrlPoints()[3].y())
393                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].y()
394                                              + u * fBottom.getCtrlPoints()[3].y()));
395            pos[dataIndex] = s0 + s1 - s2;
396
397            if (cornerColors) {
398                bilerp(u, v, cornerColors[kTopLeft_Corner].to4f(),
399                             cornerColors[kTopRight_Corner].to4f(),
400                             cornerColors[kBottomLeft_Corner].to4f(),
401                             cornerColors[kBottomRight_Corner].to4f()).store(tmpColors[dataIndex].fVec);
402                if (is_opaque) {
403                    tmpColors[dataIndex].fVec[3] = 1;
404                }
405            }
406
407            if (texs) {
408                texs[dataIndex] = SkPoint::Make(bilerp(u, v, srcTexCoords[kTopLeft_Corner].x(),
409                                                       srcTexCoords[kTopRight_Corner].x(),
410                                                       srcTexCoords[kBottomLeft_Corner].x(),
411                                                       srcTexCoords[kBottomRight_Corner].x()),
412                                                bilerp(u, v, srcTexCoords[kTopLeft_Corner].y(),
413                                                       srcTexCoords[kTopRight_Corner].y(),
414                                                       srcTexCoords[kBottomLeft_Corner].y(),
415                                                       srcTexCoords[kBottomRight_Corner].y()));
416
417            }
418
419            if(x < lodX && y < lodY) {
420                int i = 6 * (x * lodY + y);
421                indices[i] = x * stride + y;
422                indices[i + 1] = x * stride + 1 + y;
423                indices[i + 2] = (x + 1) * stride + 1 + y;
424                indices[i + 3] = indices[i];
425                indices[i + 4] = indices[i + 2];
426                indices[i + 5] = (x + 1) * stride + y;
427            }
428            v = SkScalarClampMax(v + 1.f / lodY, 1);
429        }
430        u = SkScalarClampMax(u + 1.f / lodX, 1);
431    }
432
433    if (tmpColors) {
434        if (doPremul) {
435            unpremul(tmpColors, vertexCount);
436        }
437        linear_to_skcolor(builder.colors(), tmpColors, vertexCount, convertCS.get());
438    }
439    return builder.detach();
440}
441