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 "src/utils/SkPatchUtils.h"
9 
10 #include "include/private/SkColorData.h"
11 #include "include/private/SkTo.h"
12 #include "src/core/SkArenaAlloc.h"
13 #include "src/core/SkColorSpacePriv.h"
14 #include "src/core/SkConvertPixels.h"
15 #include "src/core/SkGeometry.h"
16 
17 namespace {
18     enum CubicCtrlPts {
19         kTopP0_CubicCtrlPts = 0,
20         kTopP1_CubicCtrlPts = 1,
21         kTopP2_CubicCtrlPts = 2,
22         kTopP3_CubicCtrlPts = 3,
23 
24         kRightP0_CubicCtrlPts = 3,
25         kRightP1_CubicCtrlPts = 4,
26         kRightP2_CubicCtrlPts = 5,
27         kRightP3_CubicCtrlPts = 6,
28 
29         kBottomP0_CubicCtrlPts = 9,
30         kBottomP1_CubicCtrlPts = 8,
31         kBottomP2_CubicCtrlPts = 7,
32         kBottomP3_CubicCtrlPts = 6,
33 
34         kLeftP0_CubicCtrlPts = 0,
35         kLeftP1_CubicCtrlPts = 11,
36         kLeftP2_CubicCtrlPts = 10,
37         kLeftP3_CubicCtrlPts = 9,
38     };
39 
40     // Enum for corner also clockwise.
41     enum Corner {
42         kTopLeft_Corner = 0,
43         kTopRight_Corner,
44         kBottomRight_Corner,
45         kBottomLeft_Corner
46     };
47 }
48 
49 /**
50  * Evaluator to sample the values of a cubic bezier using forward differences.
51  * Forward differences is a method for evaluating a nth degree polynomial at a uniform step by only
52  * adding precalculated values.
53  * For a linear example we have the function f(t) = m*t+b, then the value of that function at t+h
54  * would be f(t+h) = m*(t+h)+b. If we want to know the uniform step that we must add to the first
55  * evaluation f(t) then we need to substract f(t+h) - f(t) = m*t + m*h + b - m*t + b = mh. After
56  * obtaining this value (mh) we could just add this constant step to our first sampled point
57  * to compute the next one.
58  *
59  * For the cubic case the first difference gives as a result a quadratic polynomial to which we can
60  * apply again forward differences and get linear function to which we can apply again forward
61  * differences to get a constant difference. This is why we keep an array of size 4, the 0th
62  * position keeps the sampled value while the next ones keep the quadratic, linear and constant
63  * difference values.
64  */
65 
66 class FwDCubicEvaluator {
67 
68 public:
69 
70     /**
71      * Receives the 4 control points of the cubic bezier.
72      */
73 
FwDCubicEvaluator(const SkPoint points[4])74     explicit FwDCubicEvaluator(const SkPoint points[4])
75             : fCoefs(points) {
76         memcpy(fPoints, points, 4 * sizeof(SkPoint));
77 
78         this->restart(1);
79     }
80 
81     /**
82      * Restarts the forward differences evaluator to the first value of t = 0.
83      */
restart(int divisions)84     void restart(int divisions)  {
85         fDivisions = divisions;
86         fCurrent    = 0;
87         fMax        = fDivisions + 1;
88         Sk2s h  = Sk2s(1.f / fDivisions);
89         Sk2s h2 = h * h;
90         Sk2s h3 = h2 * h;
91         Sk2s fwDiff3 = Sk2s(6) * fCoefs.fA * h3;
92         fFwDiff[3] = to_point(fwDiff3);
93         fFwDiff[2] = to_point(fwDiff3 + times_2(fCoefs.fB) * h2);
94         fFwDiff[1] = to_point(fCoefs.fA * h3 + fCoefs.fB * h2 + fCoefs.fC * h);
95         fFwDiff[0] = to_point(fCoefs.fD);
96     }
97 
98     /**
99      * Check if the evaluator is still within the range of 0<=t<=1
100      */
done() const101     bool done() const {
102         return fCurrent > fMax;
103     }
104 
105     /**
106      * Call next to obtain the SkPoint sampled and move to the next one.
107      */
next()108     SkPoint next() {
109         SkPoint point = fFwDiff[0];
110         fFwDiff[0]    += fFwDiff[1];
111         fFwDiff[1]    += fFwDiff[2];
112         fFwDiff[2]    += fFwDiff[3];
113         fCurrent++;
114         return point;
115     }
116 
getCtrlPoints() const117     const SkPoint* getCtrlPoints() const {
118         return fPoints;
119     }
120 
121 private:
122     SkCubicCoeff fCoefs;
123     int fMax, fCurrent, fDivisions;
124     SkPoint fFwDiff[4], fPoints[4];
125 };
126 
127 ////////////////////////////////////////////////////////////////////////////////
128 
129 // size in pixels of each partition per axis, adjust this knob
130 static const int kPartitionSize = 10;
131 
132 /**
133  *  Calculate the approximate arc length given a bezier curve's control points.
134  *  Returns -1 if bad calc (i.e. non-finite)
135  */
approx_arc_length(const SkPoint points[],int count)136 static SkScalar approx_arc_length(const SkPoint points[], int count) {
137     if (count < 2) {
138         return 0;
139     }
140     SkScalar arcLength = 0;
141     for (int i = 0; i < count - 1; i++) {
142         arcLength += SkPoint::Distance(points[i], points[i + 1]);
143     }
144     return SkScalarIsFinite(arcLength) ? arcLength : -1;
145 }
146 
bilerp(SkScalar tx,SkScalar ty,SkScalar c00,SkScalar c10,SkScalar c01,SkScalar c11)147 static SkScalar bilerp(SkScalar tx, SkScalar ty, SkScalar c00, SkScalar c10, SkScalar c01,
148                        SkScalar c11) {
149     SkScalar a = c00 * (1.f - tx) + c10 * tx;
150     SkScalar b = c01 * (1.f - tx) + c11 * tx;
151     return a * (1.f - ty) + b * ty;
152 }
153 
bilerp(SkScalar tx,SkScalar ty,const Sk4f & c00,const Sk4f & c10,const Sk4f & c01,const Sk4f & c11)154 static Sk4f bilerp(SkScalar tx, SkScalar ty,
155                    const Sk4f& c00, const Sk4f& c10, const Sk4f& c01, const Sk4f& c11) {
156     Sk4f a = c00 * (1.f - tx) + c10 * tx;
157     Sk4f b = c01 * (1.f - tx) + c11 * tx;
158     return a * (1.f - ty) + b * ty;
159 }
160 
GetLevelOfDetail(const SkPoint cubics[12],const SkMatrix * matrix)161 SkISize SkPatchUtils::GetLevelOfDetail(const SkPoint cubics[12], const SkMatrix* matrix) {
162     // Approximate length of each cubic.
163     SkPoint pts[kNumPtsCubic];
164     SkPatchUtils::GetTopCubic(cubics, pts);
165     matrix->mapPoints(pts, kNumPtsCubic);
166     SkScalar topLength = approx_arc_length(pts, kNumPtsCubic);
167 
168     SkPatchUtils::GetBottomCubic(cubics, pts);
169     matrix->mapPoints(pts, kNumPtsCubic);
170     SkScalar bottomLength = approx_arc_length(pts, kNumPtsCubic);
171 
172     SkPatchUtils::GetLeftCubic(cubics, pts);
173     matrix->mapPoints(pts, kNumPtsCubic);
174     SkScalar leftLength = approx_arc_length(pts, kNumPtsCubic);
175 
176     SkPatchUtils::GetRightCubic(cubics, pts);
177     matrix->mapPoints(pts, kNumPtsCubic);
178     SkScalar rightLength = approx_arc_length(pts, kNumPtsCubic);
179 
180     if (topLength < 0 || bottomLength < 0 || leftLength < 0 || rightLength < 0) {
181         return {0, 0};  // negative length is a sentinel for bad length (i.e. non-finite)
182     }
183 
184     // Level of detail per axis, based on the larger side between top and bottom or left and right
185     int lodX = static_cast<int>(std::max(topLength, bottomLength) / kPartitionSize);
186     int lodY = static_cast<int>(std::max(leftLength, rightLength) / kPartitionSize);
187 
188     return SkISize::Make(std::max(8, lodX), std::max(8, lodY));
189 }
190 
GetTopCubic(const SkPoint cubics[12],SkPoint points[4])191 void SkPatchUtils::GetTopCubic(const SkPoint cubics[12], SkPoint points[4]) {
192     points[0] = cubics[kTopP0_CubicCtrlPts];
193     points[1] = cubics[kTopP1_CubicCtrlPts];
194     points[2] = cubics[kTopP2_CubicCtrlPts];
195     points[3] = cubics[kTopP3_CubicCtrlPts];
196 }
197 
GetBottomCubic(const SkPoint cubics[12],SkPoint points[4])198 void SkPatchUtils::GetBottomCubic(const SkPoint cubics[12], SkPoint points[4]) {
199     points[0] = cubics[kBottomP0_CubicCtrlPts];
200     points[1] = cubics[kBottomP1_CubicCtrlPts];
201     points[2] = cubics[kBottomP2_CubicCtrlPts];
202     points[3] = cubics[kBottomP3_CubicCtrlPts];
203 }
204 
GetLeftCubic(const SkPoint cubics[12],SkPoint points[4])205 void SkPatchUtils::GetLeftCubic(const SkPoint cubics[12], SkPoint points[4]) {
206     points[0] = cubics[kLeftP0_CubicCtrlPts];
207     points[1] = cubics[kLeftP1_CubicCtrlPts];
208     points[2] = cubics[kLeftP2_CubicCtrlPts];
209     points[3] = cubics[kLeftP3_CubicCtrlPts];
210 }
211 
GetRightCubic(const SkPoint cubics[12],SkPoint points[4])212 void SkPatchUtils::GetRightCubic(const SkPoint cubics[12], SkPoint points[4]) {
213     points[0] = cubics[kRightP0_CubicCtrlPts];
214     points[1] = cubics[kRightP1_CubicCtrlPts];
215     points[2] = cubics[kRightP2_CubicCtrlPts];
216     points[3] = cubics[kRightP3_CubicCtrlPts];
217 }
218 
skcolor_to_float(SkPMColor4f * dst,const SkColor * src,int count,SkColorSpace * dstCS)219 static void skcolor_to_float(SkPMColor4f* dst, const SkColor* src, int count, SkColorSpace* dstCS) {
220     SkImageInfo srcInfo = SkImageInfo::Make(count, 1, kBGRA_8888_SkColorType,
221                                             kUnpremul_SkAlphaType, SkColorSpace::MakeSRGB());
222     SkImageInfo dstInfo = SkImageInfo::Make(count, 1, kRGBA_F32_SkColorType,
223                                             kPremul_SkAlphaType, sk_ref_sp(dstCS));
224     SkConvertPixels(dstInfo, dst, 0, srcInfo, src, 0);
225 }
226 
float_to_skcolor(SkColor * dst,const SkPMColor4f * src,int count,SkColorSpace * srcCS)227 static void float_to_skcolor(SkColor* dst, const SkPMColor4f* src, int count, SkColorSpace* srcCS) {
228     SkImageInfo srcInfo = SkImageInfo::Make(count, 1, kRGBA_F32_SkColorType,
229                                             kPremul_SkAlphaType, sk_ref_sp(srcCS));
230     SkImageInfo dstInfo = SkImageInfo::Make(count, 1, kBGRA_8888_SkColorType,
231                                             kUnpremul_SkAlphaType, SkColorSpace::MakeSRGB());
232     SkConvertPixels(dstInfo, dst, 0, srcInfo, src, 0);
233 }
234 
MakeVertices(const SkPoint cubics[12],const SkColor srcColors[4],const SkPoint srcTexCoords[4],int lodX,int lodY,SkColorSpace * colorSpace)235 sk_sp<SkVertices> SkPatchUtils::MakeVertices(const SkPoint cubics[12], const SkColor srcColors[4],
236                                              const SkPoint srcTexCoords[4], int lodX, int lodY,
237                                              SkColorSpace* colorSpace) {
238     if (lodX < 1 || lodY < 1 || nullptr == cubics) {
239         return nullptr;
240     }
241 
242     // check for overflow in multiplication
243     const int64_t lodX64 = (lodX + 1),
244     lodY64 = (lodY + 1),
245     mult64 = lodX64 * lodY64;
246     if (mult64 > SK_MaxS32) {
247         return nullptr;
248     }
249 
250     // Treat null interpolation space as sRGB.
251     if (!colorSpace) {
252         colorSpace = sk_srgb_singleton();
253     }
254 
255     int vertexCount = SkToS32(mult64);
256     // it is recommended to generate draw calls of no more than 65536 indices, so we never generate
257     // more than 60000 indices. To accomplish that we resize the LOD and vertex count
258     if (vertexCount > 10000 || lodX > 200 || lodY > 200) {
259         float weightX = static_cast<float>(lodX) / (lodX + lodY);
260         float weightY = static_cast<float>(lodY) / (lodX + lodY);
261 
262         // 200 comes from the 100 * 2 which is the max value of vertices because of the limit of
263         // 60000 indices ( sqrt(60000 / 6) that comes from data->fIndexCount = lodX * lodY * 6)
264         // Need a min of 1 since we later divide by lod
265         lodX = std::max(1, sk_float_floor2int_no_saturate(weightX * 200));
266         lodY = std::max(1, sk_float_floor2int_no_saturate(weightY * 200));
267         vertexCount = (lodX + 1) * (lodY + 1);
268     }
269     const int indexCount = lodX * lodY * 6;
270     uint32_t flags = 0;
271     if (srcTexCoords) {
272         flags |= SkVertices::kHasTexCoords_BuilderFlag;
273     }
274     if (srcColors) {
275         flags |= SkVertices::kHasColors_BuilderFlag;
276     }
277 
278     SkSTArenaAlloc<2048> alloc;
279     SkPMColor4f* cornerColors = srcColors ? alloc.makeArray<SkPMColor4f>(4) : nullptr;
280     SkPMColor4f* tmpColors = srcColors ? alloc.makeArray<SkPMColor4f>(vertexCount) : nullptr;
281 
282     SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, indexCount, flags);
283     SkPoint* pos = builder.positions();
284     SkPoint* texs = builder.texCoords();
285     uint16_t* indices = builder.indices();
286 
287     if (cornerColors) {
288         skcolor_to_float(cornerColors, srcColors, kNumCorners, colorSpace);
289     }
290 
291     SkPoint pts[kNumPtsCubic];
292     SkPatchUtils::GetBottomCubic(cubics, pts);
293     FwDCubicEvaluator fBottom(pts);
294     SkPatchUtils::GetTopCubic(cubics, pts);
295     FwDCubicEvaluator fTop(pts);
296     SkPatchUtils::GetLeftCubic(cubics, pts);
297     FwDCubicEvaluator fLeft(pts);
298     SkPatchUtils::GetRightCubic(cubics, pts);
299     FwDCubicEvaluator fRight(pts);
300 
301     fBottom.restart(lodX);
302     fTop.restart(lodX);
303 
304     SkScalar u = 0.0f;
305     int stride = lodY + 1;
306     for (int x = 0; x <= lodX; x++) {
307         SkPoint bottom = fBottom.next(), top = fTop.next();
308         fLeft.restart(lodY);
309         fRight.restart(lodY);
310         SkScalar v = 0.f;
311         for (int y = 0; y <= lodY; y++) {
312             int dataIndex = x * (lodY + 1) + y;
313 
314             SkPoint left = fLeft.next(), right = fRight.next();
315 
316             SkPoint s0 = SkPoint::Make((1.0f - v) * top.x() + v * bottom.x(),
317                                        (1.0f - v) * top.y() + v * bottom.y());
318             SkPoint s1 = SkPoint::Make((1.0f - u) * left.x() + u * right.x(),
319                                        (1.0f - u) * left.y() + u * right.y());
320             SkPoint s2 = SkPoint::Make(
321                                        (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].x()
322                                                      + u * fTop.getCtrlPoints()[3].x())
323                                        + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].x()
324                                               + u * fBottom.getCtrlPoints()[3].x()),
325                                        (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].y()
326                                                      + u * fTop.getCtrlPoints()[3].y())
327                                        + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].y()
328                                               + u * fBottom.getCtrlPoints()[3].y()));
329             pos[dataIndex] = s0 + s1 - s2;
330 
331             if (cornerColors) {
332                 bilerp(u, v, Sk4f::Load(cornerColors[kTopLeft_Corner].vec()),
333                              Sk4f::Load(cornerColors[kTopRight_Corner].vec()),
334                              Sk4f::Load(cornerColors[kBottomLeft_Corner].vec()),
335                              Sk4f::Load(cornerColors[kBottomRight_Corner].vec()))
336                     .store(tmpColors[dataIndex].vec());
337             }
338 
339             if (texs) {
340                 texs[dataIndex] = SkPoint::Make(bilerp(u, v, srcTexCoords[kTopLeft_Corner].x(),
341                                                        srcTexCoords[kTopRight_Corner].x(),
342                                                        srcTexCoords[kBottomLeft_Corner].x(),
343                                                        srcTexCoords[kBottomRight_Corner].x()),
344                                                 bilerp(u, v, srcTexCoords[kTopLeft_Corner].y(),
345                                                        srcTexCoords[kTopRight_Corner].y(),
346                                                        srcTexCoords[kBottomLeft_Corner].y(),
347                                                        srcTexCoords[kBottomRight_Corner].y()));
348 
349             }
350 
351             if(x < lodX && y < lodY) {
352                 int i = 6 * (x * lodY + y);
353                 indices[i] = x * stride + y;
354                 indices[i + 1] = x * stride + 1 + y;
355                 indices[i + 2] = (x + 1) * stride + 1 + y;
356                 indices[i + 3] = indices[i];
357                 indices[i + 4] = indices[i + 2];
358                 indices[i + 5] = (x + 1) * stride + y;
359             }
360             v = SkTPin(v + 1.f / lodY, 0.0f, 1.0f);
361         }
362         u = SkTPin(u + 1.f / lodX, 0.0f, 1.0f);
363     }
364 
365     if (tmpColors) {
366         float_to_skcolor(builder.colors(), tmpColors, vertexCount, colorSpace);
367     }
368     return builder.detach();
369 }
370