# base/math (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/base/math/

수학 보조 함수. (원본 base/math.js)
- 수는 원본 자바스크립트 수처럼 f64 다. random_int 만 i32 다.
- 원본의 floor, ceil, sqrt, abs, sin, cos, tan, asin, acos, pow 를 같은 이름의 함수로 둔다. (쓰는 코드가 원본과 같게)
  sin, cos, tan 은 원본처럼 크롬 Math.sin, cos, tan 과 같은 셈(바르게 반올림한 f64, base/trigonometry.rs)이다. (시스템 libm 은 플랫폼마다 끝자리가 다르다)
  round 는 반을 +무한대 쪽으로 올리는 점(-2.5 → -2)이 f64::round(-2.5 → -3)와 달라 원본 식 그대로 옮겼다.
- 무작위는 엔진의 random(xorshift64*)을 쓴다. (원본 Math.random 자리)
- 원본 shuffle 의 randomFunction 기본 인자는 shuffle(엔진 random), shuffle_with_random_function(넘긴 함수)으로 나눴다.

예제: 범위 제한, 보간, 반올림, 각 바꾸기, 난수

```rust
use vanilla::math;

assert_eq!(math::clamp(15.0, 0.0, 10.0), 10.0);
assert_eq!(math::lerp(0.0, 10.0, 0.25), 2.5);
assert_eq!(math::round(-2.5), -2.0);
assert!((math::degree_to_radian(180.0) - math::PI).abs() < 1e-6);

let value = math::random_range(5.0, 10.0);
assert!(value >= 5.0 && value <= 10.0);
```

## Functions and constants

- `pub const PI: f64 = std::f64::consts::PI` (field, since 0.3.2): 원주율. (std::f64::consts::PI)
  - returns f64
- `pub const POSITIVE_INFINITY: f64 = f64::INFINITY` (field, since 0.4.0): 양의 무한대. (원본 PositiveInfinity)
  - returns f64
- `pub const NEGATIVE_INFINITY: f64 = f64::NEG_INFINITY` (field, since 0.4.0): 음의 무한대. (원본 NegativeInfinity)
  - returns f64
- `pub fn min(left: f64, right: f64) -> f64` (method, since 0.4.0): 더 낮은 수. (원본처럼 left < right 가 아니면 right, NaN 이 끼면 f64::min 과 다르다)
  - `left` f64: 첫째 수.
  - `right` f64: 둘째 수.
  - returns f64: left < right 면 left, 아니면 right. (어느 쪽이든 NaN 이면 right)

  예제: NaN 이 끼면 둘째 값

  ```rust
  use vanilla::math;
  
  assert_eq!(math::min(2.0, 1.0), 1.0);
  assert_eq!(math::min(f64::NAN, 1.0), 1.0);
  assert!(math::min(1.0, f64::NAN).is_nan());
  ```

- `pub fn max(left: f64, right: f64) -> f64` (method, since 0.4.0): 더 높은 수. (원본처럼 left > right 가 아니면 right)
  - `left` f64: 첫째 수.
  - `right` f64: 둘째 수.
  - returns f64: left > right 면 left, 아니면 right. (어느 쪽이든 NaN 이면 right)
- `pub fn floor(value: f64) -> f64` (method, since 0.4.0): 내림. (무한대는 그대로)
  - `value` f64: 내릴 수.
  - returns f64: value 이하에서 가장 큰 정수.
- `pub fn ceil(value: f64) -> f64` (method, since 0.4.0): 올림. (무한대는 그대로)
  - `value` f64: 올릴 수.
  - returns f64: value 이상에서 가장 작은 정수.
- `pub fn round(value: f64) -> f64` (method, since 0.4.0): 반올림. (원본 round: 반은 +무한대 쪽으로, -2.5 → -2, -0.5 → 0, 무한대는 그대로)
  - `value` f64: 반올림할 수.
  - returns f64: 가장 가까운 정수. (반은 +무한대 쪽, NaN 과 무한대는 그대로)

  예제: 음수의 반은 위로 올린다

  ```rust
  use vanilla::math;
  
  assert_eq!(math::round(2.5), 3.0);
  assert_eq!(math::round(-2.5), -2.0);
  assert_eq!(math::round(-2.6), -3.0);
  assert_eq!(math::round(f64::INFINITY), f64::INFINITY);
  ```

- `pub fn sqrt(value: f64) -> f64` (method, since 0.4.0): 제곱근. (음수는 NaN)
  - `value` f64: 제곱근을 구할 수.
  - returns f64: 제곱근. (음수면 NaN)
