Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <cmath>
- struct Vec {
- double x, y, z;
- Vec(){x=y=z=0;}
- Vec(double a, double b, double c){x=a,y=b,z=c;}
- Vec operator- (Vec v) {return Vec(x-v.x,y-v.y,z-v.z);}
- };
- double dot(Vec v, Vec b) {return (v.x*b.x+v.y*b.y+v.z*b.z);}
- struct Ray {
- Vec o; // origin
- Vec d; // direction
- Ray(Vec i, Vec j) {o=i,d=j;}
- };
- struct Sphere {
- Vec c; // Center
- double r; // Radius
- Sphere(Vec i, double j){c=i, r=j;}
- bool intersect(Ray ray, double &t) {
- Vec o = ray.o;
- Vec d = ray.d;
- Vec oc = o-c;
- double b = 2*dot(oc,d);
- double c = dot(oc, oc)-r*r;
- double disc = b*b-4*c;
- if (disc < 0) return false;
- else {
- disc = sqrt(disc);
- double t0 = -b-disc;
- double t1 = -b+disc;
- t = (t0 < t1) ? t0 : t1;
- return true;
- }
- }
- };
- struct Color {
- double r,g,b;
- Color(){r=g=b=0;}
- Color(double i, double j, double k){r=i,g=j,b=k;}
- };
- int main() {
- const int W = 500; // Image width
- const int H = 500; // Image height;
- std::ofstream out("out.ppm");
- out << "P3" << std::endl << W << std::endl << H << std::endl << "255" << std::endl;
- Color pixel_col[H][W];
- Color white(255, 255, 255);
- Sphere sphere(Vec(W/2,H/2,50),20);
- // for each pixel
- for (int y = 0; y < H; y++) {
- for (int x = 0; x < W; x++) {
- // send a ray through each pixel
- Ray ray(Vec(x, y, 0),Vec(0, 0, 1));
- double t = 20000;
- // Check for intersections
- if (sphere.intersect(ray,t)) {
- pixel_col[y][x] = white;
- }
- out << pixel_col[y][x].r << std::endl;
- out << pixel_col[y][x].g << std::endl;
- out << pixel_col[y][x].b << std::endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement