Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

vec2.h (1470B) · raw


      1 /// @file core/vec2.h
      2 /// @brief Two-dimensional fixed-point vector for the simulation.
      3 #pragma once
      4 
      5 #include "core/fixed.h"
      6 
      7 namespace kumo {
      8 
      9 /// @brief A 2D position, offset, or velocity in 16.16 fixed point.
     10 struct Vec2 {
     11   Fixed x;
     12   Fixed y;
     13 
     14   /// @brief The zero vector (0, 0).
     15   static constexpr Vec2 zero() { return {}; }
     16 
     17   /// @brief A vector from whole integer coordinates.
     18   static constexpr Vec2 from_ints(int x, int y) {
     19     return {Fixed::from_int(x), Fixed::from_int(y)};
     20   }
     21 
     22   constexpr Vec2 operator-() const { return {-x, -y}; }
     23   constexpr Vec2 operator+(Vec2 other) const {
     24     return {x + other.x, y + other.y};
     25   }
     26   constexpr Vec2 operator-(Vec2 other) const {
     27     return {x - other.x, y - other.y};
     28   }
     29   constexpr Vec2 operator*(Fixed scalar) const {
     30     return {x * scalar, y * scalar};
     31   }
     32 
     33   constexpr Vec2& operator+=(Vec2 other) {
     34     x += other.x;
     35     y += other.y;
     36     return *this;
     37   }
     38   constexpr Vec2& operator-=(Vec2 other) {
     39     x -= other.x;
     40     y -= other.y;
     41     return *this;
     42   }
     43   constexpr Vec2& operator*=(Fixed scalar) {
     44     x = x * scalar;
     45     y = y * scalar;
     46     return *this;
     47   }
     48 
     49   constexpr bool operator==(const Vec2&) const = default;
     50 };
     51 
     52 constexpr Vec2 operator*(Fixed scalar, Vec2 vector) { return vector * scalar; }
     53 
     54 /// @brief Component-wise linear interpolation from @p a to @p b at @p t.
     55 constexpr Vec2 lerp(Vec2 a, Vec2 b, Fixed t) {
     56   return {lerp(a.x, b.x, t), lerp(a.y, b.y, t)};
     57 }
     58 
     59 }  // namespace kumo