Quaternion.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
  2. public class Quaternion {
  3. public float w, x, y, z;
  4. Quaternion() { // identity
  5. w = 1.0f; x = y = z = 0.0f;
  6. }
  7. Quaternion(float w, float x, float y, float z) {
  8. this.w = w;
  9. this.x = x;
  10. this.y = y;
  11. this.z = z;
  12. }
  13. public Quaternion clone() {
  14. return new Quaternion(w, x, y, z);
  15. }
  16. public Quaternion multiply(final Quaternion p) {
  17. Quaternion q = this;
  18. return new Quaternion(
  19. q.w * p.w - q.x * p.x - q.y * p.y - q.z * p.z,
  20. q.w * p.x + q.x * p.w + q.y * p.z - q.z * p.y,
  21. q.w * p.y + q.y * p.w + q.z * p.x - q.x * p.z,
  22. q.w * p.z + q.z * p.w + q.x * p.y - q.y * p.x);
  23. }
  24. public static float[] cross(final float[] v1, final float[] v2) {
  25. float[] v3 = new float[3];
  26. v3[0] = v1[1] * v2[2] - v1[2] * v2[1];
  27. v3[1] = v1[2] * v2[0] - v1[0] * v2[2];
  28. v3[2] = v1[0] * v2[1] - v1[1] * v2[0];
  29. return v3;
  30. }
  31. public static float[] multiply(final float s, final float[] v) {
  32. float[] result = new float[3];
  33. result[0] = s * v[0];
  34. result[1] = s * v[1];
  35. result[2] = s * v[2];
  36. return result;
  37. }
  38. public static float[] add(final float[] v1, final float[] v2) {
  39. float[] v3 = new float[3];
  40. v3[0] = v1[0] + v2[0];
  41. v3[1] = v1[1] + v2[1];
  42. v3[2] = v1[2] + v2[2];
  43. return v3;
  44. }
  45. public float[] multiply(final float[] v) { // rotate a point
  46. Quaternion q = this;
  47. float[] axis = new float[3];
  48. axis[0] = q.x; axis[1] = q.y; axis[2] = q.z;
  49. float[] uv = cross(axis, v);
  50. float[] uuv = cross(axis, uv);
  51. uv = multiply(2.0f * q.w, uv);
  52. uuv = multiply(2.0f, uuv);
  53. return add(v, add(uv, uuv));
  54. }
  55. }