💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.3 KiB

  1. /*
  2. * Copyright (C) 2023 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <engine/ai/steering/behavior/wander.hpp>
  20. #include <engine/ai/steering/behavior/seek.hpp>
  21. #include <engine/math/random.hpp>
  22. #include <engine/math/quaternion.hpp>
  23. namespace ai {
  24. namespace steering {
  25. namespace behavior {
  26. float3 wander_2d(const agent& agent, float noise, float distance, float radius, float& angle)
  27. {
  28. // Shift wander angle
  29. angle += math::random(-noise, noise);
  30. // Calculate center of wander circle
  31. const float3 center = agent.position + agent.forward * distance;
  32. // Decompose orientation into swing and twist rotations
  33. math::quaternion<float> swing, twist;
  34. math::swing_twist(agent.orientation, agent.up, swing, twist);
  35. // Calculate offset to point on wander circle
  36. const float3 offset = math::conjugate(twist) * (math::angle_axis(angle, agent.up) * agent.forward * radius);
  37. // Seek toward point on wander circle
  38. return seek(agent, center + offset);
  39. }
  40. float3 wander_3d(const agent& agent, float noise, float distance, float radius, float& theta, float& phi)
  41. {
  42. // Shift wander angles
  43. theta += math::random(-noise, noise);
  44. phi += math::random(-noise, noise);
  45. // Calculate center of wander sphere
  46. const float3 center = agent.position + agent.forward * distance;
  47. // Convert spherical coordinates to Cartesian point on wander sphere
  48. const float r_cos_theta = radius * std::cos(theta);
  49. const float3 offset =
  50. {
  51. r_cos_theta * std::cos(phi),
  52. r_cos_theta * std::sin(phi),
  53. radius * std::sin(theta)
  54. };
  55. // Seek toward point on wander sphere
  56. return seek(agent, center + offset);
  57. }
  58. } // namespace behavior
  59. } // namespace steering
  60. } // namespace ai