Question

Write a Java program which uses the LWJGL library to draw a window of 640x480 (with...

Write a Java program which uses the LWJGL library to draw a window of 640x480 (with a black background). The coordinate system should be centered in this window. Your program will read a file titled coordinates.txt and draw the corresponding filled polygon in this window using the scanline polygon fill algorithm. Each specified polygon should be filled in the color specified in the text file and then undergo the transformations specified in the input file before being drawn on the screen. Hence you will need to calculate the composition of the transformation matrices and then calculate the position of the polygon vertices and then apply the scan line fill algorithm. Use the glVertex2f() command to plot the pixel and glColor3f() to specify the color. Finally, your program should also use the input.Keyboard class to have the escape key quit your application.

The given coordinates.txt file will be in the following format:

P 0.5 0.6 0.3

30 300

80 150

160 400

200 150

250 300

T

r 45 0 0

s 0.5 1.5 0 0

t 200 –150

r –90 0 0

P 0.2 0.4 0.7

-350 –350

-350 350

350 350

350 –350

T

r 90 0 0

t 100 100

s 0.5 0.5 0 0

The file coordinates.txt will contain an ordered set of vertices for the polygon. The polygon can be drawn by joining the first vertex to the second, the second to the third and so on, until the final vertex is joined to the first to close the polygon. It denotes the polygon vertices by using the symbol P and the transformations for that polygon by using the symbol T. The symbol P is followed by three-float numbers that signify the R, G and B values specifying the fill color of the polygon. The symbols r, s and t stand for rotation, scaling and translation respectively. The symbol r is followed by the rotation angle, and the coordinate for the pivot point. Similarly the symbol s is followed by the scaling factors in the x and y direction and the pivot point coordinates. The symbol t is followed by the translation coordinates in the x and y direction. The sample file shows two polygons and the transformations for each polygon.

File coordinates.txt:

P 1.0 0.0 0.0
80 10
80 30
230 37
280 30
280 10
T
t 100 -75
r 30 0 0
s 0.5 1.5 0 0
P 0.1 0.8 0.3
10 10
10 80
80 60
210 10
210 80
150 10
T
r 90 0 0
s 2.0 0.2 0 0
t 30 30
r -45 0 0
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Edge.java

public class Edge {
    public float yMin;
    public float yMax;
    public float xVal;
    public float slop;
    public Edge(float y1, float y2, float x, float slope){
        yMin = y1;
        yMax = y2;
        xVal = x;
        slop = slope;
    }
    //Returns true if what you're comparing to is bigger
    public boolean compare(Edge e){
        if (this.yMin < e.yMin){
            return true;
        } else if (this.yMin > e.yMin){
            return false;
        } else {
            if (this.xVal < e.xVal){
                return true;
            } else if (this.xVal > e.xVal){
                return false;
            } else {
                if (this.yMax < e.yMax){
                    return true;
                } else if (this.yMax > e.yMax){
                    return false;
                } else {
                    return false;
                }
            }
        }
    }
  
    public int compareTo(Edge e){
        if (this.xVal < e.xVal){
            return -1;
        } else if (this.xVal == e.xVal){
            return 0;
        } else {
            return 1;
        }
    }
  
}


Node.java

public class Node {
    public float x;
    public float y;
    public Node(float xx, float yy){
        x = xx;
        y = yy;
    }
    public float returnX(){
        return x;
    }
    public float returnY(){
        return y;
    }
  
}

PolygonOpenGLFiller.java
package polygon.opengl.filler;

import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;

public class PolygonOpenGLFiller {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    PolygonOpenGLFiller work = new PolygonOpenGLFiller();
      
        work.start();    }
  
    public void start() {
try {
    createWindow();
    initGL();
    render();} catch (Exception e) {
e.printStackTrace();}
}
  
    public void createWindow() throws Exception{
        Display.setFullscreen(false);
        Display.setDisplayMode(new DisplayMode(640, 480));
        Display.setTitle("Program 1");
      
        Display.create();
    }
  
    public void initGL() throws Exception{
        glClearColor(0.0f,0.0f,0.0f,0.0f);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-1280, 1280, -960, 960, 1, -1);
        glMatrixMode(GL_MODELVIEW);
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    }
  
    private void render() {
while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
    try{
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glLoadIdentity();
        glColor3f(1.0f,1.0f,0.0f);
        glPointSize(1);
        glBegin(GL_POINTS);
        File file = new File("coordinates.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        Scanner sc = new Scanner(br);
        ArrayList<Node> list = new ArrayList<Node>();
        String check = "";
        String hold = "";
        ArrayList<String> holdForm = new ArrayList<String>();
        char c;
        Scanner b;
        boolean Transformation = false;
            boolean newPoly = false;
        while (sc.hasNext()){
            if (!newPoly){
            hold = sc.nextLine();
            c = hold.charAt(0);
            hold = hold.replaceAll(",", " ");
            b = new Scanner(hold);}
                else {
                c = check.charAt(0);
                hold = check;
                hold = hold.replaceAll(",", " ");
                b = new Scanner(hold);
                Transformation = false;
                newPoly = false;
              
              
            }
            if (c=='P'){
                String newhold = hold.substring(1);
                b = new Scanner(newhold);
                glColor3f(b.nextFloat(), b.nextFloat(), b.nextFloat());
            } else if (Character.isDigit(c)){
                float holdx = b.nextFloat();
                float holdy = b.nextFloat();
                list.add(new Node(holdx, holdy));
              
            } else if (c == 'T'){
                Transformation = true;
                holdForm.removeAll(holdForm);
                while (sc.hasNext()){
                    check = sc.nextLine();
                    if (check.charAt(0)=='P'){
                        //Take off tranaforms if you don't want the transforms
                        Transform(list, holdForm);
                        Fill(list);
                        newPoly = true;
                        list = new ArrayList<Node>();
                        break;
                    }
                    holdForm.add(check);
                  
                }
              
            }
        }
        //Take off tranaforms if you don't want the transforms
       Transform(list, holdForm);
        Fill(list);
        System.out.println("Done");
     //   Fill(list);
        glEnd();
        Display.update();
        Display.sync(60);
        }catch(Exception e){
        }
  
}
    }

    public void Transform(ArrayList<Node> list, ArrayList<String> action){
      
        for (int i = 0; i <action.size(); i++){
            if (action.get(i).charAt(0) == 'r'){
                Scanner sc = new Scanner(action.get(i).substring(1));
                Rotate(list, sc.nextFloat(), sc.nextFloat(), sc.nextFloat());
            } else if (action.get(i).charAt(0) == 't'){
                Scanner sc = new Scanner(action.get(i).substring(1));
                Translate(list, sc.nextFloat(), sc.nextFloat());
            } else {
               Scanner sc = new Scanner(action.get(i).substring(1));
                Scaling(list, sc.nextFloat(), sc.nextFloat(),sc.nextFloat(),sc.nextFloat());
            }
        }
      
      
    }
  
    public void Translate(ArrayList<Node> list, float x, float y){
        for (int i = 0; i < list.size(); i++){
            list.get(i).x += x;
            list.get(i).y += y;
        }
    }
  
    public float getCenterx(ArrayList<Node> list){
        float minx= 0;
        float maxx= 0;
        float miny =0;
        float maxy =0;
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                minx = list.get(i).x;
            } else {
                if (list.get(i).x < minx){
                    minx = list.get(i).x;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                miny = list.get(i).y;
            } else {
                if (list.get(i).y < minx){
                    miny = list.get(i).y;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                maxx = list.get(i).x;
            } else {
                if (list.get(i).x > maxx){
                    maxx = list.get(i).x;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                maxy = list.get(i).y;
            } else {
                if (list.get(i).y > maxy){
                    maxx = list.get(i).y;
                }
            }
        }
        return (minx +((maxx - minx)/2));
      
    }
  
    public float getCentery(ArrayList<Node> list){
        float minx= 0;
        float maxx= 0;
        float miny =0;
        float maxy =0;
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                minx = list.get(i).x;
            } else {
                if (list.get(i).x < minx){
                    minx = list.get(i).x;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                miny = list.get(i).y;
            } else {
                if (list.get(i).y < minx){
                    miny = list.get(i).y;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                maxx = list.get(i).x;
            } else {
                if (list.get(i).x > maxx){
                    maxx = list.get(i).x;
                }
            }
        }
      
        for (int i = 0; i < list.size(); i++){
            if (i==0){
                maxy = list.get(i).y;
            } else {
                if (list.get(i).y > maxy){
                    maxx = list.get(i).y;
                }
            }
        }
        return (miny + ((maxy-miny)/2));
      
    }
  
  
    public void Rotate(ArrayList<Node> list, float degree, float pivot, float pivot2){
        float centerx = getCenterx(list);
        float centery = getCentery(list);
        for (int i = 0 ; i < list.size(); i++){
            float[] holder = {list.get(i).x, list.get(i).y};
            AffineTransform.getRotateInstance(Math.toRadians(degree), pivot, pivot2).transform(holder, 0, holder, 0, 1);
            list.get(i).x = holder[0];
            list.get(i).y = holder[1];
//            list.get(i).x = (int)(pivot + (list.get(i).x - pivot)*Math.cos(degree) - (list.get(i).y - pivot2)*Math.sin(degree));
//            list.get(i).y = (int)(pivot2 + (list.get(i).x -pivot)*Math.sin(degree) + (list.get(i).y - pivot2)*Math.cos(degree));
        }
    }
  
    public void Scaling(ArrayList<Node> list, float scale, float scale2, float pivot, float pivot2){
        float centerx = getCenterx(list);
        float centery = getCentery(list);
        for (int i = 0 ; i < list.size(); i++){
            list.get(i).x = Math.round(((list.get(i).x - pivot)*scale)+pivot);
            list.get(i).y = Math.round(((list.get(i).y - pivot2)*scale2)+pivot2);
        }
    }


   public void changeC(float x, float y, float z){
        glColor3f(x,y,z);
    }

   public void Fill(ArrayList<Node> list){
        ArrayList<Edge> All = new ArrayList<Edge>();
        ArrayList<Edge> Global = new ArrayList<Edge>();
        ArrayList<Edge> Active = new ArrayList<Edge>();
        for (int i = 0; i < list.size(); i++){
            if (i == (list.size()-1)){float currentymin;
                float currentymax;
                float currentxval;
                float currentslope;
                int check = findYMin(list.get(i), list.get(0));
                if (check==0){
                  
                    currentymin = list.get(0).y;
                    currentxval = list.get(0).x;
                } else if (check==1){
                    currentymin = list.get(i).y;
                    currentxval = list.get(i).x;
                } else {
                    currentymin = list.get(0).y;
                    currentxval = list.get(0).x;
                }
              
                int check2 = findYMax(list.get(i), list.get(0));
                if (check2==0){
                    currentymax = list.get(0).y;
                } else if (check2==1){
                    currentymax = list.get(i).y;
                } else {
                    currentymax = list.get(0).y;
                }
              
                currentslope = inverseSlope(list.get(i), list.get(0));
                All.add(new Edge(currentymin, currentymax, currentxval, currentslope));
              
            } else {
                float currentymin;
                float currentymax;
                float currentxval;
                float currentslope;
                int check = findYMin(list.get(i), list.get(i+1));
                if (check==0){
                    currentymin = list.get(i+1).y;
                    currentxval = list.get(i+1).x;
                } else if (check==1){
                    currentymin = list.get(i).y;
                    currentxval = list.get(i).x;
                } else {
                    currentymin = list.get(i+1).y;
                    currentxval = list.get(i+1).x;
                }
              
                int check2 = findYMax(list.get(i), list.get(i+1));
                if (check2==0){
                    currentymax = list.get(i+1).y;
                } else if (check2==1){
                    currentymax = list.get(i).y;
                } else {
                    currentymax = list.get(i+1).y;
                }
              
                currentslope = inverseSlope(list.get(i), list.get(i+1));
                All.add(new Edge(currentymin, currentymax, currentxval, currentslope));
              
              
            }
          
        }
      
//        for (int i = 0; i < All.size(); i++){
//            System.out.println(All.get(i).yMin);
//        }
        //Global Table Move
            for (int i = 0; i < All.size(); i++){
                if (i==0){
                    if (checkIf(All.get(0))){
                        Global.add(All.get(0));
                    }
                } else {
                    if (checkIf(All.get(i))){
                        for (int j = Global.size()-1; j >= 0; j--){
                            if (All.get(i).compare(Global.get(j))){
                                if (j==0){
                                    Global.add(0, All.get(i));
                                }
                            } else {
                                Global.add(j+1, All.get(i));
                                break;
                            }
                        }
                    }
                }
            }
          
//            for (int i = 0; i < Global.size(); i++){
//            System.out.println(Global.get(i).yMin);
//        }
            //Active Table Start
            float Scanline = Global.get(0).yMin;
            boolean Parity = true;
            float max = 0;
            for (int i = 0; i < Global.size(); i++){
                if (i==0){
                    max = Global.get(i).yMax;
                } else {
                    if (Global.get(i).yMax > max){
                        max = Global.get(i).yMax;
                    }
                }
            }
            for (int i = (int) Scanline; i < max; i++){
                for (int j = 0; j < Global.size(); ){
                    if (Global.get(j).yMin!=i){
                        break;
                    }else{
                        Active.add(Global.get(j));
                        Global.remove(j);
                    }
                }
//                for (int z = 0; z < Global.size(); z++){
//                    System.out.println(Global.get(z).yMin);
//                }
              
                 Collections.sort(Active, new Comparator<Edge>(){
                    @Override
                    public int compare(Edge e , Edge x){
                    return e.compareTo(x);
                     }
                        });
                FillStuff(Active, i);
              
                for (int j = Active.size()-1; j >-1; j--){
                    if (Active.get(j).yMax <= i+1){
                        Active.remove(j);
                    }
                }
                             
            }
          
          
          
      
   }

   public void FillStuff(ArrayList<Edge> list, int y){
       boolean Parity = false;
//       for (int i = 0; i < list.size(); i++){
//           System.out.println(list.get(i).yMax);
//       }
     
       for(int i = 0; i < list.size(); i++){
           Parity = !Parity;
           if (Parity){
               float xMax = list.get(i+1).xVal;
             
               for (float j = list.get(i).xVal; j <= xMax; j++){
                   glVertex2f(j, y);
               }
           }
         
       }
       for (int j = 0; j < list.size(); j++){
               list.get(j).xVal = list.get(j).xVal + list.get(j).slop;
           }
     
       Collections.sort(list, new Comparator<Edge>(){
           @Override
           public int compare(Edge e , Edge x){
               return e.compareTo(x);
           }
       });
   }

   public boolean checkIf(Edge e){
       if (e.slop==1999999){
           return false;
       } else {
           return true;
       }
   }

   public int findYMin(Node x, Node y){
       if (x.y < y.y){
           return 1;
       } else if (y.y < x.y){
           return 2;
       } else {
           return 0;
       }
   }

   public int findYMax(Node x, Node y){
       if (x.y > y.y){
           return 1;
       } else if (y.y > x.y){
           return 2;
       } else {
           return 0;
       }
   }

   public float inverseSlope(Node x, Node y){
       float dx = y.x - x.x;
       float dy = y.y - x.y;
       if (dy == 0){
           return 1999999;
       } else {
           return dx/dy;
       }
   }



   public void makePoly(ArrayList<Node> list){
       glBegin(GL_POLYGON);
        for (int i = (list.size()-1); i < 0; i--){
            glVertex2f(list.get(i).x, list.get(i).y);
        }
       glEnd();
   }
}