- `pub fn abs(value: f64) -> f64` (method, since 0.4.0): 절대값. (원본처럼 0 보다 작으면 부호를 뒤집는다)
  - `value` f64: 절대값을 구할 수.
  - returns f64: 0 보다 작으면 -value, 아니면 value. (-0 과 NaN 은 그대로)
- `pub fn sin(value: f64) -> f64` (method, since 0.4.0): 사인.
  - `value` f64: 각. (라디안)
  - returns f64: 사인 값. (-1 ~ 1)
- `pub fn cos(value: f64) -> f64` (method, since 0.4.0): 코사인.
  - `value` f64: 각. (라디안)
  - returns f64: 코사인 값. (-1 ~ 1)
- `pub fn tan(value: f64) -> f64` (method, since 0.4.0): 탄젠트.
  - `value` f64: 각. (라디안)
  - returns f64: 탄젠트 값.
- `pub fn asin(value: f64) -> f64` (method, since 0.4.0): 아크사인. (범위 밖은 NaN)
  - `value` f64: 사인 값. (-1 ~ 1)
  - returns f64: 각. (라디안, -PI / 2 ~ PI / 2, 범위 밖이면 NaN)
- `pub fn acos(value: f64) -> f64` (method, since 0.4.0): 아크코사인. (범위 밖은 NaN)
  - `value` f64: 코사인 값. (-1 ~ 1)
  - returns f64: 각. (라디안, 0 ~ PI, 범위 밖이면 NaN)
- `pub fn pow(base: f64, exponent: f64) -> f64` (method, since 0.4.0): 거듭제곱. (지수가 분수나 음수여도 맞다)
  - `base` f64: 밑.
  - `exponent` f64: 지수.
  - returns f64: base 의 exponent 제곱.
- `pub fn clamp(value: f64, minimum: f64, maximum: f64) -> f64` (method, since 0.3.2): 범위 제한.
  - `value` f64: 제한할 수.
  - `minimum` f64: 최소값.
  - `maximum` f64: 최대값.
  - returns f64: value 가 minimum 보다 작으면 minimum, maximum 보다 크면 maximum, 아니면 value. (minimum 을 먼저 본다)
- `pub fn clamp01(value: f64) -> f64` (method, since 0.3.2): 0 ~ 1 범위 제한.
  - `value` f64: 제한할 수.
  - returns f64: 0 ~ 1 로 자른 값.
- `pub fn degree_to_radian(degree: f64) -> f64` (method, since 0.3.2): 도 → 라디안.
  - `degree` f64: 각. (도)
  - returns f64: 각. (라디안)
- `pub fn radian_to_degree(radian: f64) -> f64` (method, since 0.3.2): 라디안 → 도.
  - `radian` f64: 각. (라디안)
  - returns f64: 각. (도)
- `pub fn lerp(from: f64, to: f64, time: f64) -> f64` (method, since 0.3.2): 선형 보간.
  - `from` f64: 시작 값.
  - `to` f64: 끝 값.
  - `time` f64: 보간 비율. (0 이면 from, 1 이면 to, 0 ~ 1 밖도 자르지 않는다)
  - returns f64: from + (to - from) * time.
- `pub fn random() -> f64` (method, since 0.3.2): 0 이상 1 미만 난수.
  - returns f64: 0 이상 1 미만 난수. (2 의 -24 제곱 단위, 스레드마다 상태를 따로 둔다)
- `pub fn random_range(minimum: f64, maximum: f64) -> f64` (method, since 0.3.2): 범위 난수. (minimum 이상 maximum 미만)
  - `minimum` f64: 범위 시작. (포함)
  - `maximum` f64: 범위 끝.
  - returns f64: minimum + (maximum - minimum) * random().
- `pub fn random_int(minimum: i32, maximum: i32) -> i32` (method, since 0.4.0): 정수 범위 난수. (minimum 이상 maximum 이하)
  - `minimum` i32: 가장 작은 값. (포함)
  - `maximum` i32: 가장 큰 값. (포함)
  - returns i32: minimum 이상 maximum 이하 정수.

  예제: 주사위 굴리기

  ```rust
  use vanilla::math;
  
  let dice = math::random_int(1, 6);
  assert!((1..=6).contains(&dice));
  assert_eq!(math::random_int(5, 5), 5);
  ```

