CubicMapTest.cpp 2.1 KB

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