-
Notifications
You must be signed in to change notification settings - Fork 11
/
delta.go
123 lines (106 loc) · 2.36 KB
/
delta.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package math
import (
"math"
)
// Delta represents a move between two pixel positions.
type Delta struct {
DX, DY int
}
func (d Delta) Norm0() int {
norm := 0
if d.DX > norm {
norm = d.DX
} else if -d.DX > norm {
norm = -d.DX
}
if d.DY > norm {
norm = d.DY
} else if -d.DY > norm {
norm = -d.DY
}
return norm
}
func (d Delta) Norm1() int {
norm := 0
if d.DX >= 0 {
norm += d.DX
} else {
norm -= d.DX
}
if d.DY >= 0 {
norm += d.DY
} else {
norm -= d.DY
}
return norm
}
func (d Delta) Length2() int {
return d.DX*d.DX + d.DY*d.DY
}
func (d Delta) Length() float64 {
return math.Sqrt(float64(d.Length2()))
}
func (d Delta) Add(d2 Delta) Delta {
return Delta{DX: d.DX + d2.DX, DY: d.DY + d2.DY}
}
func (d Delta) Sub(d2 Delta) Delta {
return Delta{DX: d.DX - d2.DX, DY: d.DY - d2.DY}
}
func (d Delta) Mul(n int) Delta {
return Delta{DX: d.DX * n, DY: d.DY * n}
}
func (d Delta) Mul2(mx, my int) Delta {
return Delta{DX: d.DX * mx, DY: d.DY * my}
}
func (d Delta) Div(m int) Delta {
return Delta{DX: Div(d.DX, m), DY: Div(d.DY, m)}
}
func (d Delta) MulFloat(f float64) Delta {
return Delta{DX: Rint(float64(d.DX) * f), DY: Rint(float64(d.DY) * f)}
}
func (d Delta) WithLength(f float64) Delta {
n := math.Sqrt(float64(d.Length2()))
if n == 0 {
return d
}
return d.MulFloat(f / n)
}
func (d Delta) WithMaxLength(f float64) Delta {
n2 := float64(d.Length2())
if n2 <= f*f {
return d
}
n := math.Sqrt(n2)
return d.MulFloat(f / n)
}
func North() Delta {
return Delta{DX: 0, DY: -1}
}
func East() Delta {
return Delta{DX: 1, DY: 0}
}
func South() Delta {
return Delta{DX: 0, DY: 1}
}
func West() Delta {
return Delta{DX: -1, DY: 0}
}
func (d Delta) Dot(d2 Delta) int {
return d.DX*d2.DX + d.DY*d2.DY
}
func (d Delta) IsZero() bool {
return d.DX == 0 && d.DY == 0
}