SkPoint3.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2015 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/SkPoint3.h"
  8. // Returns the square of the Euclidian distance to (x,y,z).
  9. static inline float get_length_squared(float x, float y, float z) {
  10. return x * x + y * y + z * z;
  11. }
  12. // Calculates the square of the Euclidian distance to (x,y,z) and stores it in
  13. // *lengthSquared. Returns true if the distance is judged to be "nearly zero".
  14. //
  15. // This logic is encapsulated in a helper method to make it explicit that we
  16. // always perform this check in the same manner, to avoid inconsistencies
  17. // (see http://code.google.com/p/skia/issues/detail?id=560 ).
  18. static inline bool is_length_nearly_zero(float x, float y, float z, float *lengthSquared) {
  19. *lengthSquared = get_length_squared(x, y, z);
  20. return *lengthSquared <= (SK_ScalarNearlyZero * SK_ScalarNearlyZero);
  21. }
  22. SkScalar SkPoint3::Length(SkScalar x, SkScalar y, SkScalar z) {
  23. float magSq = get_length_squared(x, y, z);
  24. if (SkScalarIsFinite(magSq)) {
  25. return sk_float_sqrt(magSq);
  26. } else {
  27. double xx = x;
  28. double yy = y;
  29. double zz = z;
  30. return (float)sqrt(xx * xx + yy * yy + zz * zz);
  31. }
  32. }
  33. /*
  34. * We have to worry about 2 tricky conditions:
  35. * 1. underflow of magSq (compared against nearlyzero^2)
  36. * 2. overflow of magSq (compared w/ isfinite)
  37. *
  38. * If we underflow, we return false. If we overflow, we compute again using
  39. * doubles, which is much slower (3x in a desktop test) but will not overflow.
  40. */
  41. bool SkPoint3::normalize() {
  42. float magSq;
  43. if (is_length_nearly_zero(fX, fY, fZ, &magSq)) {
  44. this->set(0, 0, 0);
  45. return false;
  46. }
  47. // sqrtf does not provide enough precision; since sqrt takes a double,
  48. // there's no additional penalty to storing invScale in a double
  49. double invScale;
  50. if (sk_float_isfinite(magSq)) {
  51. invScale = magSq;
  52. } else {
  53. // our magSq step overflowed to infinity, so use doubles instead.
  54. // much slower, but needed when x, y or z is very large, otherwise we
  55. // divide by inf. and return (0,0,0) vector.
  56. double xx = fX;
  57. double yy = fY;
  58. double zz = fZ;
  59. invScale = xx * xx + yy * yy + zz * zz;
  60. }
  61. // using a float instead of a double for scale loses too much precision
  62. double scale = 1 / sqrt(invScale);
  63. fX *= scale;
  64. fY *= scale;
  65. fZ *= scale;
  66. if (!sk_float_isfinite(fX) || !sk_float_isfinite(fY) || !sk_float_isfinite(fZ)) {
  67. this->set(0, 0, 0);
  68. return false;
  69. }
  70. return true;
  71. }