vector4.vala 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. using Gee;
  6. namespace Crown
  7. {
  8. [Compact]
  9. public struct Vector4
  10. {
  11. public double x;
  12. public double y;
  13. public double z;
  14. public double w;
  15. public Vector4(double x, double y, double z, double w)
  16. {
  17. this.x = x;
  18. this.y = y;
  19. this.z = z;
  20. this.w = w;
  21. }
  22. public Vector4.from_array(ArrayList<Value?> arr)
  23. {
  24. this.x = (double)arr[0];
  25. this.y = (double)arr[1];
  26. this.z = (double)arr[2];
  27. this.w = (double)arr[3];
  28. }
  29. public ArrayList<Value?> to_array()
  30. {
  31. ArrayList<Value?> arr = new ArrayList<Value?>();
  32. arr.add(this.x);
  33. arr.add(this.y);
  34. arr.add(this.z);
  35. arr.add(this.w);
  36. return arr;
  37. }
  38. public double dot(Vector4 b)
  39. {
  40. return this.x * b.x + this.y * b.y + this.z * b.z + this.w * b.w;
  41. }
  42. public double length_squared()
  43. {
  44. return dot(this);
  45. }
  46. public double length()
  47. {
  48. return Math.sqrt(length_squared());
  49. }
  50. public void normalize()
  51. {
  52. double len = length();
  53. double inv_len = 1.0 / len;
  54. this.x *= inv_len;
  55. this.y *= inv_len;
  56. this.z *= inv_len;
  57. this.w *= inv_len;
  58. }
  59. public void set_length(double len)
  60. {
  61. normalize();
  62. this.x *= len;
  63. this.y *= len;
  64. this.z *= len;
  65. this.w *= len;
  66. }
  67. public Vector3 to_vector3()
  68. {
  69. return Vector3(this.x, this.y, this.z);
  70. }
  71. public string to_string()
  72. {
  73. return "%f, %f, %f, %f".printf(x, y, z, w);
  74. }
  75. }
  76. public const Vector4 VECTOR4_ZERO = { 0.0, 0.0, 0.0, 0.0 };
  77. public const Vector4 VECTOR4_ONE = { 1.0, 1.0, 1.0, 1.0 };
  78. } /* namespace Crown */