-
Notifications
You must be signed in to change notification settings - Fork 19
/
matrix_ext.rb
73 lines (57 loc) · 1.12 KB
/
matrix_ext.rb
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
require 'matrix'
class Vector
def abs
Math.sqrt inject(0) { |s, x| s + x ** 2 }
end
end
class Matrix
class << self
def rotate angle, i, j
cos_angle, sin_angle = Math.cos(angle), Math.sin(angle)
arr = Matrix.identity(4).to_a
arr[i][i], arr[i][j] = cos_angle, -sin_angle
arr[j][i], arr[j][j] = sin_angle, cos_angle
Matrix[*arr]
end
def rotate_x angle
rotate angle, 1, 2
end
def rotate_y angle
rotate angle, 2, 0
end
def rotate_z angle
rotate angle, 0, 1
end
def translation x, y, z
arr = Matrix.identity(4).to_a
arr[0][3] = x
arr[1][3] = y
arr[2][3] = z
Matrix[*arr]
end
def translate_x distance
translation distance, 0, 0
end
def translate_y distance
translation 0, distance, 0
end
def translate_z distance
translation 0, 0, distance
end
end
def abs
Math.sqrt inject { |s, x| s + x ** 2 }
end
def x
column_vectors[0]
end
def y
column_vectors[1]
end
def z
column_vectors[2]
end
def translation
column_vectors[3]
end
end