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 "SkColorPriv.h"
11#include "SkGeometry.h"
12
13/**
14 * Evaluator to sample the values of a cubic bezier using forward differences.
15 * Forward differences is a method for evaluating a nth degree polynomial at a uniform step by only
16 * adding precalculated values.
17 * For a linear example we have the function f(t) = m*t+b, then the value of that function at t+h
18 * would be f(t+h) = m*(t+h)+b. If we want to know the uniform step that we must add to the first
19 * evaluation f(t) then we need to substract f(t+h) - f(t) = m*t + m*h + b - m*t + b = mh. After
20 * obtaining this value (mh) we could just add this constant step to our first sampled point
21 * to compute the next one.
22 *
23 * For the cubic case the first difference gives as a result a quadratic polynomial to which we can
24 * apply again forward differences and get linear function to which we can apply again forward
25 * differences to get a constant difference. This is why we keep an array of size 4, the 0th
26 * position keeps the sampled value while the next ones keep the quadratic, linear and constant
27 * difference values.
28 */
29
30class FwDCubicEvaluator {
31
32public:
33    FwDCubicEvaluator()
34    : fMax(0)
35    , fCurrent(0)
36    , fDivisions(0) {
37        memset(fPoints, 0, 4 * sizeof(SkPoint));
38        memset(fPoints, 0, 4 * sizeof(SkPoint));
39        memset(fPoints, 0, 4 * sizeof(SkPoint));
40    }
41
42    /**
43     * Receives the 4 control points of the cubic bezier.
44     */
45    FwDCubicEvaluator(SkPoint a, SkPoint b, SkPoint c, SkPoint d) {
46        fPoints[0] = a;
47        fPoints[1] = b;
48        fPoints[2] = c;
49        fPoints[3] = d;
50
51        SkScalar cx[4], cy[4];
52        SkGetCubicCoeff(fPoints, cx, cy);
53        fCoefs[0].set(cx[0], cy[0]);
54        fCoefs[1].set(cx[1], cy[1]);
55        fCoefs[2].set(cx[2], cy[2]);
56        fCoefs[3].set(cx[3], cy[3]);
57
58        this->restart(1);
59    }
60
61    explicit FwDCubicEvaluator(const SkPoint points[4])  {
62        memcpy(fPoints, points, 4 * sizeof(SkPoint));
63
64        SkScalar cx[4], cy[4];
65        SkGetCubicCoeff(fPoints, cx, cy);
66        fCoefs[0].set(cx[0], cy[0]);
67        fCoefs[1].set(cx[1], cy[1]);
68        fCoefs[2].set(cx[2], cy[2]);
69        fCoefs[3].set(cx[3], cy[3]);
70
71        this->restart(1);
72    }
73
74    /**
75     * Restarts the forward differences evaluator to the first value of t = 0.
76     */
77    void restart(int divisions)  {
78        fDivisions = divisions;
79        SkScalar h  = 1.f / fDivisions;
80        fCurrent    = 0;
81        fMax        = fDivisions + 1;
82        fFwDiff[0]  = fCoefs[3];
83        SkScalar h2 = h * h;
84        SkScalar h3 = h2 * h;
85
86        fFwDiff[3].set(6.f * fCoefs[0].x() * h3, 6.f * fCoefs[0].y() * h3); //6ah^3
87        fFwDiff[2].set(fFwDiff[3].x() + 2.f * fCoefs[1].x() * h2, //6ah^3 + 2bh^2
88                       fFwDiff[3].y() + 2.f * fCoefs[1].y() * h2);
89        fFwDiff[1].set(fCoefs[0].x() * h3 + fCoefs[1].x() * h2 + fCoefs[2].x() * h,//ah^3 + bh^2 +ch
90                       fCoefs[0].y() * h3 + fCoefs[1].y() * h2 + fCoefs[2].y() * h);
91    }
92
93    /**
94     * Check if the evaluator is still within the range of 0<=t<=1
95     */
96    bool done() const {
97        return fCurrent > fMax;
98    }
99
100    /**
101     * Call next to obtain the SkPoint sampled and move to the next one.
102     */
103    SkPoint next() {
104        SkPoint point = fFwDiff[0];
105        fFwDiff[0]    += fFwDiff[1];
106        fFwDiff[1]    += fFwDiff[2];
107        fFwDiff[2]    += fFwDiff[3];
108        fCurrent++;
109        return point;
110    }
111
112    const SkPoint* getCtrlPoints() const {
113        return fPoints;
114    }
115
116private:
117    int fMax, fCurrent, fDivisions;
118    SkPoint fFwDiff[4], fCoefs[4], fPoints[4];
119};
120
121////////////////////////////////////////////////////////////////////////////////
122
123// size in pixels of each partition per axis, adjust this knob
124static const int kPartitionSize = 10;
125
126/**
127 * Calculate the approximate arc length given a bezier curve's control points.
128 */
129static SkScalar approx_arc_length(SkPoint* points, int count) {
130    if (count < 2) {
131        return 0;
132    }
133    SkScalar arcLength = 0;
134    for (int i = 0; i < count - 1; i++) {
135        arcLength += SkPoint::Distance(points[i], points[i + 1]);
136    }
137    return arcLength;
138}
139
140static SkScalar bilerp(SkScalar tx, SkScalar ty, SkScalar c00, SkScalar c10, SkScalar c01,
141                      SkScalar c11) {
142    SkScalar a = c00 * (1.f - tx) + c10 * tx;
143    SkScalar b = c01 * (1.f - tx) + c11 * tx;
144    return a * (1.f - ty) + b * ty;
145}
146
147SkISize SkPatchUtils::GetLevelOfDetail(const SkPoint cubics[12], const SkMatrix* matrix) {
148
149    // Approximate length of each cubic.
150    SkPoint pts[kNumPtsCubic];
151    SkPatchUtils::getTopCubic(cubics, pts);
152    matrix->mapPoints(pts, kNumPtsCubic);
153    SkScalar topLength = approx_arc_length(pts, kNumPtsCubic);
154
155    SkPatchUtils::getBottomCubic(cubics, pts);
156    matrix->mapPoints(pts, kNumPtsCubic);
157    SkScalar bottomLength = approx_arc_length(pts, kNumPtsCubic);
158
159    SkPatchUtils::getLeftCubic(cubics, pts);
160    matrix->mapPoints(pts, kNumPtsCubic);
161    SkScalar leftLength = approx_arc_length(pts, kNumPtsCubic);
162
163    SkPatchUtils::getRightCubic(cubics, pts);
164    matrix->mapPoints(pts, kNumPtsCubic);
165    SkScalar rightLength = approx_arc_length(pts, kNumPtsCubic);
166
167    // Level of detail per axis, based on the larger side between top and bottom or left and right
168    int lodX = static_cast<int>(SkMaxScalar(topLength, bottomLength) / kPartitionSize);
169    int lodY = static_cast<int>(SkMaxScalar(leftLength, rightLength) / kPartitionSize);
170
171    return SkISize::Make(SkMax32(8, lodX), SkMax32(8, lodY));
172}
173
174void SkPatchUtils::getTopCubic(const SkPoint cubics[12], SkPoint points[4]) {
175    points[0] = cubics[kTopP0_CubicCtrlPts];
176    points[1] = cubics[kTopP1_CubicCtrlPts];
177    points[2] = cubics[kTopP2_CubicCtrlPts];
178    points[3] = cubics[kTopP3_CubicCtrlPts];
179}
180
181void SkPatchUtils::getBottomCubic(const SkPoint cubics[12], SkPoint points[4]) {
182    points[0] = cubics[kBottomP0_CubicCtrlPts];
183    points[1] = cubics[kBottomP1_CubicCtrlPts];
184    points[2] = cubics[kBottomP2_CubicCtrlPts];
185    points[3] = cubics[kBottomP3_CubicCtrlPts];
186}
187
188void SkPatchUtils::getLeftCubic(const SkPoint cubics[12], SkPoint points[4]) {
189    points[0] = cubics[kLeftP0_CubicCtrlPts];
190    points[1] = cubics[kLeftP1_CubicCtrlPts];
191    points[2] = cubics[kLeftP2_CubicCtrlPts];
192    points[3] = cubics[kLeftP3_CubicCtrlPts];
193}
194
195void SkPatchUtils::getRightCubic(const SkPoint cubics[12], SkPoint points[4]) {
196    points[0] = cubics[kRightP0_CubicCtrlPts];
197    points[1] = cubics[kRightP1_CubicCtrlPts];
198    points[2] = cubics[kRightP2_CubicCtrlPts];
199    points[3] = cubics[kRightP3_CubicCtrlPts];
200}
201
202bool SkPatchUtils::getVertexData(SkPatchUtils::VertexData* data, const SkPoint cubics[12],
203                   const SkColor colors[4], const SkPoint texCoords[4], int lodX, int lodY) {
204    if (lodX < 1 || lodY < 1 || NULL == cubics || NULL == data) {
205        return false;
206    }
207
208    // check for overflow in multiplication
209    const int64_t lodX64 = (lodX + 1),
210                   lodY64 = (lodY + 1),
211                   mult64 = lodX64 * lodY64;
212    if (mult64 > SK_MaxS32) {
213        return false;
214    }
215    data->fVertexCount = SkToS32(mult64);
216
217    // it is recommended to generate draw calls of no more than 65536 indices, so we never generate
218    // more than 60000 indices. To accomplish that we resize the LOD and vertex count
219    if (data->fVertexCount > 10000 || lodX > 200 || lodY > 200) {
220        SkScalar weightX = static_cast<SkScalar>(lodX) / (lodX + lodY);
221        SkScalar weightY = static_cast<SkScalar>(lodY) / (lodX + lodY);
222
223        // 200 comes from the 100 * 2 which is the max value of vertices because of the limit of
224        // 60000 indices ( sqrt(60000 / 6) that comes from data->fIndexCount = lodX * lodY * 6)
225        lodX = static_cast<int>(weightX * 200);
226        lodY = static_cast<int>(weightY * 200);
227        data->fVertexCount = (lodX + 1) * (lodY + 1);
228    }
229    data->fIndexCount = lodX * lodY * 6;
230
231    data->fPoints = SkNEW_ARRAY(SkPoint, data->fVertexCount);
232    data->fIndices = SkNEW_ARRAY(uint16_t, data->fIndexCount);
233
234    // if colors is not null then create array for colors
235    SkPMColor colorsPM[kNumCorners];
236    if (colors) {
237        // premultiply colors to avoid color bleeding.
238        for (int i = 0; i < kNumCorners; i++) {
239            colorsPM[i] = SkPreMultiplyColor(colors[i]);
240        }
241        data->fColors = SkNEW_ARRAY(uint32_t, data->fVertexCount);
242    }
243
244    // if texture coordinates are not null then create array for them
245    if (texCoords) {
246        data->fTexCoords = SkNEW_ARRAY(SkPoint, data->fVertexCount);
247    }
248
249    SkPoint pts[kNumPtsCubic];
250    SkPatchUtils::getBottomCubic(cubics, pts);
251    FwDCubicEvaluator fBottom(pts);
252    SkPatchUtils::getTopCubic(cubics, pts);
253    FwDCubicEvaluator fTop(pts);
254    SkPatchUtils::getLeftCubic(cubics, pts);
255    FwDCubicEvaluator fLeft(pts);
256    SkPatchUtils::getRightCubic(cubics, pts);
257    FwDCubicEvaluator fRight(pts);
258
259    fBottom.restart(lodX);
260    fTop.restart(lodX);
261
262    SkScalar u = 0.0f;
263    int stride = lodY + 1;
264    for (int x = 0; x <= lodX; x++) {
265        SkPoint bottom = fBottom.next(), top = fTop.next();
266        fLeft.restart(lodY);
267        fRight.restart(lodY);
268        SkScalar v = 0.f;
269        for (int y = 0; y <= lodY; y++) {
270            int dataIndex = x * (lodY + 1) + y;
271
272            SkPoint left = fLeft.next(), right = fRight.next();
273
274            SkPoint s0 = SkPoint::Make((1.0f - v) * top.x() + v * bottom.x(),
275                                       (1.0f - v) * top.y() + v * bottom.y());
276            SkPoint s1 = SkPoint::Make((1.0f - u) * left.x() + u * right.x(),
277                                       (1.0f - u) * left.y() + u * right.y());
278            SkPoint s2 = SkPoint::Make(
279                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].x()
280                                                     + u * fTop.getCtrlPoints()[3].x())
281                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].x()
282                                              + u * fBottom.getCtrlPoints()[3].x()),
283                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].y()
284                                                     + u * fTop.getCtrlPoints()[3].y())
285                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].y()
286                                              + u * fBottom.getCtrlPoints()[3].y()));
287            data->fPoints[dataIndex] = s0 + s1 - s2;
288
289            if (colors) {
290                uint8_t a = uint8_t(bilerp(u, v,
291                                   SkScalar(SkColorGetA(colorsPM[kTopLeft_Corner])),
292                                   SkScalar(SkColorGetA(colorsPM[kTopRight_Corner])),
293                                   SkScalar(SkColorGetA(colorsPM[kBottomLeft_Corner])),
294                                   SkScalar(SkColorGetA(colorsPM[kBottomRight_Corner]))));
295                uint8_t r = uint8_t(bilerp(u, v,
296                                   SkScalar(SkColorGetR(colorsPM[kTopLeft_Corner])),
297                                   SkScalar(SkColorGetR(colorsPM[kTopRight_Corner])),
298                                   SkScalar(SkColorGetR(colorsPM[kBottomLeft_Corner])),
299                                   SkScalar(SkColorGetR(colorsPM[kBottomRight_Corner]))));
300                uint8_t g = uint8_t(bilerp(u, v,
301                                   SkScalar(SkColorGetG(colorsPM[kTopLeft_Corner])),
302                                   SkScalar(SkColorGetG(colorsPM[kTopRight_Corner])),
303                                   SkScalar(SkColorGetG(colorsPM[kBottomLeft_Corner])),
304                                   SkScalar(SkColorGetG(colorsPM[kBottomRight_Corner]))));
305                uint8_t b = uint8_t(bilerp(u, v,
306                                   SkScalar(SkColorGetB(colorsPM[kTopLeft_Corner])),
307                                   SkScalar(SkColorGetB(colorsPM[kTopRight_Corner])),
308                                   SkScalar(SkColorGetB(colorsPM[kBottomLeft_Corner])),
309                                   SkScalar(SkColorGetB(colorsPM[kBottomRight_Corner]))));
310                data->fColors[dataIndex] = SkPackARGB32(a,r,g,b);
311            }
312
313            if (texCoords) {
314                data->fTexCoords[dataIndex] = SkPoint::Make(
315                                            bilerp(u, v, texCoords[kTopLeft_Corner].x(),
316                                                   texCoords[kTopRight_Corner].x(),
317                                                   texCoords[kBottomLeft_Corner].x(),
318                                                   texCoords[kBottomRight_Corner].x()),
319                                            bilerp(u, v, texCoords[kTopLeft_Corner].y(),
320                                                   texCoords[kTopRight_Corner].y(),
321                                                   texCoords[kBottomLeft_Corner].y(),
322                                                   texCoords[kBottomRight_Corner].y()));
323
324            }
325
326            if(x < lodX && y < lodY) {
327                int i = 6 * (x * lodY + y);
328                data->fIndices[i] = x * stride + y;
329                data->fIndices[i + 1] = x * stride + 1 + y;
330                data->fIndices[i + 2] = (x + 1) * stride + 1 + y;
331                data->fIndices[i + 3] = data->fIndices[i];
332                data->fIndices[i + 4] = data->fIndices[i + 2];
333                data->fIndices[i + 5] = (x + 1) * stride + y;
334            }
335            v = SkScalarClampMax(v + 1.f / lodY, 1);
336        }
337        u = SkScalarClampMax(u + 1.f / lodX, 1);
338    }
339    return true;
340
341}
342