CS 100: Lecture L26
April 29
Demo for the triangle3D class
import java.io.*; import java.awt.*; public class L26CShow extends Frame { public static void ShowTriangle(Graphics g,Triangle3D T) { double[][] V = T.getVertices(); int[] h = new int[3]; int[] v = new int[3]; h[0] = 400 + (int)V[0][0]; v[0] = 300 - (int)V[0][1]; h[1] = 400 + (int)V[1][0]; v[1] = 300 - (int)V[1][1]; h[2] = 400 + (int)V[2][0]; v[2] = 300 - (int)V[2][1]; g.setColor(T.get_c()); g.drawLine(h[0],v[0],h[1],v[1]); g.drawLine(h[2],v[2],h[1],v[1]); g.drawLine(h[0],v[0],h[2],v[2]); g.fillPolygon(h,v,3); } public void paint(Graphics g) { int n = 50; Triangle3D[] T = new Triangle3D[n]; point P0,P1,P2; Color c; int red,green; double z,r; for (int i=0;i< n;i++) { P0 = new point(250); P1 = new point(250); P2 = new point(250); z = Math.random(); red = (int)((1-z)*255); r = 300*z; c = new Color(red,0,0); T[i] = new Triangle3D(P0,P1,P2,z,c); } Triangle3D.sort(T); for(int i=n-1;i>=0;i--) ShowTriangle(g,T[i]); } } public class L26C { public static void main(String args[]) { L26CShow d = new L26CShow(); d.resize(800,600); d.move(0,75); d.setTitle("L26C"); d.show(); d.toFront(); } }
The triangle3D Class:
// An instance of this class is a triangle with a // z-ccordinate to be // considered its distance from the observer. import java.awt.*; public class Triangle3D extends Triangle { protected double z; // Distance to observer. protected Color c; // Color // Constructor for triangle with vertices // v0, v1, v2, and // observer distance zVal. public Triangle3D(point v0, point v1, point v2, double zVal, Color cVal) { super(v0,v1,v2); z = zVal; c = cVal; } // Constructor for equilateral triangle with radius r center cent, and // observer distance zVal. public Triangle3D(point cent, double r, double zVal, Color cVal) { super(cent,r); z = zVal; c = cVal; } // Yields true if this triangle is closer to the // observer than T. public boolean closerThan(Triangle3D T) { return this.z< T.z; } // Yields true if this triangle is smaller in area // than T. public boolean smallerThan(Triangle3D T) { return this.Area() < T.Area(); } public Color get_c() { return c; } public static void sort(Triangle3D[] T) { int n=T.length; Triangle3D temp; int pass=1; int swaps; boolean Sorted = false; while (!Sorted) { swaps=0; for (int j = 0; j < n - pass; j++) { if (T[j+1].closerThan(T[j])) { temp = T[j+1]; T[j+1] = T[j]; T[j] = temp; swaps++; } } pass++; Sorted = (pass == n) || swaps==0; } } }