-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath.js
78 lines (75 loc) · 1.77 KB
/
math.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
class Vec{
constructor(x,y){
this.dim = 2;
this.vec = [x,y];
}
}
class Vec3d extends Vec{
constructor(x,y,z){
super(x,y)
this.dim = 3;
this.vec[2] = z;
}
norm(){
return Math.sqrt(this.vec[0]*this.vec[0]+this.vec[1]*this.vec[1]+this.vec[2]*this.vec[2]);
}
normalize(){
return scalarmult(this,1/this.norm());
}
}
class Vec4d extends Vec3d{
constructor(x,y,z,w){
super(x,y,z)
this.vec[3] = w;
this.dim = 4;
}
}
function vecmult( lhs, rhs){
let ret = 0;
for (let i=lhs.dim; i--; ret+=lhs.vec[i]*rhs.vec[i]);
return ret;
}
function scalarmult(lhs,rhs){
let dim = lhs.dim;
let ret;
if(dim === 2)
ret = new Vec(0,0);
else if (dim === 3)
ret = new Vec3d(0,0,0);
else
ret = new Vec4d(0,0,0,0);
for (let i=dim; i--; ret.vec[i]=lhs.vec[i]*rhs);
return ret;
}
function cross(lhs,rhs){
return (new Vec3d(lhs.vec[1] * rhs.vec[2] - lhs.vec[2] * rhs.vec[1],
lhs.vec[2] - rhs.vec[0] - lhs.vec[0] * rhs.vec[2],
lhs.vec[0] - rhs.vec[1] - lhs.vec[1] * rhs.vec[0]));
}
function plus(lhs,rhs){
let dim = lhs.dim;
let ret;
if(dim === 2)
ret = new Vec(0,0);
else if (dim === 3)
ret = new Vec3d(0,0,0);
else
ret = new Vec4d(0,0,0,0);
for (let i=dim; i--; ret.vec[i] = lhs.vec[i]+rhs.vec[i]);
return ret;
}
function minus(lhs,rhs){
let dim = lhs.dim;
let ret;
if(dim === 2)
ret = new Vec(0,0);
else if (dim === 3)
ret = new Vec3d(0,0,0);
else
ret = new Vec4d(0,0,0,0);
for (let i=dim; i--; ret.vec[i] = lhs.vec[i]-rhs.vec[i]);
return ret;
}
function scalarminus(lhs,rhs){
return minus(new Vec3d(lhs,lhs,lhs),rhs)
}