-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshapes.js
More file actions
65 lines (51 loc) · 1.79 KB
/
shapes.js
File metadata and controls
65 lines (51 loc) · 1.79 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
import * as vectors from "./maths_dir/vectors.js";
import * as rays from "./maths_dir/rays.js";
// Projection
/**
* A 3d sphere class, with equidistant radius and a centre.
*/
export class Sphere{
// A 3d Sphere class
/**
* Creates a sphere using centre-point and a radius.
*
* @param {vectors.Vector3} centre Centre of the sphere.
* @param {Number} radius Radius of the sphere.
* @param {Number} index Index in the list.
* @param {vectors.Vector3} colour Base colour of the sphere
* @param {Number} reflectivity How reflective the surface is.
*/
constructor( centre, radius, index, colour, reflectivity ){
this.centre = centre;
this.radius = radius;
this.index = index;
this.colour = colour;
this.reflectivity = reflectivity;
}
/**
* Tests if the ray passes through the sphere, and returns a RayResult3
* object
*
* @param {rays.Ray3} ray Ray to test.
* @returns {Number} Roots of the intersection
*/
rayIntersect(ray ){
// ( o - c ) in the equation, since its used quite alot
let oc = ray.start.subbed( this.centre );
let a = ray.direction.dot( ray.direction );
let b = 2 * ray.direction.dot( oc );
let c = oc.dot( oc ) - (this.radius * this.radius);
let discriminant = ( b * b ) - (4 * a * c );
// Checks if the discriminant, if the ray is inside the circle
if (discriminant < 0){
return -1
}
// Gets the closest root for the intersection
let negativeRoot = ( (-b - Math.sqrt( discriminant ) ) / (2 * a) );
if (negativeRoot > 0 ){
return negativeRoot
}
// Error handling, just dont show the pixel
return -1;
}
}