Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ui / gfx / geometry / vector3d_f.cc
blob87223880669ed51a4bd15cc1302d31a14d16a4fa
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.
5 #include "ui/gfx/geometry/vector3d_f.h"
7 #include <cmath>
9 #include "base/strings/stringprintf.h"
11 namespace {
12 const float kRadiansToDegrees = 180.0f / 3.14159265f;
15 namespace gfx {
17 Vector3dF::Vector3dF()
18 : x_(0),
19 y_(0),
20 z_(0) {
23 Vector3dF::Vector3dF(float x, float y, float z)
24 : x_(x),
25 y_(y),
26 z_(z) {
29 Vector3dF::Vector3dF(const Vector2dF& other)
30 : x_(other.x()),
31 y_(other.y()),
32 z_(0) {
35 std::string Vector3dF::ToString() const {
36 return base::StringPrintf("[%f %f %f]", x_, y_, z_);
39 bool Vector3dF::IsZero() const {
40 return x_ == 0 && y_ == 0 && z_ == 0;
43 void Vector3dF::Add(const Vector3dF& other) {
44 x_ += other.x_;
45 y_ += other.y_;
46 z_ += other.z_;
49 void Vector3dF::Subtract(const Vector3dF& other) {
50 x_ -= other.x_;
51 y_ -= other.y_;
52 z_ -= other.z_;
55 double Vector3dF::LengthSquared() const {
56 return static_cast<double>(x_) * x_ + static_cast<double>(y_) * y_ +
57 static_cast<double>(z_) * z_;
60 float Vector3dF::Length() const {
61 return static_cast<float>(std::sqrt(LengthSquared()));
64 void Vector3dF::Scale(float x_scale, float y_scale, float z_scale) {
65 x_ *= x_scale;
66 y_ *= y_scale;
67 z_ *= z_scale;
70 void Vector3dF::Cross(const Vector3dF& other) {
71 float x = y_ * other.z() - z_ * other.y();
72 float y = z_ * other.x() - x_ * other.z();
73 float z = x_ * other.y() - y_ * other.x();
74 x_ = x;
75 y_ = y;
76 z_ = z;
79 float DotProduct(const Vector3dF& lhs, const Vector3dF& rhs) {
80 return lhs.x() * rhs.x() + lhs.y() * rhs.y() + lhs.z() * rhs.z();
83 Vector3dF ScaleVector3d(const Vector3dF& v,
84 float x_scale,
85 float y_scale,
86 float z_scale) {
87 Vector3dF scaled_v(v);
88 scaled_v.Scale(x_scale, y_scale, z_scale);
89 return scaled_v;
92 float AngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
93 const gfx::Vector3dF& other) {
94 return acos(gfx::DotProduct(base, other) / base.Length() / other.Length()) *
95 kRadiansToDegrees;
98 float ClockwiseAngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
99 const gfx::Vector3dF& other,
100 const gfx::Vector3dF& normal) {
101 float angle = AngleBetweenVectorsInDegrees(base, other);
102 gfx::Vector3dF cross(base);
103 cross.Cross(other);
105 // If the dot product of this cross product is normal, it means that the
106 // shortest angle between |base| and |other| was counterclockwise with respect
107 // to the surface represented by |normal| and this angle must be reversed.
108 if (gfx::DotProduct(cross, normal) > 0.0f)
109 angle = 360.0f - angle;
110 return angle;
113 } // namespace gfx