Quaternion.java 1.7 KB

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