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