- `pub fn pick_random<T>(array: &[T]) -> Option<&T>` (method, since 0.4.0): 배열에서 무작위로 하나. (비었으면 None, 원본 undefined)
  - `array` &[T]: 고를 슬라이스.
  - returns Option<&T>: 무작위로 고른 원소의 참조. 비었으면 None.

  예제: 목록에서 하나 고르기

  ```rust
  use vanilla::math;
  
  let item_list = ["sword", "shield", "potion"];
  match math::pick_random(&item_list) {
  	Some(item) => {
  		assert!(item_list.contains(item));
  	}
  	None => {
  		unreachable!();
  	}
  }
  let empty_list: [i32; 0] = [];
  assert!(math::pick_random(&empty_list).is_none());
  ```

- `pub fn shuffle<T>(array: &mut [T])` (method, since 0.4.0): 배열 제자리 섞기. (Fisher-Yates, 엔진 random)
  - `array` &mut [T]: 섞을 슬라이스. (제자리에서 바뀐다)
- `pub fn shuffle_with_random_function<T>(array: &mut [T], mut random_function: impl FnMut() -> f64)` (method, since 0.4.0): 넘긴 난수 함수(0 이상 1 미만)로 배열 제자리 섞기. (SeededRandom 의 next_value 등)
  - `array` &mut [T]: 섞을 슬라이스. (제자리에서 바뀐다)
  - `random_function` impl FnMut() -> f64: 0 이상 1 미만을 돌려주는 함수. (원소 수 - 1 번 부른다, 1 이상이면 지금 자리로 자른다)

  예제: 씨앗 난수로 늘 같은 차례 섞기

  ```rust
  use vanilla::{math, SeededRandom};
  
  let mut first_list = [1, 2, 3, 4, 5];
  let mut second_list = [1, 2, 3, 4, 5];
  let mut first_random = SeededRandom::new(42);
  let mut second_random = SeededRandom::new(42);
  math::shuffle_with_random_function(&mut first_list, || first_random.next_value());
  math::shuffle_with_random_function(&mut second_list, || second_random.next_value());
  assert_eq!(first_list, second_list);
  
  let mut number_list = [1, 2, 3, 4];
  math::shuffle_with_random_function(&mut number_list, || 0.0);
  assert_eq!(number_list, [2, 3, 4, 1]);
  ```

- `pub fn approach(current_value: f64, target_value: f64, rate: f64, time_delta: f64) -> f64` (method, since 0.3.2): 프레임률 독립 지수 감쇠 추종. (목표가 도중에 바뀌어도 튀지 않는다, rate 가 클수록 빨리 붙는다)
  - current + (target - current) * (1 - e^(-rate * time_delta))
  - `current_value` f64: 지금 값.
  - `target_value` f64: 목표 값.
  - `rate` f64: 붙는 빠르기. (시간 단위당, 클수록 빨리 붙는다, 0 이면 그대로)
  - `time_delta` f64: 지난 시간. (rate 와 같은 시간 단위)
  - returns f64: 목표 쪽으로 옮긴 값. (rate 와 time_delta 가 0 이상이면 지나치지 않는다)

  예제: 매 프레임 목표를 부드럽게 따라가기

  ```rust
  use vanilla::math;
  
  let mut camera_x = 0.0;
  for _ in 0..60 {
  	camera_x = math::approach(camera_x, 100.0, 5.0, 1.0 / 60.0);
  }
  assert!(camera_x > 99.0 && camera_x < 100.0);
  ```

- `pub fn move_towards(current_value: f64, target_value: f64, maximum_delta: f64) -> f64` (method, since 0.4.0): 값을 일정 속도로 목표까지 옮기기. (지나치지 않는다)
  - `current_value` f64: 지금 값.
  - `target_value` f64: 목표 값.
  - `maximum_delta` f64: 한 번에 옮길 최대 거리. (0 이상)
  - returns f64: maximum_delta 만큼 목표 쪽으로 옮긴 값. 남은 차이가 maximum_delta 이하이면 target_value.

  예제: 일정 속도로 다가가고 넘지 않는다

  ```rust
  use vanilla::math;
  
  assert_eq!(math::move_towards(0.0, 10.0, 3.0), 3.0);
  assert_eq!(math::move_towards(0.0, -10.0, 3.0), -3.0);
  assert_eq!(math::move_towards(9.0, 10.0, 3.0), 10.0);
  ```

- `pub fn ease_out_quad(time: f64) -> f64` (method, since 0.3.2): 이징: 바깥으로 감속하는 2차 곡선.
  - `time` f64: 진행 비율. (0 ~ 1)
  - returns f64: 1 - (1 - time) * (1 - time). (0 이면 0, 1 이면 1)