Add a comment
Know the answer?
Add Answer to:
Write a Java program which uses the LWJGL library to draw a window of 640x480 (with...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • MATLAB PROGRAM FOR THE FOLLOWING PROBLEM Using Matlab write a program that will plot the pressure...

    MATLAB PROGRAM FOR THE FOLLOWING PROBLEM Using Matlab write a program that will plot the pressure signal, the perceived pressure signal, the resistance and the output voltage as functions of time, for Problem 1.30 in the textbook. (B) Using Matlab show a plot with the output voltage range if we happen to know that the transfer function (gain) has an uncertainty of 15% and the time constant has an uncertainty of 10%. (Note: the solution of the problem is provided...

  • One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we...

    One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we will look at ways in which we can model geometric objects comprised of polygons. Here, we want to examine the interactive part. Let’s start by writing an application that will let the user specify a series of axis- aligned rectangles interactively. Each rectangle can be defined by two mouse positions at diagonally opposite corners. Consider the event listener canvas.addEventListener("mousedown", function() { gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer); if...

  • ***** running late, mere 3 hours left for due time, please help ** #needed in c++...

    ***** running late, mere 3 hours left for due time, please help ** #needed in c++ #inputfile MinPath2.txt 0   SF 1   LA 2   DALLAS 3   CONCORD 4   PHOENIX 5   CHICAGO 6   ST LOUIS 7   BOSTON 8   NY 9   LONDON 10   PARIS 11   TOKYO 12   BANGKOK 13   MEXICO CITY 14   MONTREAL -1   0   1   40 0   2   100 0   4   130 0   8   200 0   9   800 0   10   900 1   2   50 1   3   80 1   4   70 1   8  ...

  • in Java Write a program DFSTrace that contains a version of a depth first search that...

    in Java Write a program DFSTrace that contains a version of a depth first search that prints a trace of its traversal. Write a public static method: public static void dfsPrintTrace(Graph g) { // *** Declare and initialize the marked array. dfsPrintTrace(g, 0, marked, 0); } This method calls a private method: private static void dfsPrintTrace(Graph g, int start, boolean[] marked, int indent) All references to a method below refer to this second method. Every message printed should be preceded...

  • Write a program which will Ask the user a series of questions using the Scanner object Based on t...

    Write a program which will Ask the user a series of questions using the Scanner object Based on the input, draw a grid of star figures on the DrawingPanel You program should ask your user: . What R, G & B values to create a color to draw the figure? How many stars across should the fgure be? How many stars tall should the figure be? Note that your program does not need to error check the users responses Your...

  • How can I solved my Java Program for DelivC

    //Graph Class: import java.util.ArrayList; //Graph is a class whose objects represent graphs.  public class Graph {     ArrayList<Node> nodeList;     ArrayList<Edge> edgeList;         public Graph() {         nodeList = new ArrayList<Node>();         edgeList = new ArrayList<Edge>();         }         public ArrayList<Node> getNodeList() {         return nodeList;    }    public ArrayList<Edge> getEdgeList() {         return edgeList;    }    public void addNode(Node n) {         nodeList.add(n);    }    public void addEdge(Edge e) {         edgeList.add(e);    }    public String toString() {         String s = "Graph g.\n";         if (nodeList.size() > 0) {             for (Node n : nodeList) {         // Print node info         String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";         s = s.concat(t);         }         s = s.concat("\n");             }         return s;     }  } // Node Class: import java.util.ArrayList;  // Node is a class whose objects represent nodes (a.k.a., vertices) in the graph.  public class Node {    String name;     String val; // The value of the Node     String abbrev; // The abbreviation for the Node     ArrayList<Edge> outgoingEdges;     ArrayList<Edge> incomingEdges;             String color; //Create the color of the TYPE Node List     int start; //Create the Starting Time     int end; //Create the Ending Time             public Node( String theAbbrev ) {         setAbbrev( theAbbrev );         val = null;         name = null;         outgoingEdges = new ArrayList<Edge>();         incomingEdges = new ArrayList<Edge>();     }         public String getAbbrev() {         return abbrev;     }         public String getName() {         return name;     }         public String getVal() {         return val;     }         public ArrayList<Edge> getOutgoingEdges() {         return outgoingEdges;     }         public ArrayList<Edge> getIncomingEdges() {         return incomingEdges;...

  • Write a WebGL program that displays a rotating pendulum. The pendulum bob is free to rotate...

    Write a WebGL program that displays a rotating pendulum. The pendulum bob is free to rotate through 360 degrees about an anchor point at the center of the canvas. The pendulum has the following three components. 1) The anchor point is a green square centered at the origin (0,0) with point size = 5 pixels. 2) The bob is a blue hexagon of radius r = 0.1. Render this with a triangle fan centered at the origin (along with a...

  • Copy the following java codes and compile //// HighArray.java //// HighArrayApp.java Study carefully the design and...

    Copy the following java codes and compile //// HighArray.java //// HighArrayApp.java Study carefully the design and implementation HighArray class and note the attributes and its methods.    Create findAll method which uses linear search algorithm to return all number of occurrences of specified element. /** * find an element from array and returns all number of occurrences of the specified element, returns 0 if the element does not exit. * * @param foundElement   Element to be found */ int findAll(int...

  • How do I flip this shape across the y-axis using processing? h_190527e | Processing 3.5.3 t Sketch Debug Too...

    How do I flip this shape across the y-axis using processing? h_190527e | Processing 3.5.3 t Sketch Debug Tools Help sketch_190527e sketch 190527e float angleoffsetAnchor 13; vertex(centerx, centerY); float nappedStepsForLerp-map(steps, minstepsValue, maaStepsvalue, θ, 1); color lowSteps - color(9, 10, 200); color highSteps -color(29e, o, e); lor mappedDayColor lerpColor (Lowsteps, highSteps, mappedStepsForLerp); fill (mappedDayColor); float anchorPointx1 - centerx distanceoffsetAnchor sin(angle radians(angleoffsetAnchor)) float anchorPointy centerY distance0ffsetAnchor cos (angle radíans (angleOffsetAnchor)) 54 56float controlPointx - centerx + distanceoffset sin(angle); at controlPointy centerV +...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT