This repository was archived by the owner on Apr 2, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathaffine.go
More file actions
393 lines (357 loc) · 11.3 KB
/
Copy pathaffine.go
File metadata and controls
393 lines (357 loc) · 11.3 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232<
8000
/div>
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package curve
import (
"iter"
"math"
)
// Affine describes an affine transform via coefficients.
//
// If the coefficients are (a, b, c, d, e, f), then the resulting
// transformation represents this augmented matrix:
//
// | a c e |
// | b d f |
// | 0 0 1 |
//
// Note that this convention is transposed from PostScript and Direct2D, but is
// consistent with the [Wikipedia] formulation of affine transformation as
// augmented matrix. The idea is that (A * B) * v == A * (B * v).
//
// [Wikipedia]: https://en.wikipedia.org/wiki/Affine_transformation
type Affine struct {
// We represent Affine as a struct instead of an array because Go applies fuck-all
// optimizations to arrays, while structs benefit from SROA.
N0, N1, N2, N3, N4, N5 float64
}
// Identity is the identity transform.
var Identity = Affine{1, 0, 0, 1, 0, 0}
// FlipY is a transform that is flipped on the y-axis. Useful for converting
// between y-up and y-down spaces.
var FlipY = Affine{1, 0, 0, -1, 0, 0}
// FlipX is a transform that is flipped on the x-axis.
var FlipX = Affine{-1, 0, 0, 1, 0, 0}
// Scale creates an affine transform representing non-uniform scaling with
// different scale values for x and y
func Scale(x, y float64) Affine {
return Affine{x, 0, 0, y, 0, 0}
}
// Translate creates an affine transform representing translation.
func Translate(v Vec2) Affine {
return Affine{1, 0, 0, 1, v.X, v.Y}
}
// Rotate creates an affine transform representing rotation.
//
// The convention for rotation is that a positive angle rotates a
// positive X direction into positive Y. Thus, in a Y-down coordinate
// system (as is common for graphics), it is a clockwise rotation, and
// in Y-up (traditional for math), it is anti-clockwise.
//
// The angle th is expressed in radians.
func Rotate(th float64) Affine {
sin, cos := math.Sincos(th)
return Affine{cos, sin, -sin, cos, 0, 0}
}
// RotateAbout creates an affine transform representing a rotation of th radians
// about center.
//
// See [Rotate] for more info.
func RotateAbout(th float64, center Point) Affine {
c := Vec2(center)
return Translate(c.Negate()).ThenRotate(th).ThenTranslate(c)
}
// Skew creates an affine transformation representing a skew.
//
// The x and y parameters represent skew factors for the horizontal and vertical
// directions, respectively.
//
// This is commonly used to generate a faux oblique transform for
// font rendering. In this case, you can slant the glyph 20 degrees
// clockwise in the horizontal direction (assuming a Y-up coordinate
// system).
func Skew(x, y float64) Affine {
return Affine{1, y, x, 1, 0, 0}
}
// Reflect creates an affine transform that represents reflection about the line
// point + direction * t, t ∈ [-∞, ∞]
func Reflect(pt Point, direction Vec2) Affine {
n := Vec2{
X: direction.Y,
Y: -direction.X,
}.Normalize()
// Compute Householder reflection matrix
x2 := n.X * n.X
xy := n.X * n.Y
y2 := n.Y * n.Y
// Here we also add in the post translation, because it doesn't require any further calc.
aff := Affine{
1.0 - 2.0*x2,
-2.0 * xy,
-2.0 * xy,
1.0 - 2.0*y2,
pt.X,
pt.Y,
}
return aff.PreTranslate(Vec2(pt).Negate())
}
// Coefficients returns the the coefficients of the transform.
func (aff Affine) Coefficients() [6]float64 {
return [6]float64{aff.N0, aff.N1, aff.N2, aff.N3, aff.N4, aff.N5}
}
// NewAffine creates a new affine transformation from an array of coefficients.
// Alternatively, you can initialize the fields of [Affine] manually.
func NewAffine(n [6]float64) Affine {
return Affine{n[0], n[1], n[2], n[3], n[4], n[5]}
}
func (aff Affine) Mul(o Affine) Affine {
return Affine{
aff.N0*o.N0 + aff.N2*o.N1,
aff.N1*o.N0 + aff.N3*o.N1,
aff.N0*o.N2 + aff.N2*o.N3,
aff.N1*o.N2 + aff.N3*o.N3,
aff.N0*o.N4 + aff.N2*o.N5 + aff.N4,
aff.N1*o.N4 + aff.N3*o.N5 + aff.N5,
}
}
// PreRotate creates a rotation by th followed by aff.
//
// Equivalent to "aff * Rotate(th)"
func (aff Affine) PreRotate(th float64) Affine {
return aff.Mul(Rotate(th))
}
// ThenRotate creates aff followed by a rotation of th.
//
// Equivalent to "Rotate(th) * aff"
func (aff Affine) ThenRotate(th float64) Affine {
return Rotate(th).Mul(aff)
}
// PreRotateAbout creates a rotation by th about center followed by aff.
//
// Equivalent to "aff * RotateAbout(th)"
func (aff Affine) PreRotateAbout(th float64, center Point) Affine {
return RotateAbout(th, center).Mul(aff)
}
// "ThenRotateAbout creates aff followed by a rotation of th about center.
//
// Equivalent to "RotateAbout(th, center) * aff"
func (aff Affine) ThenRotateAbout(th float64, center Point) Affine {
return RotateAbout(th, center).Mul(aff)
}
// PreScale creates a scale by (x, y) followed by aff.
//
// Equivalent to "aff * Scale(x, y)"
func (aff Affine) PreScale(x, y float64) Affine {
return aff.Mul(Scale(x, y))
}
// ThenScale creates aff followed by a scale of (x, y).
//
// Equivalent to "Scale(x, y) * aff"
func (aff Affine) ThenScale(x, y float64) Affine {
return Scale(x, y).Mul(aff)
}
// PreTranslate creates a translation of v followed by aff.
//
// Equivalent to "aff * Translate(v)"
func (aff Affine) PreTranslate(v Vec2) Affine {
return aff.Mul(Translate(v))
}
// ThenTranslate creates aff followed by a translation of v.
//
// Equivalent to "Translate(v) * aff"
func (aff Affine) ThenTranslate(v Vec2) Affine {
aff.N4 += v.X
aff.N5 += v.Y
return aff
}
// MapUnitSquare creates an affine transformation that takes the unit square to the given rectangle.
//
// Useful when you want to draw into the unit square but have your output fill any rectangle.
// In this case push the Affine onto the transform stack.
func MapUnitSqua
8000
re(rect Rect) Affine {
return Affine{
rect.Width(),
0, 0,
rect.Height(),
rect.X0,
rect.Y0,
}
}
// Determinant computes the determinant.
func (aff Affine) Determinant() float64 {
return aff.N0*aff.N3 - aff.N1*aff.N2
}
// Invert computes the inverse transform.
//
// Produces NaN values when the determinant is zero.
func (aff Affine) Invert() Affine {
invDet := 1 / aff.Determinant()
return Affine{
+invDet * aff.N3,
-invDet * aff.N1,
-invDet * aff.N2,
+invDet * aff.N0,
+invDet * (aff.N2*aff.N5 - aff.N3*aff.N4),
+invDet * (aff.N1*aff.N4 - aff.N0*aff.N5),
}
}
func (aff Affine) IsInf() bool {
return math.IsInf(aff.N0, 0) ||
math.IsInf(aff.N1, 0) ||
math.IsInf(aff.N2, 0) ||
math.IsInf(aff.N3, 0) ||
math.IsInf(aff.N4, 0) ||
math.IsInf(aff.N5, 0)
}
func (aff Affine) IsNaN() bool {
return math.IsNaN(aff.N0) ||
math.IsNaN(aff.N1) ||
math.IsNaN(aff.N2) ||
math.IsNaN(aff.N3) ||
math.IsNaN(aff.N4) ||
math.IsNaN(aff.N5)
}
// Compute the singular value decomposition of the linear transformation (ignoring the
// translation).
//
// All non-degenerate linear transformations can be represented as
//
// 1. a rotation about the origin.
// 2. a scaling along the x and y axes
// 3. another rotation about the origin
//
// composed together. Decomposing a 2x2 matrix in this way is called a "singular value
// decomposition" and is written "U Σ V^T", where U and V^T are orthogonal (rotations) and Σ
// is a diagonal matrix (a scaling).
//
// Since currently this function is used to calculate ellipse radii and rotation from an
// affine map on the unit circle, we don't calculate V^T, since a rotation of the unit (or
// any) circle about its center always results in the same circle. This is the reason that an
// ellipse mapped using an affine map is always an ellipse.
//
// Will return NaNs if the matrix (or equivalently the linear map) is singular.
//
// First part of the return tuple is the scaling, second part is the angle of rotation (in
// radians)
func (aff Affine) svd() (scale Vec2, th float64) {
// OPT(dh): if svd ever begins to inline, we should switch the computation
// of the scale over to the algorithm used in svd0.
a := aff.N0
a2 := a * a
b := aff.N1
b2 := b * b
c := aff.N2
c2 := c * c
d := aff.N3
d2 := d * d
ab := a * b
cd := c * d
th = math.Atan2(0.5*(2.0*(ab+cd)), a2-b2+c2-d2)
s1 := a2 + b2 + c2 + d2
s2 := math.Sqrt(pow2(a2-b2+c2-d2) + 4.0*pow2(ab+cd))
return Vec2{
X: math.Sqrt(0.5 * (s1 + s2)),
Y: math.Sqrt(0.5 * (s1 - s2)),
}, th
}
// svd0 is like [Affine.svd], but only computes the second return value. This is
// faster if only that value is needed.
func (aff Affine) svd0() Vec2 {
// OPT(dh): if [Affine.svd] were inlined and dead code got eliminated, we
// wouldn't need svd0.
a := aff.N0
b := aff.N1
c := aff.N2
d := aff.N3
// Given matrix A = [ a c ]
// [ b d ]
//
// The two singular values σ1, σ2 of A are the square roots of the two eigen values λ1, λ2
// of M = A^T A. The common formula for 2x2 eigenvalues requires evaluating a square root,
// but we'd like to compute the singular values of the matrix without nested square roots.
//
// M = A^T A = [ aa+cc ab+cd ]
// [ ab+cd bb+dd ]
//
// We have
// λ = 1/2 (tr(M) ± sqrt(tr(M)^2 - 4 det(M))).
//
// Note det(M) = det(A^T A) = det(A)^2.
// => 2λ = tr(M) ± sqrt(tr(M)^2 - 4 det(A)^2)
// => 2λ = tr(M) ± sqrt[(a^2+b^2+c^2+d^2)^2 - 4 (ad-bc)^2]
// By factorizing the inner term,
// => 2λ = tr(M) ± sqrt[((a+d)^2 + (b-c)^2) ((a-d)^2 + (b+c)^2)]
// => 2λ = tr(M) ± sqrt[(a+d)^2 + (b-c)^2] sqrt[(a-d)^2 + (b+c)^2]
//
// Define S1 = sqrt[(a+d)^2 + (b-c)^2]
// S2 = sqrt[(a-d)^2 + (b+c)^2].
//
// => 2λ = tr(M) ± S1 S2
// => 2λ = 1/2 (S1^2 + S2^2) ± S1 S2
// => λ = 1/4 (S1^2 + S2^2 ± 2 S1 S2)
// => λ = 1/4 (S1 ± S2)^2
//
// Note we're interested in
// σ = sqrt(λ).
//
// => σ1 = 1/2 (S1 + S2)
// and similarly σ2 = 1/2 |S1 - S2|
s1 := math.Sqrt((pow2(a+d) + pow2(b-c)))
s2 := math.Sqrt((pow2(a-d) + pow2(b+c)))
return Vec2{
X: 0.5 * (s1 + s2),
Y: 0.5 * math.Abs(s1-s2),
}
}
// svd1 is like [Affine.svd], but only computes the second return value. This is
// faster if only that value is needed.
func (aff Affine) svd1() float64 {
// OPT(dh): if [Affine.svd] were inlined and dead code got eliminated, we
// wouldn't need svd0.
a := aff.N0
a2 := a * a
b := aff.N1
b2 := b * b
c := aff.N2
c2 := c * c
d := aff.N3
d2 := d * d
ab := a * b
cd := c * d
th := math.Atan2(0.5*(2.0*(ab+cd)), a2-b2+c2-d2)
return th
}
// Translation returns the translation component of this affine transformation.
func (aff Affine) Translation() Vec2 {
return Vec2{
X: aff.N4,
Y: aff.N5,
}
}
// WithTranslation replaces the translation portion of this affine
// transformation.
func (aff Affine) WithTranslation(v Vec2) Affine {
aff.N4 = v.X
aff.N5 = v.Y
return aff
}
// TransformRectBoundingBox computes the bounding box of a transformed rectangle.
//
// Returns the minimal [Rect] that encloses the given rectangle after affine transformation.
// If the transform is axis-aligned, then this bounding box is "tight", in other words the
// returned rectangle is the transformed rectangle.
//
// The returned rectangle always has non-negative width and height.
func (aff Affine) TransformRectBoundingBox(rect Rect) Rect {
p00 := Pt(rect.X0, rect.Y0).Transform(aff)
p01 := Pt(rect.X0, rect.Y1).Transform(aff)
p10 := Pt(rect.X1, rect.Y0).Transform(aff)
p11 := Pt(rect.X1, rect.Y1).Transform(aff)
return NewRectFromPoints(p00, p01).Union(NewRectFromPoints(p10, p11))
}
func Transform[T interface{ Transform(Affine) T }](seq iter.Seq[T], aff Affine) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range seq {
if !yield(v.Transform(aff)) {
break
}
}
}
}