1 /*
2 * Copyright 2018 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 "SkCubicMap.h"
9 #include "SkGeometry.h"
10 #include "SkRandom.h"
11 #include "Test.h"
12 #include "../../src/pathops/SkPathOpsCubic.h"
13
accurate_t(float A,float B,float C,float D)14 static float accurate_t(float A, float B, float C, float D) {
15 double roots[3];
16 SkDEBUGCODE(int count =) SkDCubic::RootsValidT(A, B, C, D, roots);
17 SkASSERT(count == 1);
18 return (float)roots[0];
19 }
20
accurate_solve(SkPoint p1,SkPoint p2,SkScalar x)21 static float accurate_solve(SkPoint p1, SkPoint p2, SkScalar x) {
22 SkPoint array[] = { {0, 0}, p1, p2, {1,1} };
23 SkCubicCoeff coeff(array);
24
25 float t = accurate_t(coeff.fA[0], coeff.fB[0], coeff.fC[0], coeff.fD[0] - x);
26 SkASSERT(t >= 0 && t <= 1);
27 float y = coeff.eval(t)[1];
28 SkASSERT(y >= 0 && y <= 1.0001f);
29 return y;
30 }
31
nearly_le(SkScalar a,SkScalar b)32 static bool nearly_le(SkScalar a, SkScalar b) {
33 return a <= b || SkScalarNearlyZero(a - b);
34 }
35
exercise_cubicmap(SkPoint p1,SkPoint p2,skiatest::Reporter * reporter)36 static void exercise_cubicmap(SkPoint p1, SkPoint p2, skiatest::Reporter* reporter) {
37 const SkScalar MAX_SOLVER_ERR = 0.008f; // found by running w/ current impl
38
39 SkCubicMap cmap(p1, p2);
40
41 SkScalar prev_y = 0;
42 SkScalar dx = 1.0f / 512;
43 for (SkScalar x = dx; x < 1; x += dx) {
44 SkScalar y = cmap.computeYFromX(x);
45 // are we valid and (mostly) monotonic?
46 if (y < 0 || y > 1 || !nearly_le(prev_y, y)) {
47 cmap.computeYFromX(x);
48 REPORTER_ASSERT(reporter, false);
49 }
50 prev_y = y;
51
52 // are we close to the "correct" answer?
53 SkScalar yy = accurate_solve(p1, p2, x);
54 SkScalar diff = SkScalarAbs(yy - y);
55 REPORTER_ASSERT(reporter, diff < MAX_SOLVER_ERR);
56 }
57 }
58
DEF_TEST(CubicMap,r)59 DEF_TEST(CubicMap, r) {
60 const SkScalar values[] = {
61 0, 1, 0.5f, 0.0000001f, 0.999999f,
62 };
63
64 for (SkScalar x0 : values) {
65 for (SkScalar y0 : values) {
66 for (SkScalar x1 : values) {
67 for (SkScalar y1 : values) {
68 exercise_cubicmap({ x0, y0 }, { x1, y1 }, r);
69 }
70 }
71 }
72 }
73 }
74