StarShadow

My Quaternion class

Jun 21st, 2017 (edited)
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import org.bukkit.util.Vector;
  2.  
  3. public class Quaternion {
  4.    
  5.     private final double w, x, y, z;
  6.    
  7.     public Quaternion(double w, double x, double y, double z) {
  8.         this.w = w;
  9.         this.x = x;
  10.         this.y = y;
  11.         this.z = z;
  12.     }
  13.    
  14.     // Rotate a vector using a rotation quaternion.
  15.     public static Vector rotate(Vector vector, Quaternion r) {
  16.         return r.mul(Quaternion.from(vector)).mul(r.inverse()).toVector();
  17.     }
  18.    
  19.     // Rotate a vector theta degrees around an axis.
  20.     public static Vector rotate(Vector vector, Vector axis, double deg) {
  21.         return Quaternion.rotate(vector, Quaternion.rotation(deg, axis));
  22.     }
  23.    
  24.     // Create quaternion from a vector.
  25.     public static Quaternion from(Vector vector) {
  26.         return new Quaternion(0, vector.getX(), vector.getY(), vector.getZ());
  27.     }
  28.    
  29.     // Create a rotation quaternion from theta and an axis.
  30.     public static Quaternion rotation(double deg, Vector axis) {
  31.         axis = axis.normalize();
  32.         deg = Math.toRadians(deg / 2);
  33.         double sd = Math.sin(deg);
  34.         return new Quaternion(Math.cos(deg), axis.getX() * sd, axis.getY() * sd, axis.getZ() * sd);
  35.     }
  36.    
  37.     public Vector toVector() {
  38.         return new Vector(x, y, z);
  39.     }
  40.    
  41.     public Quaternion inverse() {
  42.         double l = w*w + x*x + y*y + z*z;
  43.         return new Quaternion(w/l, -x/l, -y/l, -z/l);
  44.     }
  45.    
  46.     public Quaternion conjugate() {
  47.         return new Quaternion(w, -x, -y, -z);
  48.     }
  49.    
  50.     // Multiply this quaternion and another.
  51.     // Returns the Hamilton product of this quaternion and r.
  52.     public Quaternion mul(Quaternion r) {
  53.         double n0 = r.w*w - r.x*x - r.y*y - r.z*z;
  54.         double n1 = r.w*x + r.x*w + r.y*z - r.z*y;
  55.         double n2 = r.w*y - r.x*z + r.y*w + r.z*x;
  56.         double n3 = r.w*z + r.x*y - r.y*x + r.z*w;
  57.         return new Quaternion(n0, n1, n2, n3);
  58.     }
  59.    
  60.     public double getW() {
  61.         return w;
  62.     }
  63.    
  64.     public double getX() {
  65.         return x;
  66.     }
  67.    
  68.     public double getY() {
  69.         return y;
  70.     }
  71.    
  72.     public double getZ() {
  73.         return z;
  74.     }
  75. }
Add Comment
Please, Sign In to add comment