#include <stdio.h> #include <stdlib.h> #include <math.h> // A struct to represent a 3D vector typedef struct Vector { double x; double y; double z; } Vector; // A struct to represent a sphere in 3D space typedef struct Sphere { Vector center; double radius; } Sphere; // A struct to represent a ray in 3D space typedef struct Ray { Vector origin; Vector direction; } Ray; // Returns the distance from the ray's origin to the point where it intersects // the sphere, or -1 if the ray does not intersect the sphere. double intersects(Ray ray, Sphere sphere) { Vector oc = { .x = ray.origin.x - sphere.center.x, .y = ray.origin.y - sphere.center.y, .z = ray.origin.z - sphere.center.z }; double b = 2 * (oc.x * ray.direction.x + oc.y * ray.direction.y + oc.z * ray.direction.z); double c = oc.x * oc.x + oc.y * oc.y + oc.z * oc.z - sphere.radius * sphere.radius; double discriminant = b * b - 4 * c; if (discriminant < 0) { return -1; } double t1 = (-b - sqrt(discriminant)) / 2; double t2 = (-b + sqrt(discriminant)) / 2; // Return the smallest non-negative value of t if (t1 >= 0 && t2 >= 0) { return fmin(t1, t2); } else if (t1 >= 0) { return t1; } else if (t2 >= 0) { return t2; } else { return -1; } } int main() { // Create a sphere at the origin with radius 1 Sphere sphere = { .center = { .x = 0, .y = 0, .z = 0 }, .radius = 1 }; // Create a ray that starts at the origin and points in the direction of the // positive x-axis Ray ray = { .origin = { .x = 0, .y = 0, .z = 0 }, .direction = { .x = 1, .y = 0, .z = 0 } }; double distance = intersects(ray, sphere); printf("The ray intersects the sphere at a distance of %f\n", distance); return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter