import java.awt.*; public class BasicRayTrace extends BufferedApplet { int focalLength = 4; double[] v = new double[3]; double[] w = new double[3]; Color[][] image; Color bgColor = new Color(0, 0, 0); double[][] spheres = { {-0.85, -0.85, -6.5, (double)2440/6378}, //MERCURY {-0.35, -0.35, -7, (double)6052/6378}, //VENUS {0.35, 0.35, -8, (double)6378/6378}, //EARTH {0.45, 0.35, -7, (double)1738/6378}, //MOON {0.85, 0.85, -8, (double)3397/6378}, //MARS }; Color[] colors = { new Color (128, 0, 0), //MERCURY new Color (0, 128, 128), //VENUS new Color (0, 0, 255), //EARTH new Color (128, 128, 128), //MOON new Color (255, 0, 0), //MARS }; public void render(Graphics g) { int H = bounds().width; int W = bounds().width; g.setColor(bgColor); g.fillRect(0, 0, W, H); image = new Color[W][H]; for (int i = 0; i < W; i++) for (int j = 0; j < H; j++) image[i][j] = bgColor; // image has height, width H, W; camera at origin v[0] = 0; v[1] = 0; // CAMERA EYEPOINT IS AT THE ORIGIN v[2] = 0; for (int i = 0; i < W; i++) // LOOP OVER IMAGE COLUMNS for (int j = 0; j < H; j++) { // LOOP OVER IMAGE ROWS w[0] = (double) (i - W / 2) / (W / 2); // COMPUTE RAY DIRECTION AT EACH PIXEL w[1] = (double) (H / 2 - j) / (W / 2); // w[2] = -focalLength; // PLACE IMAGE PLANE AT z=-focalLength image[i][j] = rayTrace(v, w); // COMPUTE COLOR AT PIXEL BY RAY TRACING } for (int i = 0; i < W; i++) for (int j = 0; j < H; j++) { g.setColor(image[i][j]); g.drawRect(i, j, 1, 1); } } public Color rayTrace(double[] v, double[] w) { double t = Double.MAX_VALUE; double newT; double A, B, C; Color color = bgColor; A = Math.pow(w[0], 2) + Math.pow(w[1], 2) + Math.pow(w[2], 2); for (int i = 0; i < spheres.length; i++) { B = 2 * (v[0] - spheres[i][0]) * w[0] + 2 * (v[1] - spheres[i][1]) * w[1] + 2 * (v[2] - spheres[i][2]) * w[2]; C = Math.pow(v[0] - spheres[i][0], 2) + Math.pow(v[1] - spheres[i][1], 2) + Math.pow(v[2] - spheres[i][2], 2) - Math.pow(spheres[i][3], 2); double discriminant = Math.pow(B, 2) - 4 * A * C; if (discriminant >= 0) { // calculate the lesser possiblity for newT newT = (-B + Math.sqrt(discriminant)) / 2 * A; if ((-B - Math.sqrt(discriminant)) / 2 * A < newT) { newT = (-B - Math.sqrt(discriminant)) / 2 * A; } if (0 < newT && newT < t) { t = newT; color = colors[i]; } } } return color; } }