-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear.js
110 lines (108 loc) · 2.31 KB
/
linear.js
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
// Vector and matrix operations on Array-like objects.
// Vectors
var V = {
dot: function (x, y) {
var ans = 0;
for (var i = Math.min(x.length, y.length) - 1; i >= 0; i--) {
ans += x[i] * y[i];
}
return ans;
},
scale: function (v, a) {
return v.map(function (x) { return x * a; });
},
add: function (x, y) {
var ans = new Array(Math.min(x.length, y.length));
for (var i = 0; i < ans.length; i++) {
ans[i] = x[i] + y[i];
}
return ans;
},
addInPlace: function (x, y) {
var l = Math.min(x.length, y.length);
for (var i = 0; i < l; i++) {
x[i] += y[i];
}
},
sum2: function (x, y) {
var ans = 0;
var t;
for (var i = Math.min(x.length, y.length) - 1; i >= 0; i--) {
t = x[i] + y[i];
ans += t * t;
}
return ans;
},
zero: function (n) {
var ans = new Array(n);
for (var i = 0; i < n; i++) { ans[i] = 0; }
return ans;
},
isZero: function (v) {
for (var i = 0; i < v.length; i++) {
if (v[i] != 0) {
return false;
}
}
return true;
},
};
// Matrices
var M = {
mul: function (m, v) {
var ans = V.zero(m.length);
for (var i = 0; i < ans.length; i++) {
for (var j = 0; j < v.length; j++) {
ans[i] += m[i][j] * v[j];
}
}
return ans;
},
transpose: function (m) {
if (!(m && m.length && m[0] && m[0].length)) { return []; }
var ans = new Array(m[0].length);
for (var i = 0; i < m[0].length; i++) {
ans[i] = V.zero(m.length);
for (var j = 0; j < m.length; j++) {
ans[i][j] = m[j][i];
}
}
return ans;
},
mulMats: function (m, n) {
if (!(m && m.length && m[0] && m[0].length)) { return []; }
if (!(n && n.length && n[0] && n[0].length)) { return []; }
if (m[0].length != n.length) { return []; }
var ans = new Array(m.length);
for (var i = 0; i < m.length; i++) {
ans[i] = V.zero(n[0].length);
for (var j = 0; j < ans.length; j++) {
for (var k = 0; k < m[i].length; k++) {
ans[i][j] += m[i][k] * n[k][j];
}
}
}
return ans;
},
toGL4: function (m) {
var k = 0;
var ans = new Float32Array(16);
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
ans[k] = m[j][i];
k++;
}
}
return ans;
},
fromGL4: function (m) {
var ans = new Array(4);
for (var i = 0; i < 4; i++) {
ans[i] = V.zero(4);
for (var j = 0; j < 4; j++) {
ans[i][j] = m[i + 4*j];
}
}
return ans;
},
};