vector2d_f.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/gfx/geometry/vector2d_f.h"
  5. #include <cmath>
  6. #include "base/strings/stringprintf.h"
  7. #include "build/build_config.h"
  8. namespace gfx {
  9. std::string Vector2dF::ToString() const {
  10. return base::StringPrintf("[%g %g]", x_, y_);
  11. }
  12. bool Vector2dF::IsZero() const {
  13. return x_ == 0 && y_ == 0;
  14. }
  15. void Vector2dF::Add(const Vector2dF& other) {
  16. x_ += other.x_;
  17. y_ += other.y_;
  18. }
  19. void Vector2dF::Subtract(const Vector2dF& other) {
  20. x_ -= other.x_;
  21. y_ -= other.y_;
  22. }
  23. double Vector2dF::LengthSquared() const {
  24. return static_cast<double>(x_) * x_ + static_cast<double>(y_) * y_;
  25. }
  26. float Vector2dF::Length() const {
  27. return hypotf(x_, y_);
  28. }
  29. void Vector2dF::Scale(float x_scale, float y_scale) {
  30. x_ *= x_scale;
  31. y_ *= y_scale;
  32. }
  33. double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs) {
  34. return static_cast<double>(lhs.x()) * rhs.y() -
  35. static_cast<double>(lhs.y()) * rhs.x();
  36. }
  37. double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs) {
  38. return static_cast<double>(lhs.x()) * rhs.x() +
  39. static_cast<double>(lhs.y()) * rhs.y();
  40. }
  41. Vector2dF ScaleVector2d(const Vector2dF& v, float x_scale, float y_scale) {
  42. Vector2dF scaled_v(v);
  43. scaled_v.Scale(x_scale, y_scale);
  44. return scaled_v;
  45. }
  46. float Vector2dF::SlopeAngleRadians() const {
  47. #if BUILDFLAG(IS_MAC)
  48. // atan2f(...) returns less accurate results on Mac.
  49. // 3.1415925 vs. 3.14159274 for atan2f(0, -50) as an example.
  50. return static_cast<float>(
  51. atan2(static_cast<double>(y_), static_cast<double>(x_)));
  52. #else
  53. return atan2f(y_, x_);
  54. #endif
  55. }
  56. } // namespace gfx