<< Chapter < Page Chapter >> Page >

Listing 32 . Source code for the program named StringArt03.

/*StringArt03.java Copyright 2008, R.G.BaldwinRevised 02/22/08 This is a 3D version of a string art program that supportsrotation in three dimensions. This program produces a 3D string art image by connectingvarious points that are equally spaced on the circumference of a circle.Initially, the circle is on the x-y plane centered on the origin. There are six points on the circle connected bylines forming a hexagon, The lines that connect the points are different colors. The radius of the circle is 50units. The points at the vertices of the hexagon are not drawn, but the lines that connect the vertices are drawn.A GUI is provided that allows the user to specify the following items and click a Replot button to cause thedrawing to change: Number PointsNumber Loops Rotate around Z (deg)Rotate around X (deg) Rotate around Y (deg)X Anchor point Y Anchor pointZ Anchor point Changing the number of points causes the number ofvertices that describe the geometric object to change. Changing the number of loops causes the number of linesthat are drawn to connect the vertices to change. For avalue of 1, each vertex is connected to the one next to it. For a value of 2, additional lines are drawnconnecting every other vertex. For a value of 3, additional lines are drawn connecting every third vertex,etc. The image can be rotated in any or all of threedimensions around an anchor point. Entering a non-zero value in one or more of the Rotate fields causes theimage to be rotated by the specified angle or angles around the anchor point. The anchor point is initiallyspecified to be at the origin, but the location of the anchor point can be changed by the user. If the anchorpoint is at the origin, the image is rotated around the origin. Otherwise, the image is rotated around the pointin 3D space specified by the anchor point. The anchor point is drawn in black.The rotation angle is specified in degrees with a positive angle being given by the right-hand rule as applied to theaxis around which the image is being rotated. The rotational effects are cumulative. The image is firstrotated around the anchor point in a direction consistent with rotation around the z-axis (rotation in the x-yplane). Then that rotated image is rotated in a direction consistent with rotation around the x-axis (rotation inthe y-z plane). Finally, the previously rotated image is rotated in a direction consistent with rotation around they-axis (rotation in the x-z plane). It is important to note, however, that the actual rotation is around theanchor point and not around the origin unless the anchor point is at the origin.The number of points is initially set to six and the number of loops is initially set to one. Making thenumber of points larger and making the number of loops larger produces many interesting patterns.Tested using JDK 1.6 under WinXP. *********************************************************/import java.awt.*; import javax.swing.*;import java.awt.geom.*; import java.awt.event.*;class StringArt03{ public static void main(String[]args){ GUI guiObj = new GUI();}//end main }//end controlling class StringArt03//======================================================// class GUI extends JFrame implements ActionListener{//Specify the horizontal and vertical size of a JFrame // object.int hSize = 300; int vSize = 470;Image osi;//an off-screen image int osiWidth;//off-screen image widthint osiHeight;//off-screen image height MyCanvas myCanvas;//a subclass of CanvasGraphics2D g2D;//Off-screen graphics context. JTextField numberPointsField;//User input field.JTextField loopsField;//User input field. int numberPoints = 6;//Can be modified by the user.int loopLim = 1;//Can be modified by the user.JTextField zRotationField;//User input field JTextField xRotationField;//User input fieldJTextField yRotationField;//User input field double zRotation;//Rotation around z in degrees.double xRotation;//Rotation around x in degrees. double yRotation;//Rotation around y in degreesJTextField xAnchorPointField;//User input fieldJTextField yAnchorPointField;//User input field JTextField zAnchorPointField;//User input fielddouble xAnchorPoint;//Rotation anchor point. double yAnchorPoint;//Rotation anchor point.double zAnchorPoint;//Rotation anchor point.//The following variable is used to refer to an array// object containing the points that define the // vertices of a geometric object.GM01.Point3D[] points;//----------------------------------------------------//GUI(){//constructor//Instantiate the array object that will be used to // store the points that define the vertices of the// geometric object. points = new GM01.Point3D[numberPoints];//Set JFrame size, title, and close operation. setSize(hSize,vSize);setTitle("Copyright 2008,R.G.Baldwin"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Instantiate the user input components.numberPointsField =new JTextField("6"); loopsField = new JTextField("1");zRotationField = new JTextField("0"); xRotationField = new JTextField("0");yRotationField = new JTextField("0"); xAnchorPointField = new JTextField("0");yAnchorPointField = new JTextField("0"); zAnchorPointField = new JTextField("0");JButton button = new JButton("Replot"); //Instantiate a JPanel that will house the user input// components and set its layout manager. JPanel controlPanel = new JPanel();controlPanel.setLayout(new GridLayout(0,2)); //Add the user input components and appropriate labels// to the control panel. controlPanel.add(new JLabel(" Number Points"));controlPanel.add(numberPointsField); controlPanel.add(new JLabel(" Number Loops"));controlPanel.add(loopsField); controlPanel.add(new JLabel(" Rotate around Z (deg)")); controlPanel.add(zRotationField);controlPanel.add(new JLabel( " Rotate around X (deg)"));controlPanel.add(xRotationField); controlPanel.add(new JLabel(" Rotate around Y (deg)")); controlPanel.add(yRotationField);controlPanel.add(new JLabel(" X anchor point")); controlPanel.add(xAnchorPointField);controlPanel.add(new JLabel(" Y anchor point")); controlPanel.add(yAnchorPointField);controlPanel.add(new JLabel(" Z anchor point")); controlPanel.add(zAnchorPointField);controlPanel.add(button); //Add the control panel to the SOUTH position in the// JFrame. this.getContentPane().add(BorderLayout.SOUTH,controlPanel);//Create a new drawing canvas and add it to the // CENTER of the JFrame above the control panel.myCanvas = new MyCanvas(); this.getContentPane().add(BorderLayout.CENTER,myCanvas); //This object must be visible before you can get an// off-screen image. It must also be visible before // you can compute the size of the canvas.setVisible(true);//Make the size of the off-screen image match the // size of the canvas.osiWidth = myCanvas.getWidth(); osiHeight = myCanvas.getHeight();//Create an off-screen image and get a graphics// context on it. osi = createImage(osiWidth,osiHeight);g2D = (Graphics2D)(osi.getGraphics());//Erase the off-screen image, establish the origin, // and draw the axessetCoordinateFrame(g2D,true); //Create the Point3D objects that define the geometric// object and manipulate them to produce the desired // results.drawOffScreen(g2D);//Register this object as an action listener on the // button.button.addActionListener(this); //Cause the overridden paint method belonging to// myCanvas to be executed. myCanvas.repaint();}//end constructor//----------------------------------------------------////The purpose of this method is to Create the Point3D // objects that define the vertices of a geometric// object and manipulate them to produce the desired // results.void drawOffScreen(Graphics2D g2D){ //Erase the off-screen image and draw new axes, but// don't move the origin. setCoordinateFrame(g2D,false);//Create a set of Point3D objects that specify // locations on the circumference of a circle that// is in the x-y plane with a radius of 50 units. Save // references to the Point3D objects in an array.for(int cnt = 0;cnt<numberPoints;cnt++){ points[cnt]= new GM01.Point3D( new GM01.ColMatrix3D(50*Math.cos((cnt*360/numberPoints)*Math.PI/180), 50*Math.sin((cnt*360/numberPoints)*Math.PI/180),0.0)); //The following ColMatrix3D object must be populated// with three rotation angles in degrees that // specify the following rotational angles in order// according to the right-hand rule as applied to // the indicated axis.// Rotate around z // Rotate around x// Rotate around y GM01.ColMatrix3D angles = new GM01.ColMatrix3D( zRotation,xRotation,yRotation);//The following object contains the 3D coordinates// of the point around which the rotations will // take place.GM01.Point3D anchorPoint = new GM01.Point3D( new GM01.ColMatrix3D(xAnchorPoint,yAnchorPoint,zAnchorPoint)); //Draw the anchorPoint in BLACK.g2D.setColor(Color.BLACK); anchorPoint.draw(g2D);//The following statement causes the rotation to be//performed. points[cnt]= points[cnt].rotate(anchorPoint,angles); }//end for loop//Implement the algorithm that draws lines connecting// points on the geometric object. GM01.Line3D line;//Begin the outer loop.for(int loop = 1;loop<= loopLim;loop++){ //The following variable specifies the array// element containing a point on which a line will // start.int start = -1;//The following variable specifies the number of // points that will be skipped between the starting// point and the ending point for a line. int skip = loop;//The following logic causes the element number to // wrap around when it reaches the end of the// array. while(skip>:= 2*numberPoints-1){ skip -= numberPoints;}//end while loop//The following variable specifies the array // element containing a point on which a line will// end. int end = start + skip;//Begin inner loop. This loop actually constructs // the GM01.Line3D objects and causes visual// manifestations of those objects to be drawn on // the off-screen image. Note the requirement to// wrap around when the element numbers exceed the // length of the array.for(int cnt = 0;cnt<numberPoints;cnt++){ if(start<numberPoints-1){ start++;}else{ //Wrap aroundstart -= (numberPoints-1); }//end elseif(end<numberPoints-1){ end++;}else{ //Wrap around.end -= (numberPoints-1); }//end else//Create some interesting colors.g2D.setColor(new Color(cnt*255/numberPoints, 127+cnt*64/numberPoints,255-cnt*255/numberPoints));//Create a line that connects points on the // geometric object.line = new GM01.Line3D(points[start],points[end]); line.draw(g2D);}//end inner loop }//end outer loop}//end drawOffScreen //----------------------------------------------------////This method is used to set the origin of the // off-screen image to the center and to draw orthogonal// 3D axes on the image that intersect at the origin. //The second parameter is used to determine if the// origin should be translated to the center. private void setCoordinateFrame(Graphics2D g2D,boolean translate){ //Translate the origin to the center if translate is// true. if(translate){GM01.translate(g2D,0.5*osiWidth,-0.5*osiHeight); }//end if//Erase the screeng2D.setColor(Color.WHITE); GM01.fillRect(g2D,-osiWidth/2,osiHeight/2,osiWidth,osiHeight); //Draw x-axis in REDg2D.setColor(Color.RED); GM01.Point3D pointA = new GM01.Point3D(new GM01.ColMatrix3D(-osiWidth/2,0,0)); GM01.Point3D pointB = new GM01.Point3D(new GM01.ColMatrix3D(osiWidth/2,0,0)); new GM01.Line3D(pointA,pointB).draw(g2D);//Draw y-axis in GREENg2D.setColor(Color.GREEN); pointA = new GM01.Point3D(new GM01.ColMatrix3D(0,-osiHeight/2,0)); pointB = new GM01.Point3D(new GM01.ColMatrix3D(0,osiHeight/2,0)); new GM01.Line3D(pointA,pointB).draw(g2D);//Draw z-axis in BLUE. Make its length the same as the// length of the x-axis. g2D.setColor(Color.BLUE);pointA = new GM01.Point3D( new GM01.ColMatrix3D(0,0,-osiWidth/2));pointB = new GM01.Point3D( new GM01.ColMatrix3D(0,0,osiWidth/2));new GM01.Line3D(pointA,pointB).draw(g2D); }//end setCoordinateFrame method//----------------------------------------------------////This method is called to respond to a click on the // button.public void actionPerformed(ActionEvent e){ //Get user input values and use them to modify several// values that control the drawing. numberPoints = Integer.parseInt(numberPointsField.getText()); loopLim = Integer.parseInt(loopsField.getText());//Rotation around z in degrees.zRotation = Double.parseDouble(zRotationField.getText());//Rotation around x in degrees. xRotation =Double.parseDouble(xRotationField.getText()); //Rotation around y in degreesyRotation = Double.parseDouble(yRotationField.getText());//Rotation anchor points xAnchorPoint =Double.parseDouble(xAnchorPointField.getText()); yAnchorPoint =Double.parseDouble(yAnchorPointField.getText()); zAnchorPoint =Double.parseDouble(zAnchorPointField.getText()); //Instantiate a new array object with a length// that matches the new value for numberPoints. points = new GM01.Point3D[numberPoints]; //Draw a new off-screen image based on user inputs.drawOffScreen(g2D); myCanvas.repaint();//Copy off-screen image to canvas.}//end actionPerformed //====================================================////This is an inner class of the GUI class. class MyCanvas extends Canvas{//Override the paint() method. This method will be // called when the JFrame and the Canvas appear on the// screen or when the repaint method is called on the // Canvas object.//The purpose of this method is to display the // off-screen image on the screen.public void paint(Graphics g){ g.drawImage(osi,0,0,this);}//end overridden paint()}//end inner class MyCanvas}//end class GUI //======================================================//

Exercises

Exercise 1

Using Java and the game-math library named GM01 , or using a different programming environment of your choice, write a program that creates and draws a20-level stepped pyramid as shown in Figure 20 .

Each level is a box. The dimensions of the bottom box are:

  • width = 100 pixels
  • height = 200/20 pixels
  • depth = 100 pixels

The height of each box is the same. The decrease in the width and depth dimensions of the boxes is linear going from the largestbox at the bottom to the smallest box at the top.

The sides of the pyramid may be transparent or opaque - your choice.

The bottom box sits on the x-z plane, is centered on the vertical axis, and the sides are parallel with thex and z axes.

Draw the axes in the approximate location shown in Figure 20 in red, green, and blue.

The positive direction for x is to the right. The positive direction for y is up, and the positive direction for z protrudes from the screen (down and to theleft).

Display your name in the drawing in some manner.

Figure 20 Screen output from Exercise 1.

Missing image.

Exercise 2

Beginning with the pyramid that you created in Exercise 1 , create a replica of that pyramid positioned at a point that is twice the width of the bottom box from the origin in the positive x direction.

Draw that pyramid in red as shown in Figure 21 .

Figure 21 Screen output from Exercise 2.

Missing image.

Exercise 3

Beginning with the two pyramids that you created in Exercise 2 , rotate the red pyramid by -30 degrees around an imaginary vertical line at the center of the pyramid as shown in Figure 22 .

Figure 22 Screen output from Exercise 3.

Missing image.

Exercise 4

Beginning with the two pyramids that you created in Exercise 2 , rotate each box around an imaginary vertical line at the center of the pyramid by a negative angle with a progressively greatermagnitude so that the rotation of the bottom box is zero and the rotation of the top box is approximately -85 degrees as shown in Figure 23 . This produces a 3D object similar to a spiral staircase with the length of eachstep being less than the length of the step below it.

Figure 23 Screen output from Exercise 4.

Missing image.

Exercise 5

Beginning with the two pyramids that you created in Exercise 2 , rotate each box in the red pyramid around an imaginary line that is parallel to the z-axis and lies in the x-z plane at the center of the bottom box as shown in Figure 24 .

Make the rotation angles for each box progressively larger in such a way that the rotation of the bottom box is zero and the rotation of the top box isapproximately 28 degrees.

Figure 24 Screen output from Exercise 5.

Missing image.

Exercise 6

Beginning with the two pyramids that you created in Exercise 2 , rotate each box in the red pyramid around the z-axis as shown in Figure 25 .

Make the rotation angles for each box progressively larger in such a way that the rotation of the bottom box is zero and the rotation of the top box isapproximately 28 degrees.

Figure 25 Screen output from Exercise 6.

Missing image.

-end-

Questions & Answers

what is mutation
Janga Reply
what is a cell
Sifune Reply
how is urine form
Sifune
what is antagonism?
mahase Reply
classification of plants, gymnosperm features.
Linsy Reply
what is the features of gymnosperm
Linsy
how many types of solid did we have
Samuel Reply
what is an ionic bond
Samuel
What is Atoms
Daprince Reply
what is fallopian tube
Merolyn
what is bladder
Merolyn
what's bulbourethral gland
Eduek Reply
urine is formed in the nephron of the renal medulla in the kidney. It starts from filtration, then selective reabsorption and finally secretion
onuoha Reply
State the evolution relation and relevance between endoplasmic reticulum and cytoskeleton as it relates to cell.
Jeremiah
what is heart
Konadu Reply
how is urine formed in human
Konadu
how is urine formed in human
Rahma
what is the diference between a cavity and a canal
Pelagie Reply
what is the causative agent of malaria
Diamond
malaria is caused by an insect called mosquito.
Naomi
Malaria is cause by female anopheles mosquito
Isaac
Malaria is caused by plasmodium Female anopheles mosquitoe is d carrier
Olalekan
a canal is more needed in a root but a cavity is a bad effect
Commander
what are pathogens
Don Reply
In biology, a pathogen (Greek: πάθος pathos "suffering", "passion" and -γενής -genēs "producer of") in the oldest and broadest sense, is anything that can produce disease. A pathogen may also be referred to as an infectious agent, or simply a germ. The term pathogen came into use in the 1880s.[1][2
Zainab
A virus
Commander
Definition of respiration
Muhsin Reply
respiration is the process in which we breath in oxygen and breath out carbon dioxide
Achor
how are lungs work
Commander
where does digestion begins
Achiri Reply
in the mouth
EZEKIEL
what are the functions of follicle stimulating harmones?
Rashima Reply
stimulates the follicle to release the mature ovum into the oviduct
Davonte
what are the functions of Endocrine and pituitary gland
Chinaza
endocrine secrete hormone and regulate body process
Achor
while pituitary gland is an example of endocrine system and it's found in the Brain
Achor
what's biology?
Egbodo Reply
Biology is the study of living organisms, divided into many specialized field that cover their morphology, physiology,anatomy, behaviour,origin and distribution.
Lisah
biology is the study of life.
Alfreda
Biology is the study of how living organisms live and survive in a specific environment
Sifune
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Game 2302 - mathematical applications for game development. OpenStax CNX. Jan 09, 2016 Download for free at https://legacy.cnx.org/content/col11450/1.33
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Game 2302 - mathematical applications for game development' conversation and receive update notifications?

Ask