Skip to content

Instantly share code, notes, and snippets.

@bluelhf
Last active June 4, 2022 18:18
Show Gist options
  • Save bluelhf/a9ada3552fe0ab6aab6ef3a107c2e3bb to your computer and use it in GitHub Desktop.
Save bluelhf/a9ada3552fe0ab6aab6ef3a107c2e3bb to your computer and use it in GitHub Desktop.
JShell script that loads a method for finding intersections between a ray and a sphere given the origin of the sphere, the origin of the ray, the direction vector of the ray, and the radius of the sphere.
import static java.lang.Math.*;
double[][] intersections(double[] p, double[] o, double[] d, double r) {
double[] ip = inverse(p);
double a = dot(d, d);
double b = 2 * dot(o, d) + 2 * dot(ip, d);
double c = dot(o, o) + 2 * dot(ip, o) + dot(ip, ip) - pow(r, 2);
double dct = pow(b, 2) - 4 * a * c;
double[] t = new double[]{
(-b - sqrt(dct)) / (2 * a),
(-b + sqrt(dct)) / (2 * a)
};
return new double[][]{
add(o, mult(d, t[0])),
add(o, mult(d, t[1]))
};
}
double[] inverse(double[] input) {
return mult(input, -1);
}
double sum(double[] input) {
double sum = 0;
for (int i = 0; i < input.length; i++) {
sum += input[i];
}
return sum;
}
double[] mult(double[] input, double scalar) {
double[] clone = new double[input.length];
for (int i = 0; i < input.length; i++) {
clone[i] = scalar * input[i];
}
return clone;
}
double[] add(double[] a, double[] b) {
double[] result = new double[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = a[i] + b[i];
}
return result;
}
double dot(double[] a, double[] b) {
assert a.length == b.length: "Dot product inputs must be of equal dimension";
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i] * b[i];
}
return sum;
}
@bluelhf
Copy link
Author

bluelhf commented Jun 4, 2022

Java 17 comes with a binary, jshell, which can execute this script — simply run the binary with the path to this script as the argument, and it'll load each method and throw you into a read-eval-print loop in which you can run intersections with your desired inputs.

input description
p the centre of the sphere
o the origin of the ray
d the direction vector of the ray
r the radius of the sphere

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment