aboutsummaryrefslogtreecommitdiff
path: root/src/model/vec2.ts
blob: 46ffc7e0dcfdbac7a44c65a371b09109e781c885 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import * as Number from 'util/number'
import * as Size from 'model/size'

export interface Vec2 {
  x: number,
  y: number,
}

export const zero: Vec2 = {
  x: 0,
  y: 0,
}

export function equals(v1: Vec2, v2: Vec2): boolean {
  return v1.x === v2.x && v1.y === v2.y
}

export function length(v: Vec2): number {
  return Math.sqrt(v.x ** 2 + v.y ** 2)
}

export function normalize(v: Vec2): Vec2 {
  if (v.x === 0 && v.y === 0) {
    return zero
  } else {
    const im = 1 / length(v)
    return {
      x: v.x * im,
      y: v.y * im
    }
  }
}

export function applyOnLength(f: (n: number) => number, v: Vec2): Vec2 {
  return scale(normalize(v), f(length(v)))
}

export function sub(v1: Vec2, v2: Vec2): Vec2 {
  return {
    x: v1.x - v2.x,
    y: v1.y - v2.y
  }
}

export function div(v: Vec2, k: number): Vec2 {
  return {
    x: v.x / k,
    y: v.y / k
  }
}

export function add(v1: Vec2, v2: Vec2): Vec2 {
  return {
    x: v1.x + v2.x,
    y: v1.y + v2.y
  }
}

export function scale(v: Vec2, k: number): Vec2 {
  return {
    x: v.x * k,
    y: v.y * k
  }
}

export function clamp(v: Vec2, vMin: Vec2, vMax: Vec2): Vec2 {
  return {
    x: Number.clamp(v.x, vMin.x, vMax.x),
    y: Number.clamp(v.y, vMin.y, vMax.y)
  }
}

export function project(from: Size.Size, to: Size.Size, v: Vec2): Vec2 {
  return {
    x: v.x / from.width * to.width,
    y: v.y / from.height * to.height
  }
}