blob: ff4aae445b745131eddac550ac6624b52d34b83f [file] [log] [blame]
Mike Reed0d4a1832018-08-14 17:21:23 -04001/*
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"
Mike Reed340818e2018-08-15 17:12:08 -04009#include "SkGeometry.h"
Mike Reed0d4a1832018-08-14 17:21:23 -040010#include "SkRandom.h"
11#include "Test.h"
Mike Reed340818e2018-08-15 17:12:08 -040012#include "../../src/pathops/SkPathOpsCubic.h"
13
14static 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
21static 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}
Mike Reed0d4a1832018-08-14 17:21:23 -040031
32static bool nearly_le(SkScalar a, SkScalar b) {
33 return a <= b || SkScalarNearlyZero(a - b);
34}
35
Mike Reed340818e2018-08-15 17:12:08 -040036static 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
Mike Reed0d4a1832018-08-14 17:21:23 -040041 SkScalar prev_y = 0;
Mike Reed340818e2018-08-15 17:12:08 -040042 SkScalar dx = 1.0f / 512;
43 for (SkScalar x = dx; x < 1; x += dx) {
Mike Reed0d4a1832018-08-14 17:21:23 -040044 SkScalar y = cmap.computeYFromX(x);
Mike Reed340818e2018-08-15 17:12:08 -040045 // are we valid and (mostly) monotonic?
Mike Reed0d4a1832018-08-14 17:21:23 -040046 if (y < 0 || y > 1 || !nearly_le(prev_y, y)) {
47 cmap.computeYFromX(x);
48 REPORTER_ASSERT(reporter, false);
49 }
50 prev_y = y;
Mike Reed340818e2018-08-15 17:12:08 -040051
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);
Mike Reed0d4a1832018-08-14 17:21:23 -040056 }
57}
58
59DEF_TEST(CubicMap, r) {
60 const SkScalar values[] = {
Mike Reed340818e2018-08-15 17:12:08 -040061 0, 1, 0.5f, 0.0000001f, 0.999999f,
Mike Reed0d4a1832018-08-14 17:21:23 -040062 };
63
64 for (SkScalar x0 : values) {
65 for (SkScalar y0 : values) {
66 for (SkScalar x1 : values) {
67 for (SkScalar y1 : values) {
Mike Reed340818e2018-08-15 17:12:08 -040068 exercise_cubicmap({ x0, y0 }, { x1, y1 }, r);
Mike Reed0d4a1832018-08-14 17:21:23 -040069 }
70 }
71 }
72 }
73}