001/*----------------------------------------------------------------------------*/
002/* Copyright (c) 2017-2018 FIRST. All Rights Reserved.                        */
003/* Open Source Software - may be modified and shared by FRC teams. The code   */
004/* must be accompanied by the FIRST BSD license file in the root directory of */
005/* the project.                                                               */
006/*----------------------------------------------------------------------------*/
007
008package edu.wpi.first.wpilibj.drive;
009
010/**
011 * This is a 2D vector struct that supports basic vector operations.
012 */
013@SuppressWarnings("MemberName")
014public class Vector2d {
015  public double x = 0.0;
016  public double y = 0.0;
017
018  public Vector2d() {}
019
020  @SuppressWarnings("ParameterName")
021  public Vector2d(double x, double y) {
022    this.x = x;
023    this.y = y;
024  }
025
026  /**
027   * Rotate a vector in Cartesian space.
028   *
029   * @param angle angle in degrees by which to rotate vector counter-clockwise.
030   */
031  public void rotate(double angle) {
032    double cosA = Math.cos(angle * (Math.PI / 180.0));
033    double sinA = Math.sin(angle * (Math.PI / 180.0));
034    double[] out = new double[2];
035    out[0] = x * cosA - y * sinA;
036    out[1] = x * sinA + y * cosA;
037    x = out[0];
038    y = out[1];
039  }
040
041  /**
042   * Returns dot product of this vector with argument.
043   *
044   * @param vec Vector with which to perform dot product.
045   */
046  public double dot(Vector2d vec) {
047    return x * vec.x + y * vec.y;
048  }
049
050  /**
051   * Returns magnitude of vector.
052   */
053  public double magnitude() {
054    return Math.sqrt(x * x + y * y);
055  }
056
057  /**
058   * Returns scalar projection of this vector onto argument.
059   *
060   * @param vec Vector onto which to project this vector.
061   */
062  public double scalarProject(Vector2d vec) {
063    return dot(vec) / vec.magnitude();
064  }
065}