vector3.vala 1.6 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 Vector3
  10. {
  11. public double x;
  12. public double y;
  13. public double z;
  14. public Vector3(double x, double y, double z)
  15. {
  16. this.x = x;
  17. this.y = y;
  18. this.z = z;
  19. }
  20. public Vector3.from_array(ArrayList<Value?> arr)
  21. {
  22. this.x = (double)arr[0];
  23. this.y = (double)arr[1];
  24. this.z = (double)arr[2];
  25. }
  26. public ArrayList<Value?> to_array()
  27. {
  28. ArrayList<Value?> arr = new ArrayList<Value?>();
  29. arr.add(this.x);
  30. arr.add(this.y);
  31. arr.add(this.z);
  32. return arr;
  33. }
  34. public double dot(Vector3 b)
  35. {
  36. return this.x * b.x + this.y * b.y + this.z * b.z;
  37. }
  38. public Vector3 cross(Vector3 b)
  39. {
  40. return Vector3(this.y * b.z - this.z * b.y
  41. , this.z * b.x - this.x * b.z
  42. , this.x * b.y - this.y * b.x
  43. );
  44. }
  45. public double length_squared()
  46. {
  47. return dot(this);
  48. }
  49. public double length()
  50. {
  51. return Math.sqrt(length_squared());
  52. }
  53. public Vector3 normalize()
  54. {
  55. double len = length();
  56. double inv_len = 1.0 / len;
  57. this.x *= inv_len;
  58. this.y *= inv_len;
  59. this.z *= inv_len;
  60. return this;
  61. }
  62. public void set_length(double len)
  63. {
  64. normalize();
  65. this.x *= len;
  66. this.y *= len;
  67. this.z *= len;
  68. }
  69. public string to_string()
  70. {
  71. return "%f, %f, %f".printf(x, y, z);
  72. }
  73. }
  74. public const Vector3 VECTOR3_ZERO = { 0.0, 0.0, 0.0 };
  75. public const Vector3 VECTOR3_ONE = { 1.0, 1.0, 1.0 };
  76. public const Vector3 VECTOR3_MIN = {-double.MAX, -double.MAX, -double.MAX };
  77. public const Vector3 VECTOR3_MAX = { double.MAX, double.MAX, double.MAX };
  78. } /* namespace Crown